PackageManagerService.java revision 056d6b0069561af5dc16b1c38fc8d18bd876b54b
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.INSTALL_EXTERNAL;
29import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
30import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
31import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT;
32import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
33import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
34import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
35import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
36import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
37import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
38import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
39import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
40import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
41import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
42import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
43import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED;
44import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
45import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
46import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
47import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
48import static android.content.pm.PackageManager.INSTALL_INTERNAL;
49import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
50import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
51import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
52import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
53import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
54import static android.content.pm.PackageManager.MATCH_ALL;
55import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
56import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
57import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
58import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
59import static android.content.pm.PackageManager.PERMISSION_GRANTED;
60import static android.content.pm.PackageParser.isApkFile;
61import static android.os.Process.PACKAGE_INFO_GID;
62import static android.os.Process.SYSTEM_UID;
63import static android.system.OsConstants.O_CREAT;
64import static android.system.OsConstants.O_RDWR;
65import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
66import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER;
67import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
68import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
69import static com.android.internal.util.ArrayUtils.appendInt;
70import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
71import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
72import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
73import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
74import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
75
76import android.Manifest;
77import android.app.ActivityManager;
78import android.app.ActivityManagerNative;
79import android.app.AppGlobals;
80import android.app.IActivityManager;
81import android.app.admin.IDevicePolicyManager;
82import android.app.backup.IBackupManager;
83import android.app.usage.UsageStats;
84import android.app.usage.UsageStatsManager;
85import android.content.BroadcastReceiver;
86import android.content.ComponentName;
87import android.content.Context;
88import android.content.IIntentReceiver;
89import android.content.Intent;
90import android.content.IntentFilter;
91import android.content.IntentSender;
92import android.content.IntentSender.SendIntentException;
93import android.content.ServiceConnection;
94import android.content.pm.ActivityInfo;
95import android.content.pm.ApplicationInfo;
96import android.content.pm.FeatureInfo;
97import android.content.pm.IOnPermissionsChangeListener;
98import android.content.pm.IPackageDataObserver;
99import android.content.pm.IPackageDeleteObserver;
100import android.content.pm.IPackageDeleteObserver2;
101import android.content.pm.IPackageInstallObserver2;
102import android.content.pm.IPackageInstaller;
103import android.content.pm.IPackageManager;
104import android.content.pm.IPackageMoveObserver;
105import android.content.pm.IPackageStatsObserver;
106import android.content.pm.InstrumentationInfo;
107import android.content.pm.IntentFilterVerificationInfo;
108import android.content.pm.KeySet;
109import android.content.pm.ManifestDigest;
110import android.content.pm.PackageCleanItem;
111import android.content.pm.PackageInfo;
112import android.content.pm.PackageInfoLite;
113import android.content.pm.PackageInstaller;
114import android.content.pm.PackageManager;
115import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
116import android.content.pm.PackageManagerInternal;
117import android.content.pm.PackageParser;
118import android.content.pm.PackageParser.ActivityIntentInfo;
119import android.content.pm.PackageParser.PackageLite;
120import android.content.pm.PackageParser.PackageParserException;
121import android.content.pm.PackageStats;
122import android.content.pm.PackageUserState;
123import android.content.pm.ParceledListSlice;
124import android.content.pm.PermissionGroupInfo;
125import android.content.pm.PermissionInfo;
126import android.content.pm.ProviderInfo;
127import android.content.pm.ResolveInfo;
128import android.content.pm.ServiceInfo;
129import android.content.pm.Signature;
130import android.content.pm.UserInfo;
131import android.content.pm.VerificationParams;
132import android.content.pm.VerifierDeviceIdentity;
133import android.content.pm.VerifierInfo;
134import android.content.res.Resources;
135import android.hardware.display.DisplayManager;
136import android.net.Uri;
137import android.os.Binder;
138import android.os.Build;
139import android.os.Bundle;
140import android.os.Debug;
141import android.os.Environment;
142import android.os.Environment.UserEnvironment;
143import android.os.FileUtils;
144import android.os.Handler;
145import android.os.IBinder;
146import android.os.Looper;
147import android.os.Message;
148import android.os.Parcel;
149import android.os.ParcelFileDescriptor;
150import android.os.Process;
151import android.os.RemoteCallbackList;
152import android.os.RemoteException;
153import android.os.SELinux;
154import android.os.ServiceManager;
155import android.os.SystemClock;
156import android.os.SystemProperties;
157import android.os.UserHandle;
158import android.os.UserManager;
159import android.os.storage.IMountService;
160import android.os.storage.StorageEventListener;
161import android.os.storage.StorageManager;
162import android.os.storage.VolumeInfo;
163import android.os.storage.VolumeRecord;
164import android.security.KeyStore;
165import android.security.SystemKeyStore;
166import android.system.ErrnoException;
167import android.system.Os;
168import android.system.StructStat;
169import android.text.TextUtils;
170import android.text.format.DateUtils;
171import android.util.ArrayMap;
172import android.util.ArraySet;
173import android.util.AtomicFile;
174import android.util.DisplayMetrics;
175import android.util.EventLog;
176import android.util.ExceptionUtils;
177import android.util.Log;
178import android.util.LogPrinter;
179import android.util.MathUtils;
180import android.util.PrintStreamPrinter;
181import android.util.Slog;
182import android.util.SparseArray;
183import android.util.SparseBooleanArray;
184import android.util.SparseIntArray;
185import android.util.Xml;
186import android.view.Display;
187
188import dalvik.system.DexFile;
189import dalvik.system.VMRuntime;
190
191import libcore.io.IoUtils;
192import libcore.util.EmptyArray;
193
194import com.android.internal.R;
195import com.android.internal.annotations.GuardedBy;
196import com.android.internal.app.IMediaContainerService;
197import com.android.internal.app.ResolverActivity;
198import com.android.internal.content.NativeLibraryHelper;
199import com.android.internal.content.PackageHelper;
200import com.android.internal.os.IParcelFileDescriptorFactory;
201import com.android.internal.os.SomeArgs;
202import com.android.internal.os.Zygote;
203import com.android.internal.util.ArrayUtils;
204import com.android.internal.util.FastPrintWriter;
205import com.android.internal.util.FastXmlSerializer;
206import com.android.internal.util.IndentingPrintWriter;
207import com.android.internal.util.Preconditions;
208import com.android.server.EventLogTags;
209import com.android.server.FgThread;
210import com.android.server.IntentResolver;
211import com.android.server.LocalServices;
212import com.android.server.ServiceThread;
213import com.android.server.SystemConfig;
214import com.android.server.Watchdog;
215import com.android.server.pm.PermissionsState.PermissionState;
216import com.android.server.pm.Settings.DatabaseVersion;
217import com.android.server.storage.DeviceStorageMonitorInternal;
218
219import org.xmlpull.v1.XmlPullParser;
220import org.xmlpull.v1.XmlPullParserException;
221import org.xmlpull.v1.XmlSerializer;
222
223import java.io.BufferedInputStream;
224import java.io.BufferedOutputStream;
225import java.io.BufferedReader;
226import java.io.ByteArrayInputStream;
227import java.io.ByteArrayOutputStream;
228import java.io.File;
229import java.io.FileDescriptor;
230import java.io.FileNotFoundException;
231import java.io.FileOutputStream;
232import java.io.FileReader;
233import java.io.FilenameFilter;
234import java.io.IOException;
235import java.io.InputStream;
236import java.io.PrintWriter;
237import java.nio.charset.StandardCharsets;
238import java.security.NoSuchAlgorithmException;
239import java.security.PublicKey;
240import java.security.cert.CertificateEncodingException;
241import java.security.cert.CertificateException;
242import java.text.SimpleDateFormat;
243import java.util.ArrayList;
244import java.util.Arrays;
245import java.util.Collection;
246import java.util.Collections;
247import java.util.Comparator;
248import java.util.Date;
249import java.util.Iterator;
250import java.util.List;
251import java.util.Map;
252import java.util.Objects;
253import java.util.Set;
254import java.util.concurrent.CountDownLatch;
255import java.util.concurrent.TimeUnit;
256import java.util.concurrent.atomic.AtomicBoolean;
257import java.util.concurrent.atomic.AtomicInteger;
258import java.util.concurrent.atomic.AtomicLong;
259
260/**
261 * Keep track of all those .apks everywhere.
262 *
263 * This is very central to the platform's security; please run the unit
264 * tests whenever making modifications here:
265 *
266mmm frameworks/base/tests/AndroidTests
267adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
268adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
269 *
270 * {@hide}
271 */
272public class PackageManagerService extends IPackageManager.Stub {
273    static final String TAG = "PackageManager";
274    static final boolean DEBUG_SETTINGS = false;
275    static final boolean DEBUG_PREFERRED = false;
276    static final boolean DEBUG_UPGRADE = false;
277    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
278    private static final boolean DEBUG_BACKUP = true;
279    private static final boolean DEBUG_INSTALL = false;
280    private static final boolean DEBUG_REMOVE = false;
281    private static final boolean DEBUG_BROADCASTS = false;
282    private static final boolean DEBUG_SHOW_INFO = false;
283    private static final boolean DEBUG_PACKAGE_INFO = false;
284    private static final boolean DEBUG_INTENT_MATCHING = false;
285    private static final boolean DEBUG_PACKAGE_SCANNING = false;
286    private static final boolean DEBUG_VERIFY = false;
287    private static final boolean DEBUG_DEXOPT = false;
288    private static final boolean DEBUG_ABI_SELECTION = false;
289
290    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = Build.IS_DEBUGGABLE;
291
292    private static final int RADIO_UID = Process.PHONE_UID;
293    private static final int LOG_UID = Process.LOG_UID;
294    private static final int NFC_UID = Process.NFC_UID;
295    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
296    private static final int SHELL_UID = Process.SHELL_UID;
297
298    // Cap the size of permission trees that 3rd party apps can define
299    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
300
301    // Suffix used during package installation when copying/moving
302    // package apks to install directory.
303    private static final String INSTALL_PACKAGE_SUFFIX = "-";
304
305    static final int SCAN_NO_DEX = 1<<1;
306    static final int SCAN_FORCE_DEX = 1<<2;
307    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
308    static final int SCAN_NEW_INSTALL = 1<<4;
309    static final int SCAN_NO_PATHS = 1<<5;
310    static final int SCAN_UPDATE_TIME = 1<<6;
311    static final int SCAN_DEFER_DEX = 1<<7;
312    static final int SCAN_BOOTING = 1<<8;
313    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
314    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
315    static final int SCAN_REQUIRE_KNOWN = 1<<12;
316    static final int SCAN_MOVE = 1<<13;
317    static final int SCAN_INITIAL = 1<<14;
318
319    static final int REMOVE_CHATTY = 1<<16;
320
321    private static final int[] EMPTY_INT_ARRAY = new int[0];
322
323    /**
324     * Timeout (in milliseconds) after which the watchdog should declare that
325     * our handler thread is wedged.  The usual default for such things is one
326     * minute but we sometimes do very lengthy I/O operations on this thread,
327     * such as installing multi-gigabyte applications, so ours needs to be longer.
328     */
329    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
330
331    /**
332     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
333     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
334     * settings entry if available, otherwise we use the hardcoded default.  If it's been
335     * more than this long since the last fstrim, we force one during the boot sequence.
336     *
337     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
338     * one gets run at the next available charging+idle time.  This final mandatory
339     * no-fstrim check kicks in only of the other scheduling criteria is never met.
340     */
341    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
342
343    /**
344     * Whether verification is enabled by default.
345     */
346    private static final boolean DEFAULT_VERIFY_ENABLE = true;
347
348    /**
349     * The default maximum time to wait for the verification agent to return in
350     * milliseconds.
351     */
352    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
353
354    /**
355     * The default response for package verification timeout.
356     *
357     * This can be either PackageManager.VERIFICATION_ALLOW or
358     * PackageManager.VERIFICATION_REJECT.
359     */
360    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
361
362    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
363
364    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
365            DEFAULT_CONTAINER_PACKAGE,
366            "com.android.defcontainer.DefaultContainerService");
367
368    private static final String KILL_APP_REASON_GIDS_CHANGED =
369            "permission grant or revoke changed gids";
370
371    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
372            "permissions revoked";
373
374    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
375
376    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
377
378    /** Permission grant: not grant the permission. */
379    private static final int GRANT_DENIED = 1;
380
381    /** Permission grant: grant the permission as an install permission. */
382    private static final int GRANT_INSTALL = 2;
383
384    /** Permission grant: grant the permission as an install permission for a legacy app. */
385    private static final int GRANT_INSTALL_LEGACY = 3;
386
387    /** Permission grant: grant the permission as a runtime one. */
388    private static final int GRANT_RUNTIME = 4;
389
390    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
391    private static final int GRANT_UPGRADE = 5;
392
393    /** Canonical intent used to identify what counts as a "web browser" app */
394    private static final Intent sBrowserIntent;
395    static {
396        sBrowserIntent = new Intent();
397        sBrowserIntent.setAction(Intent.ACTION_VIEW);
398        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
399        sBrowserIntent.setData(Uri.parse("http:"));
400    }
401
402    final ServiceThread mHandlerThread;
403
404    final PackageHandler mHandler;
405
406    /**
407     * Messages for {@link #mHandler} that need to wait for system ready before
408     * being dispatched.
409     */
410    private ArrayList<Message> mPostSystemReadyMessages;
411
412    final int mSdkVersion = Build.VERSION.SDK_INT;
413
414    final Context mContext;
415    final boolean mFactoryTest;
416    final boolean mOnlyCore;
417    final boolean mLazyDexOpt;
418    final long mDexOptLRUThresholdInMills;
419    final DisplayMetrics mMetrics;
420    final int mDefParseFlags;
421    final String[] mSeparateProcesses;
422    final boolean mIsUpgrade;
423
424    // This is where all application persistent data goes.
425    final File mAppDataDir;
426
427    // This is where all application persistent data goes for secondary users.
428    final File mUserAppDataDir;
429
430    /** The location for ASEC container files on internal storage. */
431    final String mAsecInternalPath;
432
433    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
434    // LOCK HELD.  Can be called with mInstallLock held.
435    @GuardedBy("mInstallLock")
436    final Installer mInstaller;
437
438    /** Directory where installed third-party apps stored */
439    final File mAppInstallDir;
440
441    /**
442     * Directory to which applications installed internally have their
443     * 32 bit native libraries copied.
444     */
445    private File mAppLib32InstallDir;
446
447    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
448    // apps.
449    final File mDrmAppPrivateInstallDir;
450
451    // ----------------------------------------------------------------
452
453    // Lock for state used when installing and doing other long running
454    // operations.  Methods that must be called with this lock held have
455    // the suffix "LI".
456    final Object mInstallLock = new Object();
457
458    // ----------------------------------------------------------------
459
460    // Keys are String (package name), values are Package.  This also serves
461    // as the lock for the global state.  Methods that must be called with
462    // this lock held have the prefix "LP".
463    @GuardedBy("mPackages")
464    final ArrayMap<String, PackageParser.Package> mPackages =
465            new ArrayMap<String, PackageParser.Package>();
466
467    // Tracks available target package names -> overlay package paths.
468    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
469        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
470
471    /**
472     * Tracks new system packages [receiving in an OTA] that we expect to
473     * find updated user-installed versions. Keys are package name, values
474     * are package location.
475     */
476    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
477
478    final Settings mSettings;
479    boolean mRestoredSettings;
480
481    // System configuration read by SystemConfig.
482    final int[] mGlobalGids;
483    final SparseArray<ArraySet<String>> mSystemPermissions;
484    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
485
486    // If mac_permissions.xml was found for seinfo labeling.
487    boolean mFoundPolicyFile;
488
489    // If a recursive restorecon of /data/data/<pkg> is needed.
490    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
491
492    public static final class SharedLibraryEntry {
493        public final String path;
494        public final String apk;
495
496        SharedLibraryEntry(String _path, String _apk) {
497            path = _path;
498            apk = _apk;
499        }
500    }
501
502    // Currently known shared libraries.
503    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
504            new ArrayMap<String, SharedLibraryEntry>();
505
506    // All available activities, for your resolving pleasure.
507    final ActivityIntentResolver mActivities =
508            new ActivityIntentResolver();
509
510    // All available receivers, for your resolving pleasure.
511    final ActivityIntentResolver mReceivers =
512            new ActivityIntentResolver();
513
514    // All available services, for your resolving pleasure.
515    final ServiceIntentResolver mServices = new ServiceIntentResolver();
516
517    // All available providers, for your resolving pleasure.
518    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
519
520    // Mapping from provider base names (first directory in content URI codePath)
521    // to the provider information.
522    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
523            new ArrayMap<String, PackageParser.Provider>();
524
525    // Mapping from instrumentation class names to info about them.
526    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
527            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
528
529    // Mapping from permission names to info about them.
530    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
531            new ArrayMap<String, PackageParser.PermissionGroup>();
532
533    // Packages whose data we have transfered into another package, thus
534    // should no longer exist.
535    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
536
537    // Broadcast actions that are only available to the system.
538    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
539
540    /** List of packages waiting for verification. */
541    final SparseArray<PackageVerificationState> mPendingVerification
542            = new SparseArray<PackageVerificationState>();
543
544    /** Set of packages associated with each app op permission. */
545    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
546
547    final PackageInstallerService mInstallerService;
548
549    private final PackageDexOptimizer mPackageDexOptimizer;
550
551    private AtomicInteger mNextMoveId = new AtomicInteger();
552    private final MoveCallbacks mMoveCallbacks;
553
554    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
555
556    // Cache of users who need badging.
557    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
558
559    /** Token for keys in mPendingVerification. */
560    private int mPendingVerificationToken = 0;
561
562    volatile boolean mSystemReady;
563    volatile boolean mSafeMode;
564    volatile boolean mHasSystemUidErrors;
565
566    ApplicationInfo mAndroidApplication;
567    final ActivityInfo mResolveActivity = new ActivityInfo();
568    final ResolveInfo mResolveInfo = new ResolveInfo();
569    ComponentName mResolveComponentName;
570    PackageParser.Package mPlatformPackage;
571    ComponentName mCustomResolverComponentName;
572
573    boolean mResolverReplaced = false;
574
575    private final ComponentName mIntentFilterVerifierComponent;
576    private int mIntentFilterVerificationToken = 0;
577
578    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
579            = new SparseArray<IntentFilterVerificationState>();
580
581    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
582            new DefaultPermissionGrantPolicy(this);
583
584    private static class IFVerificationParams {
585        PackageParser.Package pkg;
586        boolean replacing;
587        int userId;
588        int verifierUid;
589
590        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
591                int _userId, int _verifierUid) {
592            pkg = _pkg;
593            replacing = _replacing;
594            userId = _userId;
595            replacing = _replacing;
596            verifierUid = _verifierUid;
597        }
598    }
599
600    private interface IntentFilterVerifier<T extends IntentFilter> {
601        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
602                                               T filter, String packageName);
603        void startVerifications(int userId);
604        void receiveVerificationResponse(int verificationId);
605    }
606
607    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
608        private Context mContext;
609        private ComponentName mIntentFilterVerifierComponent;
610        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
611
612        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
613            mContext = context;
614            mIntentFilterVerifierComponent = verifierComponent;
615        }
616
617        private String getDefaultScheme() {
618            return IntentFilter.SCHEME_HTTPS;
619        }
620
621        @Override
622        public void startVerifications(int userId) {
623            // Launch verifications requests
624            int count = mCurrentIntentFilterVerifications.size();
625            for (int n=0; n<count; n++) {
626                int verificationId = mCurrentIntentFilterVerifications.get(n);
627                final IntentFilterVerificationState ivs =
628                        mIntentFilterVerificationStates.get(verificationId);
629
630                String packageName = ivs.getPackageName();
631
632                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
633                final int filterCount = filters.size();
634                ArraySet<String> domainsSet = new ArraySet<>();
635                for (int m=0; m<filterCount; m++) {
636                    PackageParser.ActivityIntentInfo filter = filters.get(m);
637                    domainsSet.addAll(filter.getHostsList());
638                }
639                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
640                synchronized (mPackages) {
641                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
642                            packageName, domainsList) != null) {
643                        scheduleWriteSettingsLocked();
644                    }
645                }
646                sendVerificationRequest(userId, verificationId, ivs);
647            }
648            mCurrentIntentFilterVerifications.clear();
649        }
650
651        private void sendVerificationRequest(int userId, int verificationId,
652                IntentFilterVerificationState ivs) {
653
654            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
655            verificationIntent.putExtra(
656                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
657                    verificationId);
658            verificationIntent.putExtra(
659                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
660                    getDefaultScheme());
661            verificationIntent.putExtra(
662                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
663                    ivs.getHostsString());
664            verificationIntent.putExtra(
665                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
666                    ivs.getPackageName());
667            verificationIntent.setComponent(mIntentFilterVerifierComponent);
668            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
669
670            UserHandle user = new UserHandle(userId);
671            mContext.sendBroadcastAsUser(verificationIntent, user);
672            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
673                    "Sending IntentFilter verification broadcast");
674        }
675
676        public void receiveVerificationResponse(int verificationId) {
677            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
678
679            final boolean verified = ivs.isVerified();
680
681            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
682            final int count = filters.size();
683            if (DEBUG_DOMAIN_VERIFICATION) {
684                Slog.i(TAG, "Received verification response " + verificationId
685                        + " for " + count + " filters, verified=" + verified);
686            }
687            for (int n=0; n<count; n++) {
688                PackageParser.ActivityIntentInfo filter = filters.get(n);
689                filter.setVerified(verified);
690
691                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
692                        + " verified with result:" + verified + " and hosts:"
693                        + ivs.getHostsString());
694            }
695
696            mIntentFilterVerificationStates.remove(verificationId);
697
698            final String packageName = ivs.getPackageName();
699            IntentFilterVerificationInfo ivi = null;
700
701            synchronized (mPackages) {
702                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
703            }
704            if (ivi == null) {
705                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
706                        + verificationId + " packageName:" + packageName);
707                return;
708            }
709            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
710                    "Updating IntentFilterVerificationInfo for verificationId:" + verificationId);
711
712            synchronized (mPackages) {
713                if (verified) {
714                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
715                } else {
716                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
717                }
718                scheduleWriteSettingsLocked();
719
720                final int userId = ivs.getUserId();
721                if (userId != UserHandle.USER_ALL) {
722                    final int userStatus =
723                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
724
725                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
726                    boolean needUpdate = false;
727
728                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
729                    // already been set by the User thru the Disambiguation dialog
730                    switch (userStatus) {
731                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
732                            if (verified) {
733                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
734                            } else {
735                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
736                            }
737                            needUpdate = true;
738                            break;
739
740                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
741                            if (verified) {
742                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
743                                needUpdate = true;
744                            }
745                            break;
746
747                        default:
748                            // Nothing to do
749                    }
750
751                    if (needUpdate) {
752                        mSettings.updateIntentFilterVerificationStatusLPw(
753                                packageName, updatedStatus, userId);
754                        scheduleWritePackageRestrictionsLocked(userId);
755                    }
756                }
757            }
758        }
759
760        @Override
761        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
762                    ActivityIntentInfo filter, String packageName) {
763            if (!hasValidDomains(filter)) {
764                return false;
765            }
766            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
767            if (ivs == null) {
768                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
769                        packageName);
770            }
771            if (DEBUG_DOMAIN_VERIFICATION) {
772                Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter);
773            }
774            ivs.addFilter(filter);
775            return true;
776        }
777
778        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
779                int userId, int verificationId, String packageName) {
780            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
781                    verifierUid, userId, packageName);
782            ivs.setPendingState();
783            synchronized (mPackages) {
784                mIntentFilterVerificationStates.append(verificationId, ivs);
785                mCurrentIntentFilterVerifications.add(verificationId);
786            }
787            return ivs;
788        }
789    }
790
791    private static boolean hasValidDomains(ActivityIntentInfo filter) {
792        boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
793                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS);
794        if (!hasHTTPorHTTPS) {
795            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
796                    "IntentFilter does not contain any HTTP or HTTPS data scheme");
797            return false;
798        }
799        return true;
800    }
801
802    private IntentFilterVerifier mIntentFilterVerifier;
803
804    // Set of pending broadcasts for aggregating enable/disable of components.
805    static class PendingPackageBroadcasts {
806        // for each user id, a map of <package name -> components within that package>
807        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
808
809        public PendingPackageBroadcasts() {
810            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
811        }
812
813        public ArrayList<String> get(int userId, String packageName) {
814            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
815            return packages.get(packageName);
816        }
817
818        public void put(int userId, String packageName, ArrayList<String> components) {
819            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
820            packages.put(packageName, components);
821        }
822
823        public void remove(int userId, String packageName) {
824            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
825            if (packages != null) {
826                packages.remove(packageName);
827            }
828        }
829
830        public void remove(int userId) {
831            mUidMap.remove(userId);
832        }
833
834        public int userIdCount() {
835            return mUidMap.size();
836        }
837
838        public int userIdAt(int n) {
839            return mUidMap.keyAt(n);
840        }
841
842        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
843            return mUidMap.get(userId);
844        }
845
846        public int size() {
847            // total number of pending broadcast entries across all userIds
848            int num = 0;
849            for (int i = 0; i< mUidMap.size(); i++) {
850                num += mUidMap.valueAt(i).size();
851            }
852            return num;
853        }
854
855        public void clear() {
856            mUidMap.clear();
857        }
858
859        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
860            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
861            if (map == null) {
862                map = new ArrayMap<String, ArrayList<String>>();
863                mUidMap.put(userId, map);
864            }
865            return map;
866        }
867    }
868    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
869
870    // Service Connection to remote media container service to copy
871    // package uri's from external media onto secure containers
872    // or internal storage.
873    private IMediaContainerService mContainerService = null;
874
875    static final int SEND_PENDING_BROADCAST = 1;
876    static final int MCS_BOUND = 3;
877    static final int END_COPY = 4;
878    static final int INIT_COPY = 5;
879    static final int MCS_UNBIND = 6;
880    static final int START_CLEANING_PACKAGE = 7;
881    static final int FIND_INSTALL_LOC = 8;
882    static final int POST_INSTALL = 9;
883    static final int MCS_RECONNECT = 10;
884    static final int MCS_GIVE_UP = 11;
885    static final int UPDATED_MEDIA_STATUS = 12;
886    static final int WRITE_SETTINGS = 13;
887    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
888    static final int PACKAGE_VERIFIED = 15;
889    static final int CHECK_PENDING_VERIFICATION = 16;
890    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
891    static final int INTENT_FILTER_VERIFIED = 18;
892
893    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
894
895    // Delay time in millisecs
896    static final int BROADCAST_DELAY = 10 * 1000;
897
898    static UserManagerService sUserManager;
899
900    // Stores a list of users whose package restrictions file needs to be updated
901    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
902
903    final private DefaultContainerConnection mDefContainerConn =
904            new DefaultContainerConnection();
905    class DefaultContainerConnection implements ServiceConnection {
906        public void onServiceConnected(ComponentName name, IBinder service) {
907            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
908            IMediaContainerService imcs =
909                IMediaContainerService.Stub.asInterface(service);
910            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
911        }
912
913        public void onServiceDisconnected(ComponentName name) {
914            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
915        }
916    }
917
918    // Recordkeeping of restore-after-install operations that are currently in flight
919    // between the Package Manager and the Backup Manager
920    class PostInstallData {
921        public InstallArgs args;
922        public PackageInstalledInfo res;
923
924        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
925            args = _a;
926            res = _r;
927        }
928    }
929
930    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
931    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
932
933    // XML tags for backup/restore of various bits of state
934    private static final String TAG_PREFERRED_BACKUP = "pa";
935    private static final String TAG_DEFAULT_APPS = "da";
936    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
937
938    final String mRequiredVerifierPackage;
939    final String mRequiredInstallerPackage;
940
941    private final PackageUsage mPackageUsage = new PackageUsage();
942
943    private class PackageUsage {
944        private static final int WRITE_INTERVAL
945            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
946
947        private final Object mFileLock = new Object();
948        private final AtomicLong mLastWritten = new AtomicLong(0);
949        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
950
951        private boolean mIsHistoricalPackageUsageAvailable = true;
952
953        boolean isHistoricalPackageUsageAvailable() {
954            return mIsHistoricalPackageUsageAvailable;
955        }
956
957        void write(boolean force) {
958            if (force) {
959                writeInternal();
960                return;
961            }
962            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
963                && !DEBUG_DEXOPT) {
964                return;
965            }
966            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
967                new Thread("PackageUsage_DiskWriter") {
968                    @Override
969                    public void run() {
970                        try {
971                            writeInternal();
972                        } finally {
973                            mBackgroundWriteRunning.set(false);
974                        }
975                    }
976                }.start();
977            }
978        }
979
980        private void writeInternal() {
981            synchronized (mPackages) {
982                synchronized (mFileLock) {
983                    AtomicFile file = getFile();
984                    FileOutputStream f = null;
985                    try {
986                        f = file.startWrite();
987                        BufferedOutputStream out = new BufferedOutputStream(f);
988                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
989                        StringBuilder sb = new StringBuilder();
990                        for (PackageParser.Package pkg : mPackages.values()) {
991                            if (pkg.mLastPackageUsageTimeInMills == 0) {
992                                continue;
993                            }
994                            sb.setLength(0);
995                            sb.append(pkg.packageName);
996                            sb.append(' ');
997                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
998                            sb.append('\n');
999                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1000                        }
1001                        out.flush();
1002                        file.finishWrite(f);
1003                    } catch (IOException e) {
1004                        if (f != null) {
1005                            file.failWrite(f);
1006                        }
1007                        Log.e(TAG, "Failed to write package usage times", e);
1008                    }
1009                }
1010            }
1011            mLastWritten.set(SystemClock.elapsedRealtime());
1012        }
1013
1014        void readLP() {
1015            synchronized (mFileLock) {
1016                AtomicFile file = getFile();
1017                BufferedInputStream in = null;
1018                try {
1019                    in = new BufferedInputStream(file.openRead());
1020                    StringBuffer sb = new StringBuffer();
1021                    while (true) {
1022                        String packageName = readToken(in, sb, ' ');
1023                        if (packageName == null) {
1024                            break;
1025                        }
1026                        String timeInMillisString = readToken(in, sb, '\n');
1027                        if (timeInMillisString == null) {
1028                            throw new IOException("Failed to find last usage time for package "
1029                                                  + packageName);
1030                        }
1031                        PackageParser.Package pkg = mPackages.get(packageName);
1032                        if (pkg == null) {
1033                            continue;
1034                        }
1035                        long timeInMillis;
1036                        try {
1037                            timeInMillis = Long.parseLong(timeInMillisString.toString());
1038                        } catch (NumberFormatException e) {
1039                            throw new IOException("Failed to parse " + timeInMillisString
1040                                                  + " as a long.", e);
1041                        }
1042                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1043                    }
1044                } catch (FileNotFoundException expected) {
1045                    mIsHistoricalPackageUsageAvailable = false;
1046                } catch (IOException e) {
1047                    Log.w(TAG, "Failed to read package usage times", e);
1048                } finally {
1049                    IoUtils.closeQuietly(in);
1050                }
1051            }
1052            mLastWritten.set(SystemClock.elapsedRealtime());
1053        }
1054
1055        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1056                throws IOException {
1057            sb.setLength(0);
1058            while (true) {
1059                int ch = in.read();
1060                if (ch == -1) {
1061                    if (sb.length() == 0) {
1062                        return null;
1063                    }
1064                    throw new IOException("Unexpected EOF");
1065                }
1066                if (ch == endOfToken) {
1067                    return sb.toString();
1068                }
1069                sb.append((char)ch);
1070            }
1071        }
1072
1073        private AtomicFile getFile() {
1074            File dataDir = Environment.getDataDirectory();
1075            File systemDir = new File(dataDir, "system");
1076            File fname = new File(systemDir, "package-usage.list");
1077            return new AtomicFile(fname);
1078        }
1079    }
1080
1081    class PackageHandler extends Handler {
1082        private boolean mBound = false;
1083        final ArrayList<HandlerParams> mPendingInstalls =
1084            new ArrayList<HandlerParams>();
1085
1086        private boolean connectToService() {
1087            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1088                    " DefaultContainerService");
1089            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1090            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1091            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1092                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
1093                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1094                mBound = true;
1095                return true;
1096            }
1097            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1098            return false;
1099        }
1100
1101        private void disconnectService() {
1102            mContainerService = null;
1103            mBound = false;
1104            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1105            mContext.unbindService(mDefContainerConn);
1106            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1107        }
1108
1109        PackageHandler(Looper looper) {
1110            super(looper);
1111        }
1112
1113        public void handleMessage(Message msg) {
1114            try {
1115                doHandleMessage(msg);
1116            } finally {
1117                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1118            }
1119        }
1120
1121        void doHandleMessage(Message msg) {
1122            switch (msg.what) {
1123                case INIT_COPY: {
1124                    HandlerParams params = (HandlerParams) msg.obj;
1125                    int idx = mPendingInstalls.size();
1126                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1127                    // If a bind was already initiated we dont really
1128                    // need to do anything. The pending install
1129                    // will be processed later on.
1130                    if (!mBound) {
1131                        // If this is the only one pending we might
1132                        // have to bind to the service again.
1133                        if (!connectToService()) {
1134                            Slog.e(TAG, "Failed to bind to media container service");
1135                            params.serviceError();
1136                            return;
1137                        } else {
1138                            // Once we bind to the service, the first
1139                            // pending request will be processed.
1140                            mPendingInstalls.add(idx, params);
1141                        }
1142                    } else {
1143                        mPendingInstalls.add(idx, params);
1144                        // Already bound to the service. Just make
1145                        // sure we trigger off processing the first request.
1146                        if (idx == 0) {
1147                            mHandler.sendEmptyMessage(MCS_BOUND);
1148                        }
1149                    }
1150                    break;
1151                }
1152                case MCS_BOUND: {
1153                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1154                    if (msg.obj != null) {
1155                        mContainerService = (IMediaContainerService) msg.obj;
1156                    }
1157                    if (mContainerService == null) {
1158                        if (!mBound) {
1159                            // Something seriously wrong since we are not bound and we are not
1160                            // waiting for connection. Bail out.
1161                            Slog.e(TAG, "Cannot bind to media container service");
1162                            for (HandlerParams params : mPendingInstalls) {
1163                                // Indicate service bind error
1164                                params.serviceError();
1165                            }
1166                            mPendingInstalls.clear();
1167                        } else {
1168                            Slog.w(TAG, "Waiting to connect to media container service");
1169                        }
1170                    } else if (mPendingInstalls.size() > 0) {
1171                        HandlerParams params = mPendingInstalls.get(0);
1172                        if (params != null) {
1173                            if (params.startCopy()) {
1174                                // We are done...  look for more work or to
1175                                // go idle.
1176                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1177                                        "Checking for more work or unbind...");
1178                                // Delete pending install
1179                                if (mPendingInstalls.size() > 0) {
1180                                    mPendingInstalls.remove(0);
1181                                }
1182                                if (mPendingInstalls.size() == 0) {
1183                                    if (mBound) {
1184                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1185                                                "Posting delayed MCS_UNBIND");
1186                                        removeMessages(MCS_UNBIND);
1187                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1188                                        // Unbind after a little delay, to avoid
1189                                        // continual thrashing.
1190                                        sendMessageDelayed(ubmsg, 10000);
1191                                    }
1192                                } else {
1193                                    // There are more pending requests in queue.
1194                                    // Just post MCS_BOUND message to trigger processing
1195                                    // of next pending install.
1196                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1197                                            "Posting MCS_BOUND for next work");
1198                                    mHandler.sendEmptyMessage(MCS_BOUND);
1199                                }
1200                            }
1201                        }
1202                    } else {
1203                        // Should never happen ideally.
1204                        Slog.w(TAG, "Empty queue");
1205                    }
1206                    break;
1207                }
1208                case MCS_RECONNECT: {
1209                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1210                    if (mPendingInstalls.size() > 0) {
1211                        if (mBound) {
1212                            disconnectService();
1213                        }
1214                        if (!connectToService()) {
1215                            Slog.e(TAG, "Failed to bind to media container service");
1216                            for (HandlerParams params : mPendingInstalls) {
1217                                // Indicate service bind error
1218                                params.serviceError();
1219                            }
1220                            mPendingInstalls.clear();
1221                        }
1222                    }
1223                    break;
1224                }
1225                case MCS_UNBIND: {
1226                    // If there is no actual work left, then time to unbind.
1227                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1228
1229                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1230                        if (mBound) {
1231                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1232
1233                            disconnectService();
1234                        }
1235                    } else if (mPendingInstalls.size() > 0) {
1236                        // There are more pending requests in queue.
1237                        // Just post MCS_BOUND message to trigger processing
1238                        // of next pending install.
1239                        mHandler.sendEmptyMessage(MCS_BOUND);
1240                    }
1241
1242                    break;
1243                }
1244                case MCS_GIVE_UP: {
1245                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1246                    mPendingInstalls.remove(0);
1247                    break;
1248                }
1249                case SEND_PENDING_BROADCAST: {
1250                    String packages[];
1251                    ArrayList<String> components[];
1252                    int size = 0;
1253                    int uids[];
1254                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1255                    synchronized (mPackages) {
1256                        if (mPendingBroadcasts == null) {
1257                            return;
1258                        }
1259                        size = mPendingBroadcasts.size();
1260                        if (size <= 0) {
1261                            // Nothing to be done. Just return
1262                            return;
1263                        }
1264                        packages = new String[size];
1265                        components = new ArrayList[size];
1266                        uids = new int[size];
1267                        int i = 0;  // filling out the above arrays
1268
1269                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1270                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1271                            Iterator<Map.Entry<String, ArrayList<String>>> it
1272                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1273                                            .entrySet().iterator();
1274                            while (it.hasNext() && i < size) {
1275                                Map.Entry<String, ArrayList<String>> ent = it.next();
1276                                packages[i] = ent.getKey();
1277                                components[i] = ent.getValue();
1278                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1279                                uids[i] = (ps != null)
1280                                        ? UserHandle.getUid(packageUserId, ps.appId)
1281                                        : -1;
1282                                i++;
1283                            }
1284                        }
1285                        size = i;
1286                        mPendingBroadcasts.clear();
1287                    }
1288                    // Send broadcasts
1289                    for (int i = 0; i < size; i++) {
1290                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1291                    }
1292                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1293                    break;
1294                }
1295                case START_CLEANING_PACKAGE: {
1296                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1297                    final String packageName = (String)msg.obj;
1298                    final int userId = msg.arg1;
1299                    final boolean andCode = msg.arg2 != 0;
1300                    synchronized (mPackages) {
1301                        if (userId == UserHandle.USER_ALL) {
1302                            int[] users = sUserManager.getUserIds();
1303                            for (int user : users) {
1304                                mSettings.addPackageToCleanLPw(
1305                                        new PackageCleanItem(user, packageName, andCode));
1306                            }
1307                        } else {
1308                            mSettings.addPackageToCleanLPw(
1309                                    new PackageCleanItem(userId, packageName, andCode));
1310                        }
1311                    }
1312                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1313                    startCleaningPackages();
1314                } break;
1315                case POST_INSTALL: {
1316                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1317                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1318                    mRunningInstalls.delete(msg.arg1);
1319                    boolean deleteOld = false;
1320
1321                    if (data != null) {
1322                        InstallArgs args = data.args;
1323                        PackageInstalledInfo res = data.res;
1324
1325                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1326                            final String packageName = res.pkg.applicationInfo.packageName;
1327                            res.removedInfo.sendBroadcast(false, true, false);
1328                            Bundle extras = new Bundle(1);
1329                            extras.putInt(Intent.EXTRA_UID, res.uid);
1330
1331                            // Now that we successfully installed the package, grant runtime
1332                            // permissions if requested before broadcasting the install.
1333                            if ((args.installFlags
1334                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) {
1335                                grantRequestedRuntimePermissions(res.pkg,
1336                                        args.user.getIdentifier());
1337                            }
1338
1339                            // Determine the set of users who are adding this
1340                            // package for the first time vs. those who are seeing
1341                            // an update.
1342                            int[] firstUsers;
1343                            int[] updateUsers = new int[0];
1344                            if (res.origUsers == null || res.origUsers.length == 0) {
1345                                firstUsers = res.newUsers;
1346                            } else {
1347                                firstUsers = new int[0];
1348                                for (int i=0; i<res.newUsers.length; i++) {
1349                                    int user = res.newUsers[i];
1350                                    boolean isNew = true;
1351                                    for (int j=0; j<res.origUsers.length; j++) {
1352                                        if (res.origUsers[j] == user) {
1353                                            isNew = false;
1354                                            break;
1355                                        }
1356                                    }
1357                                    if (isNew) {
1358                                        int[] newFirst = new int[firstUsers.length+1];
1359                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1360                                                firstUsers.length);
1361                                        newFirst[firstUsers.length] = user;
1362                                        firstUsers = newFirst;
1363                                    } else {
1364                                        int[] newUpdate = new int[updateUsers.length+1];
1365                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1366                                                updateUsers.length);
1367                                        newUpdate[updateUsers.length] = user;
1368                                        updateUsers = newUpdate;
1369                                    }
1370                                }
1371                            }
1372                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1373                                    packageName, extras, null, null, firstUsers);
1374                            final boolean update = res.removedInfo.removedPackage != null;
1375                            if (update) {
1376                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1377                            }
1378                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1379                                    packageName, extras, null, null, updateUsers);
1380                            if (update) {
1381                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1382                                        packageName, extras, null, null, updateUsers);
1383                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1384                                        null, null, packageName, null, updateUsers);
1385
1386                                // treat asec-hosted packages like removable media on upgrade
1387                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1388                                    if (DEBUG_INSTALL) {
1389                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1390                                                + " is ASEC-hosted -> AVAILABLE");
1391                                    }
1392                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1393                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1394                                    pkgList.add(packageName);
1395                                    sendResourcesChangedBroadcast(true, true,
1396                                            pkgList,uidArray, null);
1397                                }
1398                            }
1399                            if (res.removedInfo.args != null) {
1400                                // Remove the replaced package's older resources safely now
1401                                deleteOld = true;
1402                            }
1403
1404                            // If this app is a browser and it's newly-installed for some
1405                            // users, clear any default-browser state in those users
1406                            if (firstUsers.length > 0) {
1407                                // the app's nature doesn't depend on the user, so we can just
1408                                // check its browser nature in any user and generalize.
1409                                if (packageIsBrowser(packageName, firstUsers[0])) {
1410                                    synchronized (mPackages) {
1411                                        for (int userId : firstUsers) {
1412                                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1413                                        }
1414                                    }
1415                                }
1416                            }
1417                            // Log current value of "unknown sources" setting
1418                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1419                                getUnknownSourcesSettings());
1420                        }
1421                        // Force a gc to clear up things
1422                        Runtime.getRuntime().gc();
1423                        // We delete after a gc for applications  on sdcard.
1424                        if (deleteOld) {
1425                            synchronized (mInstallLock) {
1426                                res.removedInfo.args.doPostDeleteLI(true);
1427                            }
1428                        }
1429                        if (args.observer != null) {
1430                            try {
1431                                Bundle extras = extrasForInstallResult(res);
1432                                args.observer.onPackageInstalled(res.name, res.returnCode,
1433                                        res.returnMsg, extras);
1434                            } catch (RemoteException e) {
1435                                Slog.i(TAG, "Observer no longer exists.");
1436                            }
1437                        }
1438                    } else {
1439                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1440                    }
1441                } break;
1442                case UPDATED_MEDIA_STATUS: {
1443                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1444                    boolean reportStatus = msg.arg1 == 1;
1445                    boolean doGc = msg.arg2 == 1;
1446                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1447                    if (doGc) {
1448                        // Force a gc to clear up stale containers.
1449                        Runtime.getRuntime().gc();
1450                    }
1451                    if (msg.obj != null) {
1452                        @SuppressWarnings("unchecked")
1453                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1454                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1455                        // Unload containers
1456                        unloadAllContainers(args);
1457                    }
1458                    if (reportStatus) {
1459                        try {
1460                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1461                            PackageHelper.getMountService().finishMediaUpdate();
1462                        } catch (RemoteException e) {
1463                            Log.e(TAG, "MountService not running?");
1464                        }
1465                    }
1466                } break;
1467                case WRITE_SETTINGS: {
1468                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1469                    synchronized (mPackages) {
1470                        removeMessages(WRITE_SETTINGS);
1471                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1472                        mSettings.writeLPr();
1473                        mDirtyUsers.clear();
1474                    }
1475                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1476                } break;
1477                case WRITE_PACKAGE_RESTRICTIONS: {
1478                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1479                    synchronized (mPackages) {
1480                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1481                        for (int userId : mDirtyUsers) {
1482                            mSettings.writePackageRestrictionsLPr(userId);
1483                        }
1484                        mDirtyUsers.clear();
1485                    }
1486                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1487                } break;
1488                case CHECK_PENDING_VERIFICATION: {
1489                    final int verificationId = msg.arg1;
1490                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1491
1492                    if ((state != null) && !state.timeoutExtended()) {
1493                        final InstallArgs args = state.getInstallArgs();
1494                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1495
1496                        Slog.i(TAG, "Verification timed out for " + originUri);
1497                        mPendingVerification.remove(verificationId);
1498
1499                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1500
1501                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1502                            Slog.i(TAG, "Continuing with installation of " + originUri);
1503                            state.setVerifierResponse(Binder.getCallingUid(),
1504                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1505                            broadcastPackageVerified(verificationId, originUri,
1506                                    PackageManager.VERIFICATION_ALLOW,
1507                                    state.getInstallArgs().getUser());
1508                            try {
1509                                ret = args.copyApk(mContainerService, true);
1510                            } catch (RemoteException e) {
1511                                Slog.e(TAG, "Could not contact the ContainerService");
1512                            }
1513                        } else {
1514                            broadcastPackageVerified(verificationId, originUri,
1515                                    PackageManager.VERIFICATION_REJECT,
1516                                    state.getInstallArgs().getUser());
1517                        }
1518
1519                        processPendingInstall(args, ret);
1520                        mHandler.sendEmptyMessage(MCS_UNBIND);
1521                    }
1522                    break;
1523                }
1524                case PACKAGE_VERIFIED: {
1525                    final int verificationId = msg.arg1;
1526
1527                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1528                    if (state == null) {
1529                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1530                        break;
1531                    }
1532
1533                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1534
1535                    state.setVerifierResponse(response.callerUid, response.code);
1536
1537                    if (state.isVerificationComplete()) {
1538                        mPendingVerification.remove(verificationId);
1539
1540                        final InstallArgs args = state.getInstallArgs();
1541                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1542
1543                        int ret;
1544                        if (state.isInstallAllowed()) {
1545                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1546                            broadcastPackageVerified(verificationId, originUri,
1547                                    response.code, state.getInstallArgs().getUser());
1548                            try {
1549                                ret = args.copyApk(mContainerService, true);
1550                            } catch (RemoteException e) {
1551                                Slog.e(TAG, "Could not contact the ContainerService");
1552                            }
1553                        } else {
1554                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1555                        }
1556
1557                        processPendingInstall(args, ret);
1558
1559                        mHandler.sendEmptyMessage(MCS_UNBIND);
1560                    }
1561
1562                    break;
1563                }
1564                case START_INTENT_FILTER_VERIFICATIONS: {
1565                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1566                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1567                            params.replacing, params.pkg);
1568                    break;
1569                }
1570                case INTENT_FILTER_VERIFIED: {
1571                    final int verificationId = msg.arg1;
1572
1573                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1574                            verificationId);
1575                    if (state == null) {
1576                        Slog.w(TAG, "Invalid IntentFilter verification token "
1577                                + verificationId + " received");
1578                        break;
1579                    }
1580
1581                    final int userId = state.getUserId();
1582
1583                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1584                            "Processing IntentFilter verification with token:"
1585                            + verificationId + " and userId:" + userId);
1586
1587                    final IntentFilterVerificationResponse response =
1588                            (IntentFilterVerificationResponse) msg.obj;
1589
1590                    state.setVerifierResponse(response.callerUid, response.code);
1591
1592                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1593                            "IntentFilter verification with token:" + verificationId
1594                            + " and userId:" + userId
1595                            + " is settings verifier response with response code:"
1596                            + response.code);
1597
1598                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1599                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1600                                + response.getFailedDomainsString());
1601                    }
1602
1603                    if (state.isVerificationComplete()) {
1604                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1605                    } else {
1606                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1607                                "IntentFilter verification with token:" + verificationId
1608                                + " was not said to be complete");
1609                    }
1610
1611                    break;
1612                }
1613            }
1614        }
1615    }
1616
1617    private StorageEventListener mStorageListener = new StorageEventListener() {
1618        @Override
1619        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1620            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1621                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1622                    final String volumeUuid = vol.getFsUuid();
1623
1624                    // Clean up any users or apps that were removed or recreated
1625                    // while this volume was missing
1626                    reconcileUsers(volumeUuid);
1627                    reconcileApps(volumeUuid);
1628
1629                    // Clean up any install sessions that expired or were
1630                    // cancelled while this volume was missing
1631                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1632
1633                    loadPrivatePackages(vol);
1634
1635                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1636                    unloadPrivatePackages(vol);
1637                }
1638            }
1639
1640            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1641                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1642                    updateExternalMediaStatus(true, false);
1643                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1644                    updateExternalMediaStatus(false, false);
1645                }
1646            }
1647        }
1648
1649        @Override
1650        public void onVolumeForgotten(String fsUuid) {
1651            // Remove any apps installed on the forgotten volume
1652            synchronized (mPackages) {
1653                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1654                for (PackageSetting ps : packages) {
1655                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1656                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1657                            UserHandle.USER_OWNER, PackageManager.DELETE_ALL_USERS);
1658                }
1659
1660                mSettings.writeLPr();
1661            }
1662        }
1663    };
1664
1665    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) {
1666        if (userId >= UserHandle.USER_OWNER) {
1667            grantRequestedRuntimePermissionsForUser(pkg, userId);
1668        } else if (userId == UserHandle.USER_ALL) {
1669            for (int someUserId : UserManagerService.getInstance().getUserIds()) {
1670                grantRequestedRuntimePermissionsForUser(pkg, someUserId);
1671            }
1672        }
1673
1674        // We could have touched GID membership, so flush out packages.list
1675        synchronized (mPackages) {
1676            mSettings.writePackageListLPr();
1677        }
1678    }
1679
1680    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) {
1681        SettingBase sb = (SettingBase) pkg.mExtras;
1682        if (sb == null) {
1683            return;
1684        }
1685
1686        PermissionsState permissionsState = sb.getPermissionsState();
1687
1688        for (String permission : pkg.requestedPermissions) {
1689            BasePermission bp = mSettings.mPermissions.get(permission);
1690            if (bp != null && bp.isRuntime()) {
1691                permissionsState.grantRuntimePermission(bp, userId);
1692            }
1693        }
1694    }
1695
1696    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1697        Bundle extras = null;
1698        switch (res.returnCode) {
1699            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1700                extras = new Bundle();
1701                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1702                        res.origPermission);
1703                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1704                        res.origPackage);
1705                break;
1706            }
1707            case PackageManager.INSTALL_SUCCEEDED: {
1708                extras = new Bundle();
1709                extras.putBoolean(Intent.EXTRA_REPLACING,
1710                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1711                break;
1712            }
1713        }
1714        return extras;
1715    }
1716
1717    void scheduleWriteSettingsLocked() {
1718        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1719            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1720        }
1721    }
1722
1723    void scheduleWritePackageRestrictionsLocked(int userId) {
1724        if (!sUserManager.exists(userId)) return;
1725        mDirtyUsers.add(userId);
1726        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1727            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1728        }
1729    }
1730
1731    public static PackageManagerService main(Context context, Installer installer,
1732            boolean factoryTest, boolean onlyCore) {
1733        PackageManagerService m = new PackageManagerService(context, installer,
1734                factoryTest, onlyCore);
1735        ServiceManager.addService("package", m);
1736        return m;
1737    }
1738
1739    static String[] splitString(String str, char sep) {
1740        int count = 1;
1741        int i = 0;
1742        while ((i=str.indexOf(sep, i)) >= 0) {
1743            count++;
1744            i++;
1745        }
1746
1747        String[] res = new String[count];
1748        i=0;
1749        count = 0;
1750        int lastI=0;
1751        while ((i=str.indexOf(sep, i)) >= 0) {
1752            res[count] = str.substring(lastI, i);
1753            count++;
1754            i++;
1755            lastI = i;
1756        }
1757        res[count] = str.substring(lastI, str.length());
1758        return res;
1759    }
1760
1761    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1762        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1763                Context.DISPLAY_SERVICE);
1764        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1765    }
1766
1767    public PackageManagerService(Context context, Installer installer,
1768            boolean factoryTest, boolean onlyCore) {
1769        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1770                SystemClock.uptimeMillis());
1771
1772        if (mSdkVersion <= 0) {
1773            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1774        }
1775
1776        mContext = context;
1777        mFactoryTest = factoryTest;
1778        mOnlyCore = onlyCore;
1779        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1780        mMetrics = new DisplayMetrics();
1781        mSettings = new Settings(mPackages);
1782        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1783                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1784        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1785                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1786        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1787                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1788        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1789                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1790        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1791                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1792        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1793                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1794
1795        // TODO: add a property to control this?
1796        long dexOptLRUThresholdInMinutes;
1797        if (mLazyDexOpt) {
1798            dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1799        } else {
1800            dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1801        }
1802        mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1803
1804        String separateProcesses = SystemProperties.get("debug.separate_processes");
1805        if (separateProcesses != null && separateProcesses.length() > 0) {
1806            if ("*".equals(separateProcesses)) {
1807                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1808                mSeparateProcesses = null;
1809                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1810            } else {
1811                mDefParseFlags = 0;
1812                mSeparateProcesses = separateProcesses.split(",");
1813                Slog.w(TAG, "Running with debug.separate_processes: "
1814                        + separateProcesses);
1815            }
1816        } else {
1817            mDefParseFlags = 0;
1818            mSeparateProcesses = null;
1819        }
1820
1821        mInstaller = installer;
1822        mPackageDexOptimizer = new PackageDexOptimizer(this);
1823        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1824
1825        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1826                FgThread.get().getLooper());
1827
1828        getDefaultDisplayMetrics(context, mMetrics);
1829
1830        SystemConfig systemConfig = SystemConfig.getInstance();
1831        mGlobalGids = systemConfig.getGlobalGids();
1832        mSystemPermissions = systemConfig.getSystemPermissions();
1833        mAvailableFeatures = systemConfig.getAvailableFeatures();
1834
1835        synchronized (mInstallLock) {
1836        // writer
1837        synchronized (mPackages) {
1838            mHandlerThread = new ServiceThread(TAG,
1839                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1840            mHandlerThread.start();
1841            mHandler = new PackageHandler(mHandlerThread.getLooper());
1842            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1843
1844            File dataDir = Environment.getDataDirectory();
1845            mAppDataDir = new File(dataDir, "data");
1846            mAppInstallDir = new File(dataDir, "app");
1847            mAppLib32InstallDir = new File(dataDir, "app-lib");
1848            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1849            mUserAppDataDir = new File(dataDir, "user");
1850            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1851
1852            sUserManager = new UserManagerService(context, this,
1853                    mInstallLock, mPackages);
1854
1855            // Propagate permission configuration in to package manager.
1856            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1857                    = systemConfig.getPermissions();
1858            for (int i=0; i<permConfig.size(); i++) {
1859                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1860                BasePermission bp = mSettings.mPermissions.get(perm.name);
1861                if (bp == null) {
1862                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1863                    mSettings.mPermissions.put(perm.name, bp);
1864                }
1865                if (perm.gids != null) {
1866                    bp.setGids(perm.gids, perm.perUser);
1867                }
1868            }
1869
1870            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1871            for (int i=0; i<libConfig.size(); i++) {
1872                mSharedLibraries.put(libConfig.keyAt(i),
1873                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1874            }
1875
1876            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1877
1878            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1879                    mSdkVersion, mOnlyCore);
1880
1881            String customResolverActivity = Resources.getSystem().getString(
1882                    R.string.config_customResolverActivity);
1883            if (TextUtils.isEmpty(customResolverActivity)) {
1884                customResolverActivity = null;
1885            } else {
1886                mCustomResolverComponentName = ComponentName.unflattenFromString(
1887                        customResolverActivity);
1888            }
1889
1890            long startTime = SystemClock.uptimeMillis();
1891
1892            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1893                    startTime);
1894
1895            // Set flag to monitor and not change apk file paths when
1896            // scanning install directories.
1897            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
1898
1899            final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1900
1901            /**
1902             * Add everything in the in the boot class path to the
1903             * list of process files because dexopt will have been run
1904             * if necessary during zygote startup.
1905             */
1906            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1907            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1908
1909            if (bootClassPath != null) {
1910                String[] bootClassPathElements = splitString(bootClassPath, ':');
1911                for (String element : bootClassPathElements) {
1912                    alreadyDexOpted.add(element);
1913                }
1914            } else {
1915                Slog.w(TAG, "No BOOTCLASSPATH found!");
1916            }
1917
1918            if (systemServerClassPath != null) {
1919                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1920                for (String element : systemServerClassPathElements) {
1921                    alreadyDexOpted.add(element);
1922                }
1923            } else {
1924                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1925            }
1926
1927            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
1928            final String[] dexCodeInstructionSets =
1929                    getDexCodeInstructionSets(
1930                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
1931
1932            /**
1933             * Ensure all external libraries have had dexopt run on them.
1934             */
1935            if (mSharedLibraries.size() > 0) {
1936                // NOTE: For now, we're compiling these system "shared libraries"
1937                // (and framework jars) into all available architectures. It's possible
1938                // to compile them only when we come across an app that uses them (there's
1939                // already logic for that in scanPackageLI) but that adds some complexity.
1940                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1941                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1942                        final String lib = libEntry.path;
1943                        if (lib == null) {
1944                            continue;
1945                        }
1946
1947                        try {
1948                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
1949                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1950                                alreadyDexOpted.add(lib);
1951                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1952                            }
1953                        } catch (FileNotFoundException e) {
1954                            Slog.w(TAG, "Library not found: " + lib);
1955                        } catch (IOException e) {
1956                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1957                                    + e.getMessage());
1958                        }
1959                    }
1960                }
1961            }
1962
1963            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1964
1965            // Gross hack for now: we know this file doesn't contain any
1966            // code, so don't dexopt it to avoid the resulting log spew.
1967            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1968
1969            // Gross hack for now: we know this file is only part of
1970            // the boot class path for art, so don't dexopt it to
1971            // avoid the resulting log spew.
1972            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1973
1974            /**
1975             * There are a number of commands implemented in Java, which
1976             * we currently need to do the dexopt on so that they can be
1977             * run from a non-root shell.
1978             */
1979            String[] frameworkFiles = frameworkDir.list();
1980            if (frameworkFiles != null) {
1981                // TODO: We could compile these only for the most preferred ABI. We should
1982                // first double check that the dex files for these commands are not referenced
1983                // by other system apps.
1984                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1985                    for (int i=0; i<frameworkFiles.length; i++) {
1986                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1987                        String path = libPath.getPath();
1988                        // Skip the file if we already did it.
1989                        if (alreadyDexOpted.contains(path)) {
1990                            continue;
1991                        }
1992                        // Skip the file if it is not a type we want to dexopt.
1993                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1994                            continue;
1995                        }
1996                        try {
1997                            int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false);
1998                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1999                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
2000                            }
2001                        } catch (FileNotFoundException e) {
2002                            Slog.w(TAG, "Jar not found: " + path);
2003                        } catch (IOException e) {
2004                            Slog.w(TAG, "Exception reading jar: " + path, e);
2005                        }
2006                    }
2007                }
2008            }
2009
2010            // Collect vendor overlay packages.
2011            // (Do this before scanning any apps.)
2012            // For security and version matching reason, only consider
2013            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2014            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2015            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2016                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2017
2018            // Find base frameworks (resource packages without code).
2019            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2020                    | PackageParser.PARSE_IS_SYSTEM_DIR
2021                    | PackageParser.PARSE_IS_PRIVILEGED,
2022                    scanFlags | SCAN_NO_DEX, 0);
2023
2024            // Collected privileged system packages.
2025            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2026            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2027                    | PackageParser.PARSE_IS_SYSTEM_DIR
2028                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2029
2030            // Collect ordinary system packages.
2031            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2032            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2033                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2034
2035            // Collect all vendor packages.
2036            File vendorAppDir = new File("/vendor/app");
2037            try {
2038                vendorAppDir = vendorAppDir.getCanonicalFile();
2039            } catch (IOException e) {
2040                // failed to look up canonical path, continue with original one
2041            }
2042            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2043                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2044
2045            // Collect all OEM packages.
2046            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2047            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2048                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2049
2050            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
2051            mInstaller.moveFiles();
2052
2053            // Prune any system packages that no longer exist.
2054            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2055            if (!mOnlyCore) {
2056                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2057                while (psit.hasNext()) {
2058                    PackageSetting ps = psit.next();
2059
2060                    /*
2061                     * If this is not a system app, it can't be a
2062                     * disable system app.
2063                     */
2064                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2065                        continue;
2066                    }
2067
2068                    /*
2069                     * If the package is scanned, it's not erased.
2070                     */
2071                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2072                    if (scannedPkg != null) {
2073                        /*
2074                         * If the system app is both scanned and in the
2075                         * disabled packages list, then it must have been
2076                         * added via OTA. Remove it from the currently
2077                         * scanned package so the previously user-installed
2078                         * application can be scanned.
2079                         */
2080                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2081                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2082                                    + ps.name + "; removing system app.  Last known codePath="
2083                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2084                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2085                                    + scannedPkg.mVersionCode);
2086                            removePackageLI(ps, true);
2087                            mExpectingBetter.put(ps.name, ps.codePath);
2088                        }
2089
2090                        continue;
2091                    }
2092
2093                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2094                        psit.remove();
2095                        logCriticalInfo(Log.WARN, "System package " + ps.name
2096                                + " no longer exists; wiping its data");
2097                        removeDataDirsLI(null, ps.name);
2098                    } else {
2099                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2100                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2101                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2102                        }
2103                    }
2104                }
2105            }
2106
2107            //look for any incomplete package installations
2108            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2109            //clean up list
2110            for(int i = 0; i < deletePkgsList.size(); i++) {
2111                //clean up here
2112                cleanupInstallFailedPackage(deletePkgsList.get(i));
2113            }
2114            //delete tmp files
2115            deleteTempPackageFiles();
2116
2117            // Remove any shared userIDs that have no associated packages
2118            mSettings.pruneSharedUsersLPw();
2119
2120            if (!mOnlyCore) {
2121                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2122                        SystemClock.uptimeMillis());
2123                scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2124
2125                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2126                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2127
2128                /**
2129                 * Remove disable package settings for any updated system
2130                 * apps that were removed via an OTA. If they're not a
2131                 * previously-updated app, remove them completely.
2132                 * Otherwise, just revoke their system-level permissions.
2133                 */
2134                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2135                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2136                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2137
2138                    String msg;
2139                    if (deletedPkg == null) {
2140                        msg = "Updated system package " + deletedAppName
2141                                + " no longer exists; wiping its data";
2142                        removeDataDirsLI(null, deletedAppName);
2143                    } else {
2144                        msg = "Updated system app + " + deletedAppName
2145                                + " no longer present; removing system privileges for "
2146                                + deletedAppName;
2147
2148                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2149
2150                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2151                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2152                    }
2153                    logCriticalInfo(Log.WARN, msg);
2154                }
2155
2156                /**
2157                 * Make sure all system apps that we expected to appear on
2158                 * the userdata partition actually showed up. If they never
2159                 * appeared, crawl back and revive the system version.
2160                 */
2161                for (int i = 0; i < mExpectingBetter.size(); i++) {
2162                    final String packageName = mExpectingBetter.keyAt(i);
2163                    if (!mPackages.containsKey(packageName)) {
2164                        final File scanFile = mExpectingBetter.valueAt(i);
2165
2166                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2167                                + " but never showed up; reverting to system");
2168
2169                        final int reparseFlags;
2170                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2171                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2172                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2173                                    | PackageParser.PARSE_IS_PRIVILEGED;
2174                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2175                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2176                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2177                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2178                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2179                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2180                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2181                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2182                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2183                        } else {
2184                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2185                            continue;
2186                        }
2187
2188                        mSettings.enableSystemPackageLPw(packageName);
2189
2190                        try {
2191                            scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
2192                        } catch (PackageManagerException e) {
2193                            Slog.e(TAG, "Failed to parse original system package: "
2194                                    + e.getMessage());
2195                        }
2196                    }
2197                }
2198            }
2199            mExpectingBetter.clear();
2200
2201            // Now that we know all of the shared libraries, update all clients to have
2202            // the correct library paths.
2203            updateAllSharedLibrariesLPw();
2204
2205            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2206                // NOTE: We ignore potential failures here during a system scan (like
2207                // the rest of the commands above) because there's precious little we
2208                // can do about it. A settings error is reported, though.
2209                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2210                        false /* force dexopt */, false /* defer dexopt */);
2211            }
2212
2213            // Now that we know all the packages we are keeping,
2214            // read and update their last usage times.
2215            mPackageUsage.readLP();
2216
2217            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2218                    SystemClock.uptimeMillis());
2219            Slog.i(TAG, "Time to scan packages: "
2220                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2221                    + " seconds");
2222
2223            // If the platform SDK has changed since the last time we booted,
2224            // we need to re-grant app permission to catch any new ones that
2225            // appear.  This is really a hack, and means that apps can in some
2226            // cases get permissions that the user didn't initially explicitly
2227            // allow...  it would be nice to have some better way to handle
2228            // this situation.
2229            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
2230                    != mSdkVersion;
2231            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
2232                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
2233                    + "; regranting permissions for internal storage");
2234            mSettings.mInternalSdkPlatform = mSdkVersion;
2235
2236            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
2237                    | (regrantPermissions
2238                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
2239                            : 0));
2240
2241            // If this is the first boot, and it is a normal boot, then
2242            // we need to initialize the default preferred apps.
2243            if (!mRestoredSettings && !onlyCore) {
2244                mSettings.applyDefaultPreferredAppsLPw(this, UserHandle.USER_OWNER);
2245                applyFactoryDefaultBrowserLPw(UserHandle.USER_OWNER);
2246            }
2247
2248            // If this is first boot after an OTA, and a normal boot, then
2249            // we need to clear code cache directories.
2250            mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint);
2251            if (mIsUpgrade && !onlyCore) {
2252                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2253                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2254                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2255                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2256                }
2257                mSettings.mFingerprint = Build.FINGERPRINT;
2258            }
2259
2260            primeDomainVerificationsLPw();
2261            checkDefaultBrowser();
2262
2263            // All the changes are done during package scanning.
2264            mSettings.updateInternalDatabaseVersion();
2265
2266            // can downgrade to reader
2267            mSettings.writeLPr();
2268
2269            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2270                    SystemClock.uptimeMillis());
2271
2272            mRequiredVerifierPackage = getRequiredVerifierLPr();
2273            mRequiredInstallerPackage = getRequiredInstallerLPr();
2274
2275            mInstallerService = new PackageInstallerService(context, this);
2276
2277            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2278            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2279                    mIntentFilterVerifierComponent);
2280
2281        } // synchronized (mPackages)
2282        } // synchronized (mInstallLock)
2283
2284        // Now after opening every single application zip, make sure they
2285        // are all flushed.  Not really needed, but keeps things nice and
2286        // tidy.
2287        Runtime.getRuntime().gc();
2288
2289        // Expose private service for system components to use.
2290        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2291    }
2292
2293    @Override
2294    public boolean isFirstBoot() {
2295        return !mRestoredSettings;
2296    }
2297
2298    @Override
2299    public boolean isOnlyCoreApps() {
2300        return mOnlyCore;
2301    }
2302
2303    @Override
2304    public boolean isUpgrade() {
2305        return mIsUpgrade;
2306    }
2307
2308    private String getRequiredVerifierLPr() {
2309        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2310        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2311                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
2312
2313        String requiredVerifier = null;
2314
2315        final int N = receivers.size();
2316        for (int i = 0; i < N; i++) {
2317            final ResolveInfo info = receivers.get(i);
2318
2319            if (info.activityInfo == null) {
2320                continue;
2321            }
2322
2323            final String packageName = info.activityInfo.packageName;
2324
2325            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2326                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2327                continue;
2328            }
2329
2330            if (requiredVerifier != null) {
2331                throw new RuntimeException("There can be only one required verifier");
2332            }
2333
2334            requiredVerifier = packageName;
2335        }
2336
2337        return requiredVerifier;
2338    }
2339
2340    private String getRequiredInstallerLPr() {
2341        Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2342        installerIntent.addCategory(Intent.CATEGORY_DEFAULT);
2343        installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2344
2345        final List<ResolveInfo> installers = queryIntentActivities(installerIntent,
2346                PACKAGE_MIME_TYPE, 0, 0);
2347
2348        String requiredInstaller = null;
2349
2350        final int N = installers.size();
2351        for (int i = 0; i < N; i++) {
2352            final ResolveInfo info = installers.get(i);
2353            final String packageName = info.activityInfo.packageName;
2354
2355            if (!info.activityInfo.applicationInfo.isSystemApp()) {
2356                continue;
2357            }
2358
2359            if (requiredInstaller != null) {
2360                throw new RuntimeException("There must be one required installer");
2361            }
2362
2363            requiredInstaller = packageName;
2364        }
2365
2366        if (requiredInstaller == null) {
2367            throw new RuntimeException("There must be one required installer");
2368        }
2369
2370        return requiredInstaller;
2371    }
2372
2373    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2374        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2375        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2376                PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */);
2377
2378        ComponentName verifierComponentName = null;
2379
2380        int priority = -1000;
2381        final int N = receivers.size();
2382        for (int i = 0; i < N; i++) {
2383            final ResolveInfo info = receivers.get(i);
2384
2385            if (info.activityInfo == null) {
2386                continue;
2387            }
2388
2389            final String packageName = info.activityInfo.packageName;
2390
2391            final PackageSetting ps = mSettings.mPackages.get(packageName);
2392            if (ps == null) {
2393                continue;
2394            }
2395
2396            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2397                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2398                continue;
2399            }
2400
2401            // Select the IntentFilterVerifier with the highest priority
2402            if (priority < info.priority) {
2403                priority = info.priority;
2404                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2405                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2406                        + verifierComponentName + " with priority: " + info.priority);
2407            }
2408        }
2409
2410        return verifierComponentName;
2411    }
2412
2413    private void primeDomainVerificationsLPw() {
2414        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Start priming domain verifications");
2415        boolean updated = false;
2416        ArraySet<String> allHostsSet = new ArraySet<>();
2417        for (PackageParser.Package pkg : mPackages.values()) {
2418            final String packageName = pkg.packageName;
2419            if (!hasDomainURLs(pkg)) {
2420                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "No priming domain verifications for " +
2421                            "package with no domain URLs: " + packageName);
2422                continue;
2423            }
2424            if (!pkg.isSystemApp()) {
2425                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2426                        "No priming domain verifications for a non system package : " +
2427                                packageName);
2428                continue;
2429            }
2430            for (PackageParser.Activity a : pkg.activities) {
2431                for (ActivityIntentInfo filter : a.intents) {
2432                    if (hasValidDomains(filter)) {
2433                        allHostsSet.addAll(filter.getHostsList());
2434                    }
2435                }
2436            }
2437            if (allHostsSet.size() == 0) {
2438                allHostsSet.add("*");
2439            }
2440            ArrayList<String> allHostsList = new ArrayList<>(allHostsSet);
2441            IntentFilterVerificationInfo ivi =
2442                    mSettings.createIntentFilterVerificationIfNeededLPw(packageName, allHostsList);
2443            if (ivi != null) {
2444                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2445                        "Priming domain verifications for package: " + packageName +
2446                        " with hosts:" + ivi.getDomainsString());
2447                ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
2448                updated = true;
2449            }
2450            else {
2451                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2452                        "No priming domain verifications for package: " + packageName);
2453            }
2454            allHostsSet.clear();
2455        }
2456        if (updated) {
2457            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2458                    "Will need to write primed domain verifications");
2459        }
2460        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "End priming domain verifications");
2461    }
2462
2463    private void applyFactoryDefaultBrowserLPw(int userId) {
2464        // The default browser app's package name is stored in a string resource,
2465        // with a product-specific overlay used for vendor customization.
2466        String browserPkg = mContext.getResources().getString(
2467                com.android.internal.R.string.default_browser);
2468        if (browserPkg != null) {
2469            // non-empty string => required to be a known package
2470            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2471            if (ps == null) {
2472                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2473                browserPkg = null;
2474            } else {
2475                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2476            }
2477        }
2478
2479        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2480        // default.  If there's more than one, just leave everything alone.
2481        if (browserPkg == null) {
2482            calculateDefaultBrowserLPw(userId);
2483        }
2484    }
2485
2486    private void calculateDefaultBrowserLPw(int userId) {
2487        List<String> allBrowsers = resolveAllBrowserApps(userId);
2488        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2489        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2490    }
2491
2492    private List<String> resolveAllBrowserApps(int userId) {
2493        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2494        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2495                PackageManager.MATCH_ALL, userId);
2496
2497        final int count = list.size();
2498        List<String> result = new ArrayList<String>(count);
2499        for (int i=0; i<count; i++) {
2500            ResolveInfo info = list.get(i);
2501            if (info.activityInfo == null
2502                    || !info.handleAllWebDataURI
2503                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2504                    || result.contains(info.activityInfo.packageName)) {
2505                continue;
2506            }
2507            result.add(info.activityInfo.packageName);
2508        }
2509
2510        return result;
2511    }
2512
2513    private boolean packageIsBrowser(String packageName, int userId) {
2514        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2515                PackageManager.MATCH_ALL, userId);
2516        final int N = list.size();
2517        for (int i = 0; i < N; i++) {
2518            ResolveInfo info = list.get(i);
2519            if (packageName.equals(info.activityInfo.packageName)) {
2520                return true;
2521            }
2522        }
2523        return false;
2524    }
2525
2526    private void checkDefaultBrowser() {
2527        final int myUserId = UserHandle.myUserId();
2528        final String packageName = getDefaultBrowserPackageName(myUserId);
2529        if (packageName != null) {
2530            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2531            if (info == null) {
2532                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2533                synchronized (mPackages) {
2534                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2535                }
2536            }
2537        }
2538    }
2539
2540    @Override
2541    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2542            throws RemoteException {
2543        try {
2544            return super.onTransact(code, data, reply, flags);
2545        } catch (RuntimeException e) {
2546            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2547                Slog.wtf(TAG, "Package Manager Crash", e);
2548            }
2549            throw e;
2550        }
2551    }
2552
2553    void cleanupInstallFailedPackage(PackageSetting ps) {
2554        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2555
2556        removeDataDirsLI(ps.volumeUuid, ps.name);
2557        if (ps.codePath != null) {
2558            if (ps.codePath.isDirectory()) {
2559                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2560            } else {
2561                ps.codePath.delete();
2562            }
2563        }
2564        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2565            if (ps.resourcePath.isDirectory()) {
2566                FileUtils.deleteContents(ps.resourcePath);
2567            }
2568            ps.resourcePath.delete();
2569        }
2570        mSettings.removePackageLPw(ps.name);
2571    }
2572
2573    static int[] appendInts(int[] cur, int[] add) {
2574        if (add == null) return cur;
2575        if (cur == null) return add;
2576        final int N = add.length;
2577        for (int i=0; i<N; i++) {
2578            cur = appendInt(cur, add[i]);
2579        }
2580        return cur;
2581    }
2582
2583    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2584        if (!sUserManager.exists(userId)) return null;
2585        final PackageSetting ps = (PackageSetting) p.mExtras;
2586        if (ps == null) {
2587            return null;
2588        }
2589
2590        final PermissionsState permissionsState = ps.getPermissionsState();
2591
2592        final int[] gids = permissionsState.computeGids(userId);
2593        final Set<String> permissions = permissionsState.getPermissions(userId);
2594        final PackageUserState state = ps.readUserState(userId);
2595
2596        return PackageParser.generatePackageInfo(p, gids, flags,
2597                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2598    }
2599
2600    @Override
2601    public boolean isPackageFrozen(String packageName) {
2602        synchronized (mPackages) {
2603            final PackageSetting ps = mSettings.mPackages.get(packageName);
2604            if (ps != null) {
2605                return ps.frozen;
2606            }
2607        }
2608        Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen");
2609        return true;
2610    }
2611
2612    @Override
2613    public boolean isPackageAvailable(String packageName, int userId) {
2614        if (!sUserManager.exists(userId)) return false;
2615        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2616        synchronized (mPackages) {
2617            PackageParser.Package p = mPackages.get(packageName);
2618            if (p != null) {
2619                final PackageSetting ps = (PackageSetting) p.mExtras;
2620                if (ps != null) {
2621                    final PackageUserState state = ps.readUserState(userId);
2622                    if (state != null) {
2623                        return PackageParser.isAvailable(state);
2624                    }
2625                }
2626            }
2627        }
2628        return false;
2629    }
2630
2631    @Override
2632    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2633        if (!sUserManager.exists(userId)) return null;
2634        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2635        // reader
2636        synchronized (mPackages) {
2637            PackageParser.Package p = mPackages.get(packageName);
2638            if (DEBUG_PACKAGE_INFO)
2639                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2640            if (p != null) {
2641                return generatePackageInfo(p, flags, userId);
2642            }
2643            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2644                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2645            }
2646        }
2647        return null;
2648    }
2649
2650    @Override
2651    public String[] currentToCanonicalPackageNames(String[] names) {
2652        String[] out = new String[names.length];
2653        // reader
2654        synchronized (mPackages) {
2655            for (int i=names.length-1; i>=0; i--) {
2656                PackageSetting ps = mSettings.mPackages.get(names[i]);
2657                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2658            }
2659        }
2660        return out;
2661    }
2662
2663    @Override
2664    public String[] canonicalToCurrentPackageNames(String[] names) {
2665        String[] out = new String[names.length];
2666        // reader
2667        synchronized (mPackages) {
2668            for (int i=names.length-1; i>=0; i--) {
2669                String cur = mSettings.mRenamedPackages.get(names[i]);
2670                out[i] = cur != null ? cur : names[i];
2671            }
2672        }
2673        return out;
2674    }
2675
2676    @Override
2677    public int getPackageUid(String packageName, int userId) {
2678        if (!sUserManager.exists(userId)) return -1;
2679        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2680
2681        // reader
2682        synchronized (mPackages) {
2683            PackageParser.Package p = mPackages.get(packageName);
2684            if(p != null) {
2685                return UserHandle.getUid(userId, p.applicationInfo.uid);
2686            }
2687            PackageSetting ps = mSettings.mPackages.get(packageName);
2688            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2689                return -1;
2690            }
2691            p = ps.pkg;
2692            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2693        }
2694    }
2695
2696    @Override
2697    public int[] getPackageGids(String packageName, int userId) throws RemoteException {
2698        if (!sUserManager.exists(userId)) {
2699            return null;
2700        }
2701
2702        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2703                "getPackageGids");
2704
2705        // reader
2706        synchronized (mPackages) {
2707            PackageParser.Package p = mPackages.get(packageName);
2708            if (DEBUG_PACKAGE_INFO) {
2709                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2710            }
2711            if (p != null) {
2712                PackageSetting ps = (PackageSetting) p.mExtras;
2713                return ps.getPermissionsState().computeGids(userId);
2714            }
2715        }
2716
2717        return null;
2718    }
2719
2720    @Override
2721    public int getMountExternalMode(int uid) {
2722        if (Process.isIsolated(uid)) {
2723            return Zygote.MOUNT_EXTERNAL_NONE;
2724        } else {
2725            if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
2726                return Zygote.MOUNT_EXTERNAL_DEFAULT;
2727            } else if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_GRANTED) {
2728                return Zygote.MOUNT_EXTERNAL_WRITE;
2729            } else if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_GRANTED) {
2730                return Zygote.MOUNT_EXTERNAL_READ;
2731            } else {
2732                return Zygote.MOUNT_EXTERNAL_DEFAULT;
2733            }
2734        }
2735    }
2736
2737    static PermissionInfo generatePermissionInfo(
2738            BasePermission bp, int flags) {
2739        if (bp.perm != null) {
2740            return PackageParser.generatePermissionInfo(bp.perm, flags);
2741        }
2742        PermissionInfo pi = new PermissionInfo();
2743        pi.name = bp.name;
2744        pi.packageName = bp.sourcePackage;
2745        pi.nonLocalizedLabel = bp.name;
2746        pi.protectionLevel = bp.protectionLevel;
2747        return pi;
2748    }
2749
2750    @Override
2751    public PermissionInfo getPermissionInfo(String name, int flags) {
2752        // reader
2753        synchronized (mPackages) {
2754            final BasePermission p = mSettings.mPermissions.get(name);
2755            if (p != null) {
2756                return generatePermissionInfo(p, flags);
2757            }
2758            return null;
2759        }
2760    }
2761
2762    @Override
2763    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2764        // reader
2765        synchronized (mPackages) {
2766            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2767            for (BasePermission p : mSettings.mPermissions.values()) {
2768                if (group == null) {
2769                    if (p.perm == null || p.perm.info.group == null) {
2770                        out.add(generatePermissionInfo(p, flags));
2771                    }
2772                } else {
2773                    if (p.perm != null && group.equals(p.perm.info.group)) {
2774                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2775                    }
2776                }
2777            }
2778
2779            if (out.size() > 0) {
2780                return out;
2781            }
2782            return mPermissionGroups.containsKey(group) ? out : null;
2783        }
2784    }
2785
2786    @Override
2787    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2788        // reader
2789        synchronized (mPackages) {
2790            return PackageParser.generatePermissionGroupInfo(
2791                    mPermissionGroups.get(name), flags);
2792        }
2793    }
2794
2795    @Override
2796    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2797        // reader
2798        synchronized (mPackages) {
2799            final int N = mPermissionGroups.size();
2800            ArrayList<PermissionGroupInfo> out
2801                    = new ArrayList<PermissionGroupInfo>(N);
2802            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2803                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2804            }
2805            return out;
2806        }
2807    }
2808
2809    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2810            int userId) {
2811        if (!sUserManager.exists(userId)) return null;
2812        PackageSetting ps = mSettings.mPackages.get(packageName);
2813        if (ps != null) {
2814            if (ps.pkg == null) {
2815                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2816                        flags, userId);
2817                if (pInfo != null) {
2818                    return pInfo.applicationInfo;
2819                }
2820                return null;
2821            }
2822            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2823                    ps.readUserState(userId), userId);
2824        }
2825        return null;
2826    }
2827
2828    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2829            int userId) {
2830        if (!sUserManager.exists(userId)) return null;
2831        PackageSetting ps = mSettings.mPackages.get(packageName);
2832        if (ps != null) {
2833            PackageParser.Package pkg = ps.pkg;
2834            if (pkg == null) {
2835                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2836                    return null;
2837                }
2838                // Only data remains, so we aren't worried about code paths
2839                pkg = new PackageParser.Package(packageName);
2840                pkg.applicationInfo.packageName = packageName;
2841                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2842                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2843                pkg.applicationInfo.dataDir = Environment
2844                        .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName)
2845                        .getAbsolutePath();
2846                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2847                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2848            }
2849            return generatePackageInfo(pkg, flags, userId);
2850        }
2851        return null;
2852    }
2853
2854    @Override
2855    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2856        if (!sUserManager.exists(userId)) return null;
2857        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2858        // writer
2859        synchronized (mPackages) {
2860            PackageParser.Package p = mPackages.get(packageName);
2861            if (DEBUG_PACKAGE_INFO) Log.v(
2862                    TAG, "getApplicationInfo " + packageName
2863                    + ": " + p);
2864            if (p != null) {
2865                PackageSetting ps = mSettings.mPackages.get(packageName);
2866                if (ps == null) return null;
2867                // Note: isEnabledLP() does not apply here - always return info
2868                return PackageParser.generateApplicationInfo(
2869                        p, flags, ps.readUserState(userId), userId);
2870            }
2871            if ("android".equals(packageName)||"system".equals(packageName)) {
2872                return mAndroidApplication;
2873            }
2874            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2875                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2876            }
2877        }
2878        return null;
2879    }
2880
2881    @Override
2882    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
2883            final IPackageDataObserver observer) {
2884        mContext.enforceCallingOrSelfPermission(
2885                android.Manifest.permission.CLEAR_APP_CACHE, null);
2886        // Queue up an async operation since clearing cache may take a little while.
2887        mHandler.post(new Runnable() {
2888            public void run() {
2889                mHandler.removeCallbacks(this);
2890                int retCode = -1;
2891                synchronized (mInstallLock) {
2892                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2893                    if (retCode < 0) {
2894                        Slog.w(TAG, "Couldn't clear application caches");
2895                    }
2896                }
2897                if (observer != null) {
2898                    try {
2899                        observer.onRemoveCompleted(null, (retCode >= 0));
2900                    } catch (RemoteException e) {
2901                        Slog.w(TAG, "RemoveException when invoking call back");
2902                    }
2903                }
2904            }
2905        });
2906    }
2907
2908    @Override
2909    public void freeStorage(final String volumeUuid, final long freeStorageSize,
2910            final IntentSender pi) {
2911        mContext.enforceCallingOrSelfPermission(
2912                android.Manifest.permission.CLEAR_APP_CACHE, null);
2913        // Queue up an async operation since clearing cache may take a little while.
2914        mHandler.post(new Runnable() {
2915            public void run() {
2916                mHandler.removeCallbacks(this);
2917                int retCode = -1;
2918                synchronized (mInstallLock) {
2919                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2920                    if (retCode < 0) {
2921                        Slog.w(TAG, "Couldn't clear application caches");
2922                    }
2923                }
2924                if(pi != null) {
2925                    try {
2926                        // Callback via pending intent
2927                        int code = (retCode >= 0) ? 1 : 0;
2928                        pi.sendIntent(null, code, null,
2929                                null, null);
2930                    } catch (SendIntentException e1) {
2931                        Slog.i(TAG, "Failed to send pending intent");
2932                    }
2933                }
2934            }
2935        });
2936    }
2937
2938    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
2939        synchronized (mInstallLock) {
2940            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
2941                throw new IOException("Failed to free enough space");
2942            }
2943        }
2944    }
2945
2946    @Override
2947    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2948        if (!sUserManager.exists(userId)) return null;
2949        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2950        synchronized (mPackages) {
2951            PackageParser.Activity a = mActivities.mActivities.get(component);
2952
2953            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2954            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2955                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2956                if (ps == null) return null;
2957                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2958                        userId);
2959            }
2960            if (mResolveComponentName.equals(component)) {
2961                return PackageParser.generateActivityInfo(mResolveActivity, flags,
2962                        new PackageUserState(), userId);
2963            }
2964        }
2965        return null;
2966    }
2967
2968    @Override
2969    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2970            String resolvedType) {
2971        synchronized (mPackages) {
2972            PackageParser.Activity a = mActivities.mActivities.get(component);
2973            if (a == null) {
2974                return false;
2975            }
2976            for (int i=0; i<a.intents.size(); i++) {
2977                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2978                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2979                    return true;
2980                }
2981            }
2982            return false;
2983        }
2984    }
2985
2986    @Override
2987    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2988        if (!sUserManager.exists(userId)) return null;
2989        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
2990        synchronized (mPackages) {
2991            PackageParser.Activity a = mReceivers.mActivities.get(component);
2992            if (DEBUG_PACKAGE_INFO) Log.v(
2993                TAG, "getReceiverInfo " + component + ": " + a);
2994            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2995                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2996                if (ps == null) return null;
2997                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2998                        userId);
2999            }
3000        }
3001        return null;
3002    }
3003
3004    @Override
3005    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3006        if (!sUserManager.exists(userId)) return null;
3007        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3008        synchronized (mPackages) {
3009            PackageParser.Service s = mServices.mServices.get(component);
3010            if (DEBUG_PACKAGE_INFO) Log.v(
3011                TAG, "getServiceInfo " + component + ": " + s);
3012            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
3013                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3014                if (ps == null) return null;
3015                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3016                        userId);
3017            }
3018        }
3019        return null;
3020    }
3021
3022    @Override
3023    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3024        if (!sUserManager.exists(userId)) return null;
3025        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3026        synchronized (mPackages) {
3027            PackageParser.Provider p = mProviders.mProviders.get(component);
3028            if (DEBUG_PACKAGE_INFO) Log.v(
3029                TAG, "getProviderInfo " + component + ": " + p);
3030            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
3031                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3032                if (ps == null) return null;
3033                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3034                        userId);
3035            }
3036        }
3037        return null;
3038    }
3039
3040    @Override
3041    public String[] getSystemSharedLibraryNames() {
3042        Set<String> libSet;
3043        synchronized (mPackages) {
3044            libSet = mSharedLibraries.keySet();
3045            int size = libSet.size();
3046            if (size > 0) {
3047                String[] libs = new String[size];
3048                libSet.toArray(libs);
3049                return libs;
3050            }
3051        }
3052        return null;
3053    }
3054
3055    /**
3056     * @hide
3057     */
3058    PackageParser.Package findSharedNonSystemLibrary(String libName) {
3059        synchronized (mPackages) {
3060            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
3061            if (lib != null && lib.apk != null) {
3062                return mPackages.get(lib.apk);
3063            }
3064        }
3065        return null;
3066    }
3067
3068    @Override
3069    public FeatureInfo[] getSystemAvailableFeatures() {
3070        Collection<FeatureInfo> featSet;
3071        synchronized (mPackages) {
3072            featSet = mAvailableFeatures.values();
3073            int size = featSet.size();
3074            if (size > 0) {
3075                FeatureInfo[] features = new FeatureInfo[size+1];
3076                featSet.toArray(features);
3077                FeatureInfo fi = new FeatureInfo();
3078                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3079                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3080                features[size] = fi;
3081                return features;
3082            }
3083        }
3084        return null;
3085    }
3086
3087    @Override
3088    public boolean hasSystemFeature(String name) {
3089        synchronized (mPackages) {
3090            return mAvailableFeatures.containsKey(name);
3091        }
3092    }
3093
3094    private void checkValidCaller(int uid, int userId) {
3095        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
3096            return;
3097
3098        throw new SecurityException("Caller uid=" + uid
3099                + " is not privileged to communicate with user=" + userId);
3100    }
3101
3102    @Override
3103    public int checkPermission(String permName, String pkgName, int userId) {
3104        if (!sUserManager.exists(userId)) {
3105            return PackageManager.PERMISSION_DENIED;
3106        }
3107
3108        synchronized (mPackages) {
3109            final PackageParser.Package p = mPackages.get(pkgName);
3110            if (p != null && p.mExtras != null) {
3111                final PackageSetting ps = (PackageSetting) p.mExtras;
3112                if (ps.getPermissionsState().hasPermission(permName, userId)) {
3113                    return PackageManager.PERMISSION_GRANTED;
3114                }
3115            }
3116        }
3117
3118        return PackageManager.PERMISSION_DENIED;
3119    }
3120
3121    @Override
3122    public int checkUidPermission(String permName, int uid) {
3123        final int userId = UserHandle.getUserId(uid);
3124
3125        if (!sUserManager.exists(userId)) {
3126            return PackageManager.PERMISSION_DENIED;
3127        }
3128
3129        synchronized (mPackages) {
3130            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3131            if (obj != null) {
3132                final SettingBase ps = (SettingBase) obj;
3133                if (ps.getPermissionsState().hasPermission(permName, userId)) {
3134                    return PackageManager.PERMISSION_GRANTED;
3135                }
3136            } else {
3137                ArraySet<String> perms = mSystemPermissions.get(uid);
3138                if (perms != null && perms.contains(permName)) {
3139                    return PackageManager.PERMISSION_GRANTED;
3140                }
3141            }
3142        }
3143
3144        return PackageManager.PERMISSION_DENIED;
3145    }
3146
3147    /**
3148     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3149     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3150     * @param checkShell TODO(yamasani):
3151     * @param message the message to log on security exception
3152     */
3153    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3154            boolean checkShell, String message) {
3155        if (userId < 0) {
3156            throw new IllegalArgumentException("Invalid userId " + userId);
3157        }
3158        if (checkShell) {
3159            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3160        }
3161        if (userId == UserHandle.getUserId(callingUid)) return;
3162        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3163            if (requireFullPermission) {
3164                mContext.enforceCallingOrSelfPermission(
3165                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3166            } else {
3167                try {
3168                    mContext.enforceCallingOrSelfPermission(
3169                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3170                } catch (SecurityException se) {
3171                    mContext.enforceCallingOrSelfPermission(
3172                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3173                }
3174            }
3175        }
3176    }
3177
3178    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3179        if (callingUid == Process.SHELL_UID) {
3180            if (userHandle >= 0
3181                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3182                throw new SecurityException("Shell does not have permission to access user "
3183                        + userHandle);
3184            } else if (userHandle < 0) {
3185                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3186                        + Debug.getCallers(3));
3187            }
3188        }
3189    }
3190
3191    private BasePermission findPermissionTreeLP(String permName) {
3192        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3193            if (permName.startsWith(bp.name) &&
3194                    permName.length() > bp.name.length() &&
3195                    permName.charAt(bp.name.length()) == '.') {
3196                return bp;
3197            }
3198        }
3199        return null;
3200    }
3201
3202    private BasePermission checkPermissionTreeLP(String permName) {
3203        if (permName != null) {
3204            BasePermission bp = findPermissionTreeLP(permName);
3205            if (bp != null) {
3206                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3207                    return bp;
3208                }
3209                throw new SecurityException("Calling uid "
3210                        + Binder.getCallingUid()
3211                        + " is not allowed to add to permission tree "
3212                        + bp.name + " owned by uid " + bp.uid);
3213            }
3214        }
3215        throw new SecurityException("No permission tree found for " + permName);
3216    }
3217
3218    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3219        if (s1 == null) {
3220            return s2 == null;
3221        }
3222        if (s2 == null) {
3223            return false;
3224        }
3225        if (s1.getClass() != s2.getClass()) {
3226            return false;
3227        }
3228        return s1.equals(s2);
3229    }
3230
3231    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3232        if (pi1.icon != pi2.icon) return false;
3233        if (pi1.logo != pi2.logo) return false;
3234        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3235        if (!compareStrings(pi1.name, pi2.name)) return false;
3236        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3237        // We'll take care of setting this one.
3238        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3239        // These are not currently stored in settings.
3240        //if (!compareStrings(pi1.group, pi2.group)) return false;
3241        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3242        //if (pi1.labelRes != pi2.labelRes) return false;
3243        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3244        return true;
3245    }
3246
3247    int permissionInfoFootprint(PermissionInfo info) {
3248        int size = info.name.length();
3249        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3250        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3251        return size;
3252    }
3253
3254    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3255        int size = 0;
3256        for (BasePermission perm : mSettings.mPermissions.values()) {
3257            if (perm.uid == tree.uid) {
3258                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3259            }
3260        }
3261        return size;
3262    }
3263
3264    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3265        // We calculate the max size of permissions defined by this uid and throw
3266        // if that plus the size of 'info' would exceed our stated maximum.
3267        if (tree.uid != Process.SYSTEM_UID) {
3268            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3269            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3270                throw new SecurityException("Permission tree size cap exceeded");
3271            }
3272        }
3273    }
3274
3275    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3276        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3277            throw new SecurityException("Label must be specified in permission");
3278        }
3279        BasePermission tree = checkPermissionTreeLP(info.name);
3280        BasePermission bp = mSettings.mPermissions.get(info.name);
3281        boolean added = bp == null;
3282        boolean changed = true;
3283        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3284        if (added) {
3285            enforcePermissionCapLocked(info, tree);
3286            bp = new BasePermission(info.name, tree.sourcePackage,
3287                    BasePermission.TYPE_DYNAMIC);
3288        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3289            throw new SecurityException(
3290                    "Not allowed to modify non-dynamic permission "
3291                    + info.name);
3292        } else {
3293            if (bp.protectionLevel == fixedLevel
3294                    && bp.perm.owner.equals(tree.perm.owner)
3295                    && bp.uid == tree.uid
3296                    && comparePermissionInfos(bp.perm.info, info)) {
3297                changed = false;
3298            }
3299        }
3300        bp.protectionLevel = fixedLevel;
3301        info = new PermissionInfo(info);
3302        info.protectionLevel = fixedLevel;
3303        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3304        bp.perm.info.packageName = tree.perm.info.packageName;
3305        bp.uid = tree.uid;
3306        if (added) {
3307            mSettings.mPermissions.put(info.name, bp);
3308        }
3309        if (changed) {
3310            if (!async) {
3311                mSettings.writeLPr();
3312            } else {
3313                scheduleWriteSettingsLocked();
3314            }
3315        }
3316        return added;
3317    }
3318
3319    @Override
3320    public boolean addPermission(PermissionInfo info) {
3321        synchronized (mPackages) {
3322            return addPermissionLocked(info, false);
3323        }
3324    }
3325
3326    @Override
3327    public boolean addPermissionAsync(PermissionInfo info) {
3328        synchronized (mPackages) {
3329            return addPermissionLocked(info, true);
3330        }
3331    }
3332
3333    @Override
3334    public void removePermission(String name) {
3335        synchronized (mPackages) {
3336            checkPermissionTreeLP(name);
3337            BasePermission bp = mSettings.mPermissions.get(name);
3338            if (bp != null) {
3339                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3340                    throw new SecurityException(
3341                            "Not allowed to modify non-dynamic permission "
3342                            + name);
3343                }
3344                mSettings.mPermissions.remove(name);
3345                mSettings.writeLPr();
3346            }
3347        }
3348    }
3349
3350    private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg,
3351            BasePermission bp) {
3352        int index = pkg.requestedPermissions.indexOf(bp.name);
3353        if (index == -1) {
3354            throw new SecurityException("Package " + pkg.packageName
3355                    + " has not requested permission " + bp.name);
3356        }
3357        if (!bp.isRuntime()) {
3358            throw new SecurityException("Permission " + bp.name
3359                    + " is not a changeable permission type");
3360        }
3361    }
3362
3363    @Override
3364    public void grantRuntimePermission(String packageName, String name, final int userId) {
3365        if (!sUserManager.exists(userId)) {
3366            Log.e(TAG, "No such user:" + userId);
3367            return;
3368        }
3369
3370        mContext.enforceCallingOrSelfPermission(
3371                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3372                "grantRuntimePermission");
3373
3374        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3375                "grantRuntimePermission");
3376
3377        final int uid;
3378        final SettingBase sb;
3379
3380        synchronized (mPackages) {
3381            final PackageParser.Package pkg = mPackages.get(packageName);
3382            if (pkg == null) {
3383                throw new IllegalArgumentException("Unknown package: " + packageName);
3384            }
3385
3386            final BasePermission bp = mSettings.mPermissions.get(name);
3387            if (bp == null) {
3388                throw new IllegalArgumentException("Unknown permission: " + name);
3389            }
3390
3391            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3392
3393            uid = pkg.applicationInfo.uid;
3394            sb = (SettingBase) pkg.mExtras;
3395            if (sb == null) {
3396                throw new IllegalArgumentException("Unknown package: " + packageName);
3397            }
3398
3399            final PermissionsState permissionsState = sb.getPermissionsState();
3400
3401            final int flags = permissionsState.getPermissionFlags(name, userId);
3402            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3403                throw new SecurityException("Cannot grant system fixed permission: "
3404                        + name + " for package: " + packageName);
3405            }
3406
3407            final int result = permissionsState.grantRuntimePermission(bp, userId);
3408            switch (result) {
3409                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3410                    return;
3411                }
3412
3413                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3414                    mHandler.post(new Runnable() {
3415                        @Override
3416                        public void run() {
3417                            killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED);
3418                        }
3419                    });
3420                } break;
3421            }
3422
3423            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3424
3425            // Not critical if that is lost - app has to request again.
3426            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3427        }
3428
3429        if (READ_EXTERNAL_STORAGE.equals(name)
3430                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3431            final long token = Binder.clearCallingIdentity();
3432            try {
3433                final StorageManager storage = mContext.getSystemService(StorageManager.class);
3434                storage.remountUid(uid);
3435            } finally {
3436                Binder.restoreCallingIdentity(token);
3437            }
3438        }
3439    }
3440
3441    @Override
3442    public void revokeRuntimePermission(String packageName, String name, int userId) {
3443        if (!sUserManager.exists(userId)) {
3444            Log.e(TAG, "No such user:" + userId);
3445            return;
3446        }
3447
3448        mContext.enforceCallingOrSelfPermission(
3449                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3450                "revokeRuntimePermission");
3451
3452        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3453                "revokeRuntimePermission");
3454
3455        final SettingBase sb;
3456
3457        synchronized (mPackages) {
3458            final PackageParser.Package pkg = mPackages.get(packageName);
3459            if (pkg == null) {
3460                throw new IllegalArgumentException("Unknown package: " + packageName);
3461            }
3462
3463            final BasePermission bp = mSettings.mPermissions.get(name);
3464            if (bp == null) {
3465                throw new IllegalArgumentException("Unknown permission: " + name);
3466            }
3467
3468            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3469
3470            sb = (SettingBase) pkg.mExtras;
3471            if (sb == null) {
3472                throw new IllegalArgumentException("Unknown package: " + packageName);
3473            }
3474
3475            final PermissionsState permissionsState = sb.getPermissionsState();
3476
3477            final int flags = permissionsState.getPermissionFlags(name, userId);
3478            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3479                throw new SecurityException("Cannot revoke system fixed permission: "
3480                        + name + " for package: " + packageName);
3481            }
3482
3483            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3484                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3485                return;
3486            }
3487
3488            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3489
3490            // Critical, after this call app should never have the permission.
3491            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3492        }
3493
3494        killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3495    }
3496
3497    @Override
3498    public void resetRuntimePermissions() {
3499        mContext.enforceCallingOrSelfPermission(
3500                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3501                "revokeRuntimePermission");
3502
3503        int callingUid = Binder.getCallingUid();
3504        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3505            mContext.enforceCallingOrSelfPermission(
3506                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3507                    "resetRuntimePermissions");
3508        }
3509
3510        final int[] userIds;
3511
3512        synchronized (mPackages) {
3513            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3514            final int userCount = UserManagerService.getInstance().getUserIds().length;
3515            userIds = Arrays.copyOf(UserManagerService.getInstance().getUserIds(), userCount);
3516        }
3517
3518        for (int userId : userIds) {
3519            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
3520        }
3521    }
3522
3523    @Override
3524    public int getPermissionFlags(String name, String packageName, int userId) {
3525        if (!sUserManager.exists(userId)) {
3526            return 0;
3527        }
3528
3529        mContext.enforceCallingOrSelfPermission(
3530                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3531                "getPermissionFlags");
3532
3533        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3534                "getPermissionFlags");
3535
3536        synchronized (mPackages) {
3537            final PackageParser.Package pkg = mPackages.get(packageName);
3538            if (pkg == null) {
3539                throw new IllegalArgumentException("Unknown package: " + packageName);
3540            }
3541
3542            final BasePermission bp = mSettings.mPermissions.get(name);
3543            if (bp == null) {
3544                throw new IllegalArgumentException("Unknown permission: " + name);
3545            }
3546
3547            SettingBase sb = (SettingBase) pkg.mExtras;
3548            if (sb == null) {
3549                throw new IllegalArgumentException("Unknown package: " + packageName);
3550            }
3551
3552            PermissionsState permissionsState = sb.getPermissionsState();
3553            return permissionsState.getPermissionFlags(name, userId);
3554        }
3555    }
3556
3557    @Override
3558    public void updatePermissionFlags(String name, String packageName, int flagMask,
3559            int flagValues, int userId) {
3560        if (!sUserManager.exists(userId)) {
3561            return;
3562        }
3563
3564        mContext.enforceCallingOrSelfPermission(
3565                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3566                "updatePermissionFlags");
3567
3568        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3569                "updatePermissionFlags");
3570
3571        // Only the system can change system fixed flags.
3572        if (getCallingUid() != Process.SYSTEM_UID) {
3573            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3574            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3575        }
3576
3577        synchronized (mPackages) {
3578            final PackageParser.Package pkg = mPackages.get(packageName);
3579            if (pkg == null) {
3580                throw new IllegalArgumentException("Unknown package: " + packageName);
3581            }
3582
3583            final BasePermission bp = mSettings.mPermissions.get(name);
3584            if (bp == null) {
3585                throw new IllegalArgumentException("Unknown permission: " + name);
3586            }
3587
3588            SettingBase sb = (SettingBase) pkg.mExtras;
3589            if (sb == null) {
3590                throw new IllegalArgumentException("Unknown package: " + packageName);
3591            }
3592
3593            PermissionsState permissionsState = sb.getPermissionsState();
3594
3595            // Only the package manager can change flags for system component permissions.
3596            final int flags = permissionsState.getPermissionFlags(bp.name, userId);
3597            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3598                return;
3599            }
3600
3601            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3602
3603            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3604                // Install and runtime permissions are stored in different places,
3605                // so figure out what permission changed and persist the change.
3606                if (permissionsState.getInstallPermissionState(name) != null) {
3607                    scheduleWriteSettingsLocked();
3608                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3609                        || hadState) {
3610                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3611                }
3612            }
3613        }
3614    }
3615
3616    /**
3617     * Update the permission flags for all packages and runtime permissions of a user in order
3618     * to allow device or profile owner to remove POLICY_FIXED.
3619     */
3620    @Override
3621    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3622        if (!sUserManager.exists(userId)) {
3623            return;
3624        }
3625
3626        mContext.enforceCallingOrSelfPermission(
3627                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3628                "updatePermissionFlagsForAllApps");
3629
3630        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3631                "updatePermissionFlagsForAllApps");
3632
3633        // Only the system can change system fixed flags.
3634        if (getCallingUid() != Process.SYSTEM_UID) {
3635            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3636            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3637        }
3638
3639        synchronized (mPackages) {
3640            boolean changed = false;
3641            final int packageCount = mPackages.size();
3642            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
3643                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
3644                SettingBase sb = (SettingBase) pkg.mExtras;
3645                if (sb == null) {
3646                    continue;
3647                }
3648                PermissionsState permissionsState = sb.getPermissionsState();
3649                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
3650                        userId, flagMask, flagValues);
3651            }
3652            if (changed) {
3653                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3654            }
3655        }
3656    }
3657
3658    @Override
3659    public boolean shouldShowRequestPermissionRationale(String permissionName,
3660            String packageName, int userId) {
3661        if (UserHandle.getCallingUserId() != userId) {
3662            mContext.enforceCallingPermission(
3663                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3664                    "canShowRequestPermissionRationale for user " + userId);
3665        }
3666
3667        final int uid = getPackageUid(packageName, userId);
3668        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
3669            return false;
3670        }
3671
3672        if (checkPermission(permissionName, packageName, userId)
3673                == PackageManager.PERMISSION_GRANTED) {
3674            return false;
3675        }
3676
3677        final int flags;
3678
3679        final long identity = Binder.clearCallingIdentity();
3680        try {
3681            flags = getPermissionFlags(permissionName,
3682                    packageName, userId);
3683        } finally {
3684            Binder.restoreCallingIdentity(identity);
3685        }
3686
3687        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
3688                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
3689                | PackageManager.FLAG_PERMISSION_USER_FIXED;
3690
3691        if ((flags & fixedFlags) != 0) {
3692            return false;
3693        }
3694
3695        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
3696    }
3697
3698    void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) {
3699        BasePermission bp = mSettings.mPermissions.get(permission);
3700        if (bp == null) {
3701            throw new SecurityException("Missing " + permission + " permission");
3702        }
3703
3704        SettingBase sb = (SettingBase) pkg.mExtras;
3705        PermissionsState permissionsState = sb.getPermissionsState();
3706
3707        if (permissionsState.grantInstallPermission(bp) !=
3708                PermissionsState.PERMISSION_OPERATION_FAILURE) {
3709            scheduleWriteSettingsLocked();
3710        }
3711    }
3712
3713    @Override
3714    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3715        mContext.enforceCallingOrSelfPermission(
3716                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
3717                "addOnPermissionsChangeListener");
3718
3719        synchronized (mPackages) {
3720            mOnPermissionChangeListeners.addListenerLocked(listener);
3721        }
3722    }
3723
3724    @Override
3725    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3726        synchronized (mPackages) {
3727            mOnPermissionChangeListeners.removeListenerLocked(listener);
3728        }
3729    }
3730
3731    @Override
3732    public boolean isProtectedBroadcast(String actionName) {
3733        synchronized (mPackages) {
3734            return mProtectedBroadcasts.contains(actionName);
3735        }
3736    }
3737
3738    @Override
3739    public int checkSignatures(String pkg1, String pkg2) {
3740        synchronized (mPackages) {
3741            final PackageParser.Package p1 = mPackages.get(pkg1);
3742            final PackageParser.Package p2 = mPackages.get(pkg2);
3743            if (p1 == null || p1.mExtras == null
3744                    || p2 == null || p2.mExtras == null) {
3745                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3746            }
3747            return compareSignatures(p1.mSignatures, p2.mSignatures);
3748        }
3749    }
3750
3751    @Override
3752    public int checkUidSignatures(int uid1, int uid2) {
3753        // Map to base uids.
3754        uid1 = UserHandle.getAppId(uid1);
3755        uid2 = UserHandle.getAppId(uid2);
3756        // reader
3757        synchronized (mPackages) {
3758            Signature[] s1;
3759            Signature[] s2;
3760            Object obj = mSettings.getUserIdLPr(uid1);
3761            if (obj != null) {
3762                if (obj instanceof SharedUserSetting) {
3763                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3764                } else if (obj instanceof PackageSetting) {
3765                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3766                } else {
3767                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3768                }
3769            } else {
3770                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3771            }
3772            obj = mSettings.getUserIdLPr(uid2);
3773            if (obj != null) {
3774                if (obj instanceof SharedUserSetting) {
3775                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3776                } else if (obj instanceof PackageSetting) {
3777                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3778                } else {
3779                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3780                }
3781            } else {
3782                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3783            }
3784            return compareSignatures(s1, s2);
3785        }
3786    }
3787
3788    private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) {
3789        final long identity = Binder.clearCallingIdentity();
3790        try {
3791            if (sb instanceof SharedUserSetting) {
3792                SharedUserSetting sus = (SharedUserSetting) sb;
3793                final int packageCount = sus.packages.size();
3794                for (int i = 0; i < packageCount; i++) {
3795                    PackageSetting susPs = sus.packages.valueAt(i);
3796                    if (userId == UserHandle.USER_ALL) {
3797                        killApplication(susPs.pkg.packageName, susPs.appId, reason);
3798                    } else {
3799                        final int uid = UserHandle.getUid(userId, susPs.appId);
3800                        killUid(uid, reason);
3801                    }
3802                }
3803            } else if (sb instanceof PackageSetting) {
3804                PackageSetting ps = (PackageSetting) sb;
3805                if (userId == UserHandle.USER_ALL) {
3806                    killApplication(ps.pkg.packageName, ps.appId, reason);
3807                } else {
3808                    final int uid = UserHandle.getUid(userId, ps.appId);
3809                    killUid(uid, reason);
3810                }
3811            }
3812        } finally {
3813            Binder.restoreCallingIdentity(identity);
3814        }
3815    }
3816
3817    private static void killUid(int uid, String reason) {
3818        IActivityManager am = ActivityManagerNative.getDefault();
3819        if (am != null) {
3820            try {
3821                am.killUid(uid, reason);
3822            } catch (RemoteException e) {
3823                /* ignore - same process */
3824            }
3825        }
3826    }
3827
3828    /**
3829     * Compares two sets of signatures. Returns:
3830     * <br />
3831     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3832     * <br />
3833     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3834     * <br />
3835     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3836     * <br />
3837     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3838     * <br />
3839     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3840     */
3841    static int compareSignatures(Signature[] s1, Signature[] s2) {
3842        if (s1 == null) {
3843            return s2 == null
3844                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3845                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3846        }
3847
3848        if (s2 == null) {
3849            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3850        }
3851
3852        if (s1.length != s2.length) {
3853            return PackageManager.SIGNATURE_NO_MATCH;
3854        }
3855
3856        // Since both signature sets are of size 1, we can compare without HashSets.
3857        if (s1.length == 1) {
3858            return s1[0].equals(s2[0]) ?
3859                    PackageManager.SIGNATURE_MATCH :
3860                    PackageManager.SIGNATURE_NO_MATCH;
3861        }
3862
3863        ArraySet<Signature> set1 = new ArraySet<Signature>();
3864        for (Signature sig : s1) {
3865            set1.add(sig);
3866        }
3867        ArraySet<Signature> set2 = new ArraySet<Signature>();
3868        for (Signature sig : s2) {
3869            set2.add(sig);
3870        }
3871        // Make sure s2 contains all signatures in s1.
3872        if (set1.equals(set2)) {
3873            return PackageManager.SIGNATURE_MATCH;
3874        }
3875        return PackageManager.SIGNATURE_NO_MATCH;
3876    }
3877
3878    /**
3879     * If the database version for this type of package (internal storage or
3880     * external storage) is less than the version where package signatures
3881     * were updated, return true.
3882     */
3883    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3884        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
3885                DatabaseVersion.SIGNATURE_END_ENTITY))
3886                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
3887                        DatabaseVersion.SIGNATURE_END_ENTITY));
3888    }
3889
3890    /**
3891     * Used for backward compatibility to make sure any packages with
3892     * certificate chains get upgraded to the new style. {@code existingSigs}
3893     * will be in the old format (since they were stored on disk from before the
3894     * system upgrade) and {@code scannedSigs} will be in the newer format.
3895     */
3896    private int compareSignaturesCompat(PackageSignatures existingSigs,
3897            PackageParser.Package scannedPkg) {
3898        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
3899            return PackageManager.SIGNATURE_NO_MATCH;
3900        }
3901
3902        ArraySet<Signature> existingSet = new ArraySet<Signature>();
3903        for (Signature sig : existingSigs.mSignatures) {
3904            existingSet.add(sig);
3905        }
3906        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
3907        for (Signature sig : scannedPkg.mSignatures) {
3908            try {
3909                Signature[] chainSignatures = sig.getChainSignatures();
3910                for (Signature chainSig : chainSignatures) {
3911                    scannedCompatSet.add(chainSig);
3912                }
3913            } catch (CertificateEncodingException e) {
3914                scannedCompatSet.add(sig);
3915            }
3916        }
3917        /*
3918         * Make sure the expanded scanned set contains all signatures in the
3919         * existing one.
3920         */
3921        if (scannedCompatSet.equals(existingSet)) {
3922            // Migrate the old signatures to the new scheme.
3923            existingSigs.assignSignatures(scannedPkg.mSignatures);
3924            // The new KeySets will be re-added later in the scanning process.
3925            synchronized (mPackages) {
3926                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
3927            }
3928            return PackageManager.SIGNATURE_MATCH;
3929        }
3930        return PackageManager.SIGNATURE_NO_MATCH;
3931    }
3932
3933    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3934        if (isExternal(scannedPkg)) {
3935            return mSettings.isExternalDatabaseVersionOlderThan(
3936                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3937        } else {
3938            return mSettings.isInternalDatabaseVersionOlderThan(
3939                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3940        }
3941    }
3942
3943    private int compareSignaturesRecover(PackageSignatures existingSigs,
3944            PackageParser.Package scannedPkg) {
3945        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
3946            return PackageManager.SIGNATURE_NO_MATCH;
3947        }
3948
3949        String msg = null;
3950        try {
3951            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
3952                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
3953                        + scannedPkg.packageName);
3954                return PackageManager.SIGNATURE_MATCH;
3955            }
3956        } catch (CertificateException e) {
3957            msg = e.getMessage();
3958        }
3959
3960        logCriticalInfo(Log.INFO,
3961                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
3962        return PackageManager.SIGNATURE_NO_MATCH;
3963    }
3964
3965    @Override
3966    public String[] getPackagesForUid(int uid) {
3967        uid = UserHandle.getAppId(uid);
3968        // reader
3969        synchronized (mPackages) {
3970            Object obj = mSettings.getUserIdLPr(uid);
3971            if (obj instanceof SharedUserSetting) {
3972                final SharedUserSetting sus = (SharedUserSetting) obj;
3973                final int N = sus.packages.size();
3974                final String[] res = new String[N];
3975                final Iterator<PackageSetting> it = sus.packages.iterator();
3976                int i = 0;
3977                while (it.hasNext()) {
3978                    res[i++] = it.next().name;
3979                }
3980                return res;
3981            } else if (obj instanceof PackageSetting) {
3982                final PackageSetting ps = (PackageSetting) obj;
3983                return new String[] { ps.name };
3984            }
3985        }
3986        return null;
3987    }
3988
3989    @Override
3990    public String getNameForUid(int uid) {
3991        // reader
3992        synchronized (mPackages) {
3993            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3994            if (obj instanceof SharedUserSetting) {
3995                final SharedUserSetting sus = (SharedUserSetting) obj;
3996                return sus.name + ":" + sus.userId;
3997            } else if (obj instanceof PackageSetting) {
3998                final PackageSetting ps = (PackageSetting) obj;
3999                return ps.name;
4000            }
4001        }
4002        return null;
4003    }
4004
4005    @Override
4006    public int getUidForSharedUser(String sharedUserName) {
4007        if(sharedUserName == null) {
4008            return -1;
4009        }
4010        // reader
4011        synchronized (mPackages) {
4012            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4013            if (suid == null) {
4014                return -1;
4015            }
4016            return suid.userId;
4017        }
4018    }
4019
4020    @Override
4021    public int getFlagsForUid(int uid) {
4022        synchronized (mPackages) {
4023            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4024            if (obj instanceof SharedUserSetting) {
4025                final SharedUserSetting sus = (SharedUserSetting) obj;
4026                return sus.pkgFlags;
4027            } else if (obj instanceof PackageSetting) {
4028                final PackageSetting ps = (PackageSetting) obj;
4029                return ps.pkgFlags;
4030            }
4031        }
4032        return 0;
4033    }
4034
4035    @Override
4036    public int getPrivateFlagsForUid(int uid) {
4037        synchronized (mPackages) {
4038            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4039            if (obj instanceof SharedUserSetting) {
4040                final SharedUserSetting sus = (SharedUserSetting) obj;
4041                return sus.pkgPrivateFlags;
4042            } else if (obj instanceof PackageSetting) {
4043                final PackageSetting ps = (PackageSetting) obj;
4044                return ps.pkgPrivateFlags;
4045            }
4046        }
4047        return 0;
4048    }
4049
4050    @Override
4051    public boolean isUidPrivileged(int uid) {
4052        uid = UserHandle.getAppId(uid);
4053        // reader
4054        synchronized (mPackages) {
4055            Object obj = mSettings.getUserIdLPr(uid);
4056            if (obj instanceof SharedUserSetting) {
4057                final SharedUserSetting sus = (SharedUserSetting) obj;
4058                final Iterator<PackageSetting> it = sus.packages.iterator();
4059                while (it.hasNext()) {
4060                    if (it.next().isPrivileged()) {
4061                        return true;
4062                    }
4063                }
4064            } else if (obj instanceof PackageSetting) {
4065                final PackageSetting ps = (PackageSetting) obj;
4066                return ps.isPrivileged();
4067            }
4068        }
4069        return false;
4070    }
4071
4072    @Override
4073    public String[] getAppOpPermissionPackages(String permissionName) {
4074        synchronized (mPackages) {
4075            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4076            if (pkgs == null) {
4077                return null;
4078            }
4079            return pkgs.toArray(new String[pkgs.size()]);
4080        }
4081    }
4082
4083    @Override
4084    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4085            int flags, int userId) {
4086        if (!sUserManager.exists(userId)) return null;
4087        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4088        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4089        return chooseBestActivity(intent, resolvedType, flags, query, userId);
4090    }
4091
4092    @Override
4093    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4094            IntentFilter filter, int match, ComponentName activity) {
4095        final int userId = UserHandle.getCallingUserId();
4096        if (DEBUG_PREFERRED) {
4097            Log.v(TAG, "setLastChosenActivity intent=" + intent
4098                + " resolvedType=" + resolvedType
4099                + " flags=" + flags
4100                + " filter=" + filter
4101                + " match=" + match
4102                + " activity=" + activity);
4103            filter.dump(new PrintStreamPrinter(System.out), "    ");
4104        }
4105        intent.setComponent(null);
4106        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4107        // Find any earlier preferred or last chosen entries and nuke them
4108        findPreferredActivity(intent, resolvedType,
4109                flags, query, 0, false, true, false, userId);
4110        // Add the new activity as the last chosen for this filter
4111        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4112                "Setting last chosen");
4113    }
4114
4115    @Override
4116    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4117        final int userId = UserHandle.getCallingUserId();
4118        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4119        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4120        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4121                false, false, false, userId);
4122    }
4123
4124    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4125            int flags, List<ResolveInfo> query, int userId) {
4126        if (query != null) {
4127            final int N = query.size();
4128            if (N == 1) {
4129                return query.get(0);
4130            } else if (N > 1) {
4131                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4132                // If there is more than one activity with the same priority,
4133                // then let the user decide between them.
4134                ResolveInfo r0 = query.get(0);
4135                ResolveInfo r1 = query.get(1);
4136                if (DEBUG_INTENT_MATCHING || debug) {
4137                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4138                            + r1.activityInfo.name + "=" + r1.priority);
4139                }
4140                // If the first activity has a higher priority, or a different
4141                // default, then it is always desireable to pick it.
4142                if (r0.priority != r1.priority
4143                        || r0.preferredOrder != r1.preferredOrder
4144                        || r0.isDefault != r1.isDefault) {
4145                    return query.get(0);
4146                }
4147                // If we have saved a preference for a preferred activity for
4148                // this Intent, use that.
4149                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4150                        flags, query, r0.priority, true, false, debug, userId);
4151                if (ri != null) {
4152                    return ri;
4153                }
4154                if (userId != 0) {
4155                    ri = new ResolveInfo(mResolveInfo);
4156                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
4157                    ri.activityInfo.applicationInfo = new ApplicationInfo(
4158                            ri.activityInfo.applicationInfo);
4159                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4160                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4161                    return ri;
4162                }
4163                return mResolveInfo;
4164            }
4165        }
4166        return null;
4167    }
4168
4169    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4170            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4171        final int N = query.size();
4172        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4173                .get(userId);
4174        // Get the list of persistent preferred activities that handle the intent
4175        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4176        List<PersistentPreferredActivity> pprefs = ppir != null
4177                ? ppir.queryIntent(intent, resolvedType,
4178                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4179                : null;
4180        if (pprefs != null && pprefs.size() > 0) {
4181            final int M = pprefs.size();
4182            for (int i=0; i<M; i++) {
4183                final PersistentPreferredActivity ppa = pprefs.get(i);
4184                if (DEBUG_PREFERRED || debug) {
4185                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4186                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4187                            + "\n  component=" + ppa.mComponent);
4188                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4189                }
4190                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4191                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4192                if (DEBUG_PREFERRED || debug) {
4193                    Slog.v(TAG, "Found persistent preferred activity:");
4194                    if (ai != null) {
4195                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4196                    } else {
4197                        Slog.v(TAG, "  null");
4198                    }
4199                }
4200                if (ai == null) {
4201                    // This previously registered persistent preferred activity
4202                    // component is no longer known. Ignore it and do NOT remove it.
4203                    continue;
4204                }
4205                for (int j=0; j<N; j++) {
4206                    final ResolveInfo ri = query.get(j);
4207                    if (!ri.activityInfo.applicationInfo.packageName
4208                            .equals(ai.applicationInfo.packageName)) {
4209                        continue;
4210                    }
4211                    if (!ri.activityInfo.name.equals(ai.name)) {
4212                        continue;
4213                    }
4214                    //  Found a persistent preference that can handle the intent.
4215                    if (DEBUG_PREFERRED || debug) {
4216                        Slog.v(TAG, "Returning persistent preferred activity: " +
4217                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4218                    }
4219                    return ri;
4220                }
4221            }
4222        }
4223        return null;
4224    }
4225
4226    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4227            List<ResolveInfo> query, int priority, boolean always,
4228            boolean removeMatches, boolean debug, int userId) {
4229        if (!sUserManager.exists(userId)) return null;
4230        // writer
4231        synchronized (mPackages) {
4232            if (intent.getSelector() != null) {
4233                intent = intent.getSelector();
4234            }
4235            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4236
4237            // Try to find a matching persistent preferred activity.
4238            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4239                    debug, userId);
4240
4241            // If a persistent preferred activity matched, use it.
4242            if (pri != null) {
4243                return pri;
4244            }
4245
4246            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4247            // Get the list of preferred activities that handle the intent
4248            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4249            List<PreferredActivity> prefs = pir != null
4250                    ? pir.queryIntent(intent, resolvedType,
4251                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4252                    : null;
4253            if (prefs != null && prefs.size() > 0) {
4254                boolean changed = false;
4255                try {
4256                    // First figure out how good the original match set is.
4257                    // We will only allow preferred activities that came
4258                    // from the same match quality.
4259                    int match = 0;
4260
4261                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4262
4263                    final int N = query.size();
4264                    for (int j=0; j<N; j++) {
4265                        final ResolveInfo ri = query.get(j);
4266                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4267                                + ": 0x" + Integer.toHexString(match));
4268                        if (ri.match > match) {
4269                            match = ri.match;
4270                        }
4271                    }
4272
4273                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4274                            + Integer.toHexString(match));
4275
4276                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4277                    final int M = prefs.size();
4278                    for (int i=0; i<M; i++) {
4279                        final PreferredActivity pa = prefs.get(i);
4280                        if (DEBUG_PREFERRED || debug) {
4281                            Slog.v(TAG, "Checking PreferredActivity ds="
4282                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4283                                    + "\n  component=" + pa.mPref.mComponent);
4284                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4285                        }
4286                        if (pa.mPref.mMatch != match) {
4287                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4288                                    + Integer.toHexString(pa.mPref.mMatch));
4289                            continue;
4290                        }
4291                        // If it's not an "always" type preferred activity and that's what we're
4292                        // looking for, skip it.
4293                        if (always && !pa.mPref.mAlways) {
4294                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4295                            continue;
4296                        }
4297                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4298                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4299                        if (DEBUG_PREFERRED || debug) {
4300                            Slog.v(TAG, "Found preferred activity:");
4301                            if (ai != null) {
4302                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4303                            } else {
4304                                Slog.v(TAG, "  null");
4305                            }
4306                        }
4307                        if (ai == null) {
4308                            // This previously registered preferred activity
4309                            // component is no longer known.  Most likely an update
4310                            // to the app was installed and in the new version this
4311                            // component no longer exists.  Clean it up by removing
4312                            // it from the preferred activities list, and skip it.
4313                            Slog.w(TAG, "Removing dangling preferred activity: "
4314                                    + pa.mPref.mComponent);
4315                            pir.removeFilter(pa);
4316                            changed = true;
4317                            continue;
4318                        }
4319                        for (int j=0; j<N; j++) {
4320                            final ResolveInfo ri = query.get(j);
4321                            if (!ri.activityInfo.applicationInfo.packageName
4322                                    .equals(ai.applicationInfo.packageName)) {
4323                                continue;
4324                            }
4325                            if (!ri.activityInfo.name.equals(ai.name)) {
4326                                continue;
4327                            }
4328
4329                            if (removeMatches) {
4330                                pir.removeFilter(pa);
4331                                changed = true;
4332                                if (DEBUG_PREFERRED) {
4333                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4334                                }
4335                                break;
4336                            }
4337
4338                            // Okay we found a previously set preferred or last chosen app.
4339                            // If the result set is different from when this
4340                            // was created, we need to clear it and re-ask the
4341                            // user their preference, if we're looking for an "always" type entry.
4342                            if (always && !pa.mPref.sameSet(query)) {
4343                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4344                                        + intent + " type " + resolvedType);
4345                                if (DEBUG_PREFERRED) {
4346                                    Slog.v(TAG, "Removing preferred activity since set changed "
4347                                            + pa.mPref.mComponent);
4348                                }
4349                                pir.removeFilter(pa);
4350                                // Re-add the filter as a "last chosen" entry (!always)
4351                                PreferredActivity lastChosen = new PreferredActivity(
4352                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4353                                pir.addFilter(lastChosen);
4354                                changed = true;
4355                                return null;
4356                            }
4357
4358                            // Yay! Either the set matched or we're looking for the last chosen
4359                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4360                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4361                            return ri;
4362                        }
4363                    }
4364                } finally {
4365                    if (changed) {
4366                        if (DEBUG_PREFERRED) {
4367                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4368                        }
4369                        scheduleWritePackageRestrictionsLocked(userId);
4370                    }
4371                }
4372            }
4373        }
4374        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4375        return null;
4376    }
4377
4378    /*
4379     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4380     */
4381    @Override
4382    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4383            int targetUserId) {
4384        mContext.enforceCallingOrSelfPermission(
4385                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4386        List<CrossProfileIntentFilter> matches =
4387                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4388        if (matches != null) {
4389            int size = matches.size();
4390            for (int i = 0; i < size; i++) {
4391                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4392            }
4393        }
4394        if (hasWebURI(intent)) {
4395            // cross-profile app linking works only towards the parent.
4396            final UserInfo parent = getProfileParent(sourceUserId);
4397            synchronized(mPackages) {
4398                return getCrossProfileDomainPreferredLpr(intent, resolvedType, 0, sourceUserId,
4399                        parent.id) != null;
4400            }
4401        }
4402        return false;
4403    }
4404
4405    private UserInfo getProfileParent(int userId) {
4406        final long identity = Binder.clearCallingIdentity();
4407        try {
4408            return sUserManager.getProfileParent(userId);
4409        } finally {
4410            Binder.restoreCallingIdentity(identity);
4411        }
4412    }
4413
4414    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4415            String resolvedType, int userId) {
4416        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4417        if (resolver != null) {
4418            return resolver.queryIntent(intent, resolvedType, false, userId);
4419        }
4420        return null;
4421    }
4422
4423    @Override
4424    public List<ResolveInfo> queryIntentActivities(Intent intent,
4425            String resolvedType, int flags, int userId) {
4426        if (!sUserManager.exists(userId)) return Collections.emptyList();
4427        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4428        ComponentName comp = intent.getComponent();
4429        if (comp == null) {
4430            if (intent.getSelector() != null) {
4431                intent = intent.getSelector();
4432                comp = intent.getComponent();
4433            }
4434        }
4435
4436        if (comp != null) {
4437            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4438            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4439            if (ai != null) {
4440                final ResolveInfo ri = new ResolveInfo();
4441                ri.activityInfo = ai;
4442                list.add(ri);
4443            }
4444            return list;
4445        }
4446
4447        // reader
4448        synchronized (mPackages) {
4449            final String pkgName = intent.getPackage();
4450            if (pkgName == null) {
4451                List<CrossProfileIntentFilter> matchingFilters =
4452                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4453                // Check for results that need to skip the current profile.
4454                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4455                        resolvedType, flags, userId);
4456                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4457                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4458                    result.add(xpResolveInfo);
4459                    return filterIfNotPrimaryUser(result, userId);
4460                }
4461
4462                // Check for results in the current profile.
4463                List<ResolveInfo> result = mActivities.queryIntent(
4464                        intent, resolvedType, flags, userId);
4465
4466                // Check for cross profile results.
4467                xpResolveInfo = queryCrossProfileIntents(
4468                        matchingFilters, intent, resolvedType, flags, userId);
4469                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4470                    result.add(xpResolveInfo);
4471                    Collections.sort(result, mResolvePrioritySorter);
4472                }
4473                result = filterIfNotPrimaryUser(result, userId);
4474                if (hasWebURI(intent)) {
4475                    CrossProfileDomainInfo xpDomainInfo = null;
4476                    final UserInfo parent = getProfileParent(userId);
4477                    if (parent != null) {
4478                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4479                                flags, userId, parent.id);
4480                    }
4481                    if (xpDomainInfo != null) {
4482                        if (xpResolveInfo != null) {
4483                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4484                            // in the result.
4485                            result.remove(xpResolveInfo);
4486                        }
4487                        if (result.size() == 0) {
4488                            result.add(xpDomainInfo.resolveInfo);
4489                            return result;
4490                        }
4491                    } else if (result.size() <= 1) {
4492                        return result;
4493                    }
4494                    result = filterCandidatesWithDomainPreferredActivitiesLPr(flags, result,
4495                            xpDomainInfo);
4496                    Collections.sort(result, mResolvePrioritySorter);
4497                }
4498                return result;
4499            }
4500            final PackageParser.Package pkg = mPackages.get(pkgName);
4501            if (pkg != null) {
4502                return filterIfNotPrimaryUser(
4503                        mActivities.queryIntentForPackage(
4504                                intent, resolvedType, flags, pkg.activities, userId),
4505                        userId);
4506            }
4507            return new ArrayList<ResolveInfo>();
4508        }
4509    }
4510
4511    private static class CrossProfileDomainInfo {
4512        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4513        ResolveInfo resolveInfo;
4514        /* Best domain verification status of the activities found in the other profile */
4515        int bestDomainVerificationStatus;
4516    }
4517
4518    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4519            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4520        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
4521                sourceUserId)) {
4522            return null;
4523        }
4524        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4525                resolvedType, flags, parentUserId);
4526
4527        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4528            return null;
4529        }
4530        CrossProfileDomainInfo result = null;
4531        int size = resultTargetUser.size();
4532        for (int i = 0; i < size; i++) {
4533            ResolveInfo riTargetUser = resultTargetUser.get(i);
4534            // Intent filter verification is only for filters that specify a host. So don't return
4535            // those that handle all web uris.
4536            if (riTargetUser.handleAllWebDataURI) {
4537                continue;
4538            }
4539            String packageName = riTargetUser.activityInfo.packageName;
4540            PackageSetting ps = mSettings.mPackages.get(packageName);
4541            if (ps == null) {
4542                continue;
4543            }
4544            int status = getDomainVerificationStatusLPr(ps, parentUserId);
4545            if (result == null) {
4546                result = new CrossProfileDomainInfo();
4547                result.resolveInfo =
4548                        createForwardingResolveInfo(null, sourceUserId, parentUserId);
4549                result.bestDomainVerificationStatus = status;
4550            } else {
4551                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
4552                        result.bestDomainVerificationStatus);
4553            }
4554        }
4555        return result;
4556    }
4557
4558    /**
4559     * Verification statuses are ordered from the worse to the best, except for
4560     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
4561     */
4562    private int bestDomainVerificationStatus(int status1, int status2) {
4563        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4564            return status2;
4565        }
4566        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4567            return status1;
4568        }
4569        return (int) MathUtils.max(status1, status2);
4570    }
4571
4572    private boolean isUserEnabled(int userId) {
4573        long callingId = Binder.clearCallingIdentity();
4574        try {
4575            UserInfo userInfo = sUserManager.getUserInfo(userId);
4576            return userInfo != null && userInfo.isEnabled();
4577        } finally {
4578            Binder.restoreCallingIdentity(callingId);
4579        }
4580    }
4581
4582    /**
4583     * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
4584     *
4585     * @return filtered list
4586     */
4587    private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
4588        if (userId == UserHandle.USER_OWNER) {
4589            return resolveInfos;
4590        }
4591        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4592            ResolveInfo info = resolveInfos.get(i);
4593            if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
4594                resolveInfos.remove(i);
4595            }
4596        }
4597        return resolveInfos;
4598    }
4599
4600    private static boolean hasWebURI(Intent intent) {
4601        if (intent.getData() == null) {
4602            return false;
4603        }
4604        final String scheme = intent.getScheme();
4605        if (TextUtils.isEmpty(scheme)) {
4606            return false;
4607        }
4608        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4609    }
4610
4611    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(
4612            int flags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo) {
4613        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4614            Slog.v("TAG", "Filtering results with preferred activities. Candidates count: " +
4615                    candidates.size());
4616        }
4617
4618        final int userId = UserHandle.getCallingUserId();
4619        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4620        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
4621        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4622        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4623        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4624
4625        synchronized (mPackages) {
4626            final int count = candidates.size();
4627            // First, try to use linked apps. Partition the candidates into four lists:
4628            // one for the final results, one for the "do not use ever", one for "undefined status"
4629            // and finally one for "browser app type".
4630            for (int n=0; n<count; n++) {
4631                ResolveInfo info = candidates.get(n);
4632                String packageName = info.activityInfo.packageName;
4633                PackageSetting ps = mSettings.mPackages.get(packageName);
4634                if (ps != null) {
4635                    // Add to the special match all list (Browser use case)
4636                    if (info.handleAllWebDataURI) {
4637                        matchAllList.add(info);
4638                        continue;
4639                    }
4640                    // Try to get the status from User settings first
4641                    int status = getDomainVerificationStatusLPr(ps, userId);
4642                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4643                        if (DEBUG_DOMAIN_VERIFICATION) {
4644                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName);
4645                        }
4646                        alwaysList.add(info);
4647                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4648                        if (DEBUG_DOMAIN_VERIFICATION) {
4649                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
4650                        }
4651                        neverList.add(info);
4652                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
4653                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
4654                        if (DEBUG_DOMAIN_VERIFICATION) {
4655                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
4656                        }
4657                        undefinedList.add(info);
4658                    }
4659                }
4660            }
4661            // First try to add the "always" resolution for the current user if there is any
4662            if (alwaysList.size() > 0) {
4663                result.addAll(alwaysList);
4664            // if there is an "always" for the parent user, add it.
4665            } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus
4666                    == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4667                result.add(xpDomainInfo.resolveInfo);
4668            } else {
4669                // Add all undefined Apps as we want them to appear in the Disambiguation dialog.
4670                result.addAll(undefinedList);
4671                if (xpDomainInfo != null && (
4672                        xpDomainInfo.bestDomainVerificationStatus
4673                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
4674                        || xpDomainInfo.bestDomainVerificationStatus
4675                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) {
4676                    result.add(xpDomainInfo.resolveInfo);
4677                }
4678                // Also add Browsers (all of them or only the default one)
4679                if ((flags & MATCH_ALL) != 0) {
4680                    result.addAll(matchAllList);
4681                } else {
4682                    // Try to add the Default Browser if we can
4683                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(
4684                            UserHandle.myUserId());
4685                    if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
4686                        boolean defaultBrowserFound = false;
4687                        final int browserCount = matchAllList.size();
4688                        for (int n=0; n<browserCount; n++) {
4689                            ResolveInfo browser = matchAllList.get(n);
4690                            if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) {
4691                                result.add(browser);
4692                                defaultBrowserFound = true;
4693                                break;
4694                            }
4695                        }
4696                        if (!defaultBrowserFound) {
4697                            result.addAll(matchAllList);
4698                        }
4699                    } else {
4700                        result.addAll(matchAllList);
4701                    }
4702                }
4703
4704                // If there is nothing selected, add all candidates and remove the ones that the user
4705                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
4706                if (result.size() == 0) {
4707                    result.addAll(candidates);
4708                    result.removeAll(neverList);
4709                }
4710            }
4711        }
4712        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4713            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
4714                    result.size());
4715            for (ResolveInfo info : result) {
4716                Slog.v(TAG, "  + " + info.activityInfo);
4717            }
4718        }
4719        return result;
4720    }
4721
4722    private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4723        int status = ps.getDomainVerificationStatusForUser(userId);
4724        // if none available, get the master status
4725        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4726            if (ps.getIntentFilterVerificationInfo() != null) {
4727                status = ps.getIntentFilterVerificationInfo().getStatus();
4728            }
4729        }
4730        return status;
4731    }
4732
4733    private ResolveInfo querySkipCurrentProfileIntents(
4734            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4735            int flags, int sourceUserId) {
4736        if (matchingFilters != null) {
4737            int size = matchingFilters.size();
4738            for (int i = 0; i < size; i ++) {
4739                CrossProfileIntentFilter filter = matchingFilters.get(i);
4740                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4741                    // Checking if there are activities in the target user that can handle the
4742                    // intent.
4743                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4744                            flags, sourceUserId);
4745                    if (resolveInfo != null) {
4746                        return resolveInfo;
4747                    }
4748                }
4749            }
4750        }
4751        return null;
4752    }
4753
4754    // Return matching ResolveInfo if any for skip current profile intent filters.
4755    private ResolveInfo queryCrossProfileIntents(
4756            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4757            int flags, int sourceUserId) {
4758        if (matchingFilters != null) {
4759            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4760            // match the same intent. For performance reasons, it is better not to
4761            // run queryIntent twice for the same userId
4762            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4763            int size = matchingFilters.size();
4764            for (int i = 0; i < size; i++) {
4765                CrossProfileIntentFilter filter = matchingFilters.get(i);
4766                int targetUserId = filter.getTargetUserId();
4767                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4768                        && !alreadyTriedUserIds.get(targetUserId)) {
4769                    // Checking if there are activities in the target user that can handle the
4770                    // intent.
4771                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4772                            flags, sourceUserId);
4773                    if (resolveInfo != null) return resolveInfo;
4774                    alreadyTriedUserIds.put(targetUserId, true);
4775                }
4776            }
4777        }
4778        return null;
4779    }
4780
4781    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
4782            String resolvedType, int flags, int sourceUserId) {
4783        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4784                resolvedType, flags, filter.getTargetUserId());
4785        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
4786            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
4787        }
4788        return null;
4789    }
4790
4791    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
4792            int sourceUserId, int targetUserId) {
4793        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4794        String className;
4795        if (targetUserId == UserHandle.USER_OWNER) {
4796            className = FORWARD_INTENT_TO_USER_OWNER;
4797        } else {
4798            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4799        }
4800        ComponentName forwardingActivityComponentName = new ComponentName(
4801                mAndroidApplication.packageName, className);
4802        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
4803                sourceUserId);
4804        if (targetUserId == UserHandle.USER_OWNER) {
4805            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
4806            forwardingResolveInfo.noResourceId = true;
4807        }
4808        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
4809        forwardingResolveInfo.priority = 0;
4810        forwardingResolveInfo.preferredOrder = 0;
4811        forwardingResolveInfo.match = 0;
4812        forwardingResolveInfo.isDefault = true;
4813        forwardingResolveInfo.filter = filter;
4814        forwardingResolveInfo.targetUserId = targetUserId;
4815        return forwardingResolveInfo;
4816    }
4817
4818    @Override
4819    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
4820            Intent[] specifics, String[] specificTypes, Intent intent,
4821            String resolvedType, int flags, int userId) {
4822        if (!sUserManager.exists(userId)) return Collections.emptyList();
4823        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
4824                false, "query intent activity options");
4825        final String resultsAction = intent.getAction();
4826
4827        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
4828                | PackageManager.GET_RESOLVED_FILTER, userId);
4829
4830        if (DEBUG_INTENT_MATCHING) {
4831            Log.v(TAG, "Query " + intent + ": " + results);
4832        }
4833
4834        int specificsPos = 0;
4835        int N;
4836
4837        // todo: note that the algorithm used here is O(N^2).  This
4838        // isn't a problem in our current environment, but if we start running
4839        // into situations where we have more than 5 or 10 matches then this
4840        // should probably be changed to something smarter...
4841
4842        // First we go through and resolve each of the specific items
4843        // that were supplied, taking care of removing any corresponding
4844        // duplicate items in the generic resolve list.
4845        if (specifics != null) {
4846            for (int i=0; i<specifics.length; i++) {
4847                final Intent sintent = specifics[i];
4848                if (sintent == null) {
4849                    continue;
4850                }
4851
4852                if (DEBUG_INTENT_MATCHING) {
4853                    Log.v(TAG, "Specific #" + i + ": " + sintent);
4854                }
4855
4856                String action = sintent.getAction();
4857                if (resultsAction != null && resultsAction.equals(action)) {
4858                    // If this action was explicitly requested, then don't
4859                    // remove things that have it.
4860                    action = null;
4861                }
4862
4863                ResolveInfo ri = null;
4864                ActivityInfo ai = null;
4865
4866                ComponentName comp = sintent.getComponent();
4867                if (comp == null) {
4868                    ri = resolveIntent(
4869                        sintent,
4870                        specificTypes != null ? specificTypes[i] : null,
4871                            flags, userId);
4872                    if (ri == null) {
4873                        continue;
4874                    }
4875                    if (ri == mResolveInfo) {
4876                        // ACK!  Must do something better with this.
4877                    }
4878                    ai = ri.activityInfo;
4879                    comp = new ComponentName(ai.applicationInfo.packageName,
4880                            ai.name);
4881                } else {
4882                    ai = getActivityInfo(comp, flags, userId);
4883                    if (ai == null) {
4884                        continue;
4885                    }
4886                }
4887
4888                // Look for any generic query activities that are duplicates
4889                // of this specific one, and remove them from the results.
4890                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
4891                N = results.size();
4892                int j;
4893                for (j=specificsPos; j<N; j++) {
4894                    ResolveInfo sri = results.get(j);
4895                    if ((sri.activityInfo.name.equals(comp.getClassName())
4896                            && sri.activityInfo.applicationInfo.packageName.equals(
4897                                    comp.getPackageName()))
4898                        || (action != null && sri.filter.matchAction(action))) {
4899                        results.remove(j);
4900                        if (DEBUG_INTENT_MATCHING) Log.v(
4901                            TAG, "Removing duplicate item from " + j
4902                            + " due to specific " + specificsPos);
4903                        if (ri == null) {
4904                            ri = sri;
4905                        }
4906                        j--;
4907                        N--;
4908                    }
4909                }
4910
4911                // Add this specific item to its proper place.
4912                if (ri == null) {
4913                    ri = new ResolveInfo();
4914                    ri.activityInfo = ai;
4915                }
4916                results.add(specificsPos, ri);
4917                ri.specificIndex = i;
4918                specificsPos++;
4919            }
4920        }
4921
4922        // Now we go through the remaining generic results and remove any
4923        // duplicate actions that are found here.
4924        N = results.size();
4925        for (int i=specificsPos; i<N-1; i++) {
4926            final ResolveInfo rii = results.get(i);
4927            if (rii.filter == null) {
4928                continue;
4929            }
4930
4931            // Iterate over all of the actions of this result's intent
4932            // filter...  typically this should be just one.
4933            final Iterator<String> it = rii.filter.actionsIterator();
4934            if (it == null) {
4935                continue;
4936            }
4937            while (it.hasNext()) {
4938                final String action = it.next();
4939                if (resultsAction != null && resultsAction.equals(action)) {
4940                    // If this action was explicitly requested, then don't
4941                    // remove things that have it.
4942                    continue;
4943                }
4944                for (int j=i+1; j<N; j++) {
4945                    final ResolveInfo rij = results.get(j);
4946                    if (rij.filter != null && rij.filter.hasAction(action)) {
4947                        results.remove(j);
4948                        if (DEBUG_INTENT_MATCHING) Log.v(
4949                            TAG, "Removing duplicate item from " + j
4950                            + " due to action " + action + " at " + i);
4951                        j--;
4952                        N--;
4953                    }
4954                }
4955            }
4956
4957            // If the caller didn't request filter information, drop it now
4958            // so we don't have to marshall/unmarshall it.
4959            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4960                rii.filter = null;
4961            }
4962        }
4963
4964        // Filter out the caller activity if so requested.
4965        if (caller != null) {
4966            N = results.size();
4967            for (int i=0; i<N; i++) {
4968                ActivityInfo ainfo = results.get(i).activityInfo;
4969                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
4970                        && caller.getClassName().equals(ainfo.name)) {
4971                    results.remove(i);
4972                    break;
4973                }
4974            }
4975        }
4976
4977        // If the caller didn't request filter information,
4978        // drop them now so we don't have to
4979        // marshall/unmarshall it.
4980        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4981            N = results.size();
4982            for (int i=0; i<N; i++) {
4983                results.get(i).filter = null;
4984            }
4985        }
4986
4987        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
4988        return results;
4989    }
4990
4991    @Override
4992    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
4993            int userId) {
4994        if (!sUserManager.exists(userId)) return Collections.emptyList();
4995        ComponentName comp = intent.getComponent();
4996        if (comp == null) {
4997            if (intent.getSelector() != null) {
4998                intent = intent.getSelector();
4999                comp = intent.getComponent();
5000            }
5001        }
5002        if (comp != null) {
5003            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5004            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5005            if (ai != null) {
5006                ResolveInfo ri = new ResolveInfo();
5007                ri.activityInfo = ai;
5008                list.add(ri);
5009            }
5010            return list;
5011        }
5012
5013        // reader
5014        synchronized (mPackages) {
5015            String pkgName = intent.getPackage();
5016            if (pkgName == null) {
5017                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5018            }
5019            final PackageParser.Package pkg = mPackages.get(pkgName);
5020            if (pkg != null) {
5021                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5022                        userId);
5023            }
5024            return null;
5025        }
5026    }
5027
5028    @Override
5029    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5030        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5031        if (!sUserManager.exists(userId)) return null;
5032        if (query != null) {
5033            if (query.size() >= 1) {
5034                // If there is more than one service with the same priority,
5035                // just arbitrarily pick the first one.
5036                return query.get(0);
5037            }
5038        }
5039        return null;
5040    }
5041
5042    @Override
5043    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5044            int userId) {
5045        if (!sUserManager.exists(userId)) return Collections.emptyList();
5046        ComponentName comp = intent.getComponent();
5047        if (comp == null) {
5048            if (intent.getSelector() != null) {
5049                intent = intent.getSelector();
5050                comp = intent.getComponent();
5051            }
5052        }
5053        if (comp != null) {
5054            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5055            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5056            if (si != null) {
5057                final ResolveInfo ri = new ResolveInfo();
5058                ri.serviceInfo = si;
5059                list.add(ri);
5060            }
5061            return list;
5062        }
5063
5064        // reader
5065        synchronized (mPackages) {
5066            String pkgName = intent.getPackage();
5067            if (pkgName == null) {
5068                return mServices.queryIntent(intent, resolvedType, flags, userId);
5069            }
5070            final PackageParser.Package pkg = mPackages.get(pkgName);
5071            if (pkg != null) {
5072                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5073                        userId);
5074            }
5075            return null;
5076        }
5077    }
5078
5079    @Override
5080    public List<ResolveInfo> queryIntentContentProviders(
5081            Intent intent, String resolvedType, int flags, int userId) {
5082        if (!sUserManager.exists(userId)) return Collections.emptyList();
5083        ComponentName comp = intent.getComponent();
5084        if (comp == null) {
5085            if (intent.getSelector() != null) {
5086                intent = intent.getSelector();
5087                comp = intent.getComponent();
5088            }
5089        }
5090        if (comp != null) {
5091            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5092            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5093            if (pi != null) {
5094                final ResolveInfo ri = new ResolveInfo();
5095                ri.providerInfo = pi;
5096                list.add(ri);
5097            }
5098            return list;
5099        }
5100
5101        // reader
5102        synchronized (mPackages) {
5103            String pkgName = intent.getPackage();
5104            if (pkgName == null) {
5105                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5106            }
5107            final PackageParser.Package pkg = mPackages.get(pkgName);
5108            if (pkg != null) {
5109                return mProviders.queryIntentForPackage(
5110                        intent, resolvedType, flags, pkg.providers, userId);
5111            }
5112            return null;
5113        }
5114    }
5115
5116    @Override
5117    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5118        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5119
5120        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5121
5122        // writer
5123        synchronized (mPackages) {
5124            ArrayList<PackageInfo> list;
5125            if (listUninstalled) {
5126                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5127                for (PackageSetting ps : mSettings.mPackages.values()) {
5128                    PackageInfo pi;
5129                    if (ps.pkg != null) {
5130                        pi = generatePackageInfo(ps.pkg, flags, userId);
5131                    } else {
5132                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5133                    }
5134                    if (pi != null) {
5135                        list.add(pi);
5136                    }
5137                }
5138            } else {
5139                list = new ArrayList<PackageInfo>(mPackages.size());
5140                for (PackageParser.Package p : mPackages.values()) {
5141                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5142                    if (pi != null) {
5143                        list.add(pi);
5144                    }
5145                }
5146            }
5147
5148            return new ParceledListSlice<PackageInfo>(list);
5149        }
5150    }
5151
5152    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5153            String[] permissions, boolean[] tmp, int flags, int userId) {
5154        int numMatch = 0;
5155        final PermissionsState permissionsState = ps.getPermissionsState();
5156        for (int i=0; i<permissions.length; i++) {
5157            final String permission = permissions[i];
5158            if (permissionsState.hasPermission(permission, userId)) {
5159                tmp[i] = true;
5160                numMatch++;
5161            } else {
5162                tmp[i] = false;
5163            }
5164        }
5165        if (numMatch == 0) {
5166            return;
5167        }
5168        PackageInfo pi;
5169        if (ps.pkg != null) {
5170            pi = generatePackageInfo(ps.pkg, flags, userId);
5171        } else {
5172            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5173        }
5174        // The above might return null in cases of uninstalled apps or install-state
5175        // skew across users/profiles.
5176        if (pi != null) {
5177            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5178                if (numMatch == permissions.length) {
5179                    pi.requestedPermissions = permissions;
5180                } else {
5181                    pi.requestedPermissions = new String[numMatch];
5182                    numMatch = 0;
5183                    for (int i=0; i<permissions.length; i++) {
5184                        if (tmp[i]) {
5185                            pi.requestedPermissions[numMatch] = permissions[i];
5186                            numMatch++;
5187                        }
5188                    }
5189                }
5190            }
5191            list.add(pi);
5192        }
5193    }
5194
5195    @Override
5196    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5197            String[] permissions, int flags, int userId) {
5198        if (!sUserManager.exists(userId)) return null;
5199        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5200
5201        // writer
5202        synchronized (mPackages) {
5203            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5204            boolean[] tmpBools = new boolean[permissions.length];
5205            if (listUninstalled) {
5206                for (PackageSetting ps : mSettings.mPackages.values()) {
5207                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5208                }
5209            } else {
5210                for (PackageParser.Package pkg : mPackages.values()) {
5211                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5212                    if (ps != null) {
5213                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5214                                userId);
5215                    }
5216                }
5217            }
5218
5219            return new ParceledListSlice<PackageInfo>(list);
5220        }
5221    }
5222
5223    @Override
5224    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5225        if (!sUserManager.exists(userId)) return null;
5226        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5227
5228        // writer
5229        synchronized (mPackages) {
5230            ArrayList<ApplicationInfo> list;
5231            if (listUninstalled) {
5232                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5233                for (PackageSetting ps : mSettings.mPackages.values()) {
5234                    ApplicationInfo ai;
5235                    if (ps.pkg != null) {
5236                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5237                                ps.readUserState(userId), userId);
5238                    } else {
5239                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5240                    }
5241                    if (ai != null) {
5242                        list.add(ai);
5243                    }
5244                }
5245            } else {
5246                list = new ArrayList<ApplicationInfo>(mPackages.size());
5247                for (PackageParser.Package p : mPackages.values()) {
5248                    if (p.mExtras != null) {
5249                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5250                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5251                        if (ai != null) {
5252                            list.add(ai);
5253                        }
5254                    }
5255                }
5256            }
5257
5258            return new ParceledListSlice<ApplicationInfo>(list);
5259        }
5260    }
5261
5262    public List<ApplicationInfo> getPersistentApplications(int flags) {
5263        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5264
5265        // reader
5266        synchronized (mPackages) {
5267            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5268            final int userId = UserHandle.getCallingUserId();
5269            while (i.hasNext()) {
5270                final PackageParser.Package p = i.next();
5271                if (p.applicationInfo != null
5272                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5273                        && (!mSafeMode || isSystemApp(p))) {
5274                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5275                    if (ps != null) {
5276                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5277                                ps.readUserState(userId), userId);
5278                        if (ai != null) {
5279                            finalList.add(ai);
5280                        }
5281                    }
5282                }
5283            }
5284        }
5285
5286        return finalList;
5287    }
5288
5289    @Override
5290    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5291        if (!sUserManager.exists(userId)) return null;
5292        // reader
5293        synchronized (mPackages) {
5294            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5295            PackageSetting ps = provider != null
5296                    ? mSettings.mPackages.get(provider.owner.packageName)
5297                    : null;
5298            return ps != null
5299                    && mSettings.isEnabledLPr(provider.info, flags, userId)
5300                    && (!mSafeMode || (provider.info.applicationInfo.flags
5301                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5302                    ? PackageParser.generateProviderInfo(provider, flags,
5303                            ps.readUserState(userId), userId)
5304                    : null;
5305        }
5306    }
5307
5308    /**
5309     * @deprecated
5310     */
5311    @Deprecated
5312    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5313        // reader
5314        synchronized (mPackages) {
5315            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5316                    .entrySet().iterator();
5317            final int userId = UserHandle.getCallingUserId();
5318            while (i.hasNext()) {
5319                Map.Entry<String, PackageParser.Provider> entry = i.next();
5320                PackageParser.Provider p = entry.getValue();
5321                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5322
5323                if (ps != null && p.syncable
5324                        && (!mSafeMode || (p.info.applicationInfo.flags
5325                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5326                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5327                            ps.readUserState(userId), userId);
5328                    if (info != null) {
5329                        outNames.add(entry.getKey());
5330                        outInfo.add(info);
5331                    }
5332                }
5333            }
5334        }
5335    }
5336
5337    @Override
5338    public List<ProviderInfo> queryContentProviders(String processName,
5339            int uid, int flags) {
5340        ArrayList<ProviderInfo> finalList = null;
5341        // reader
5342        synchronized (mPackages) {
5343            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5344            final int userId = processName != null ?
5345                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
5346            while (i.hasNext()) {
5347                final PackageParser.Provider p = i.next();
5348                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5349                if (ps != null && p.info.authority != null
5350                        && (processName == null
5351                                || (p.info.processName.equals(processName)
5352                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5353                        && mSettings.isEnabledLPr(p.info, flags, userId)
5354                        && (!mSafeMode
5355                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5356                    if (finalList == null) {
5357                        finalList = new ArrayList<ProviderInfo>(3);
5358                    }
5359                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5360                            ps.readUserState(userId), userId);
5361                    if (info != null) {
5362                        finalList.add(info);
5363                    }
5364                }
5365            }
5366        }
5367
5368        if (finalList != null) {
5369            Collections.sort(finalList, mProviderInitOrderSorter);
5370        }
5371
5372        return finalList;
5373    }
5374
5375    @Override
5376    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
5377            int flags) {
5378        // reader
5379        synchronized (mPackages) {
5380            final PackageParser.Instrumentation i = mInstrumentation.get(name);
5381            return PackageParser.generateInstrumentationInfo(i, flags);
5382        }
5383    }
5384
5385    @Override
5386    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
5387            int flags) {
5388        ArrayList<InstrumentationInfo> finalList =
5389            new ArrayList<InstrumentationInfo>();
5390
5391        // reader
5392        synchronized (mPackages) {
5393            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
5394            while (i.hasNext()) {
5395                final PackageParser.Instrumentation p = i.next();
5396                if (targetPackage == null
5397                        || targetPackage.equals(p.info.targetPackage)) {
5398                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
5399                            flags);
5400                    if (ii != null) {
5401                        finalList.add(ii);
5402                    }
5403                }
5404            }
5405        }
5406
5407        return finalList;
5408    }
5409
5410    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
5411        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
5412        if (overlays == null) {
5413            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
5414            return;
5415        }
5416        for (PackageParser.Package opkg : overlays.values()) {
5417            // Not much to do if idmap fails: we already logged the error
5418            // and we certainly don't want to abort installation of pkg simply
5419            // because an overlay didn't fit properly. For these reasons,
5420            // ignore the return value of createIdmapForPackagePairLI.
5421            createIdmapForPackagePairLI(pkg, opkg);
5422        }
5423    }
5424
5425    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
5426            PackageParser.Package opkg) {
5427        if (!opkg.mTrustedOverlay) {
5428            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
5429                    opkg.baseCodePath + ": overlay not trusted");
5430            return false;
5431        }
5432        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
5433        if (overlaySet == null) {
5434            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
5435                    opkg.baseCodePath + " but target package has no known overlays");
5436            return false;
5437        }
5438        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
5439        // TODO: generate idmap for split APKs
5440        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
5441            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
5442                    + opkg.baseCodePath);
5443            return false;
5444        }
5445        PackageParser.Package[] overlayArray =
5446            overlaySet.values().toArray(new PackageParser.Package[0]);
5447        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
5448            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
5449                return p1.mOverlayPriority - p2.mOverlayPriority;
5450            }
5451        };
5452        Arrays.sort(overlayArray, cmp);
5453
5454        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5455        int i = 0;
5456        for (PackageParser.Package p : overlayArray) {
5457            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5458        }
5459        return true;
5460    }
5461
5462    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5463        final File[] files = dir.listFiles();
5464        if (ArrayUtils.isEmpty(files)) {
5465            Log.d(TAG, "No files in app dir " + dir);
5466            return;
5467        }
5468
5469        if (DEBUG_PACKAGE_SCANNING) {
5470            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
5471                    + " flags=0x" + Integer.toHexString(parseFlags));
5472        }
5473
5474        for (File file : files) {
5475            final boolean isPackage = (isApkFile(file) || file.isDirectory())
5476                    && !PackageInstallerService.isStageName(file.getName());
5477            if (!isPackage) {
5478                // Ignore entries which are not packages
5479                continue;
5480            }
5481            try {
5482                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
5483                        scanFlags, currentTime, null);
5484            } catch (PackageManagerException e) {
5485                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
5486
5487                // Delete invalid userdata apps
5488                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
5489                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
5490                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
5491                    if (file.isDirectory()) {
5492                        mInstaller.rmPackageDir(file.getAbsolutePath());
5493                    } else {
5494                        file.delete();
5495                    }
5496                }
5497            }
5498        }
5499    }
5500
5501    private static File getSettingsProblemFile() {
5502        File dataDir = Environment.getDataDirectory();
5503        File systemDir = new File(dataDir, "system");
5504        File fname = new File(systemDir, "uiderrors.txt");
5505        return fname;
5506    }
5507
5508    static void reportSettingsProblem(int priority, String msg) {
5509        logCriticalInfo(priority, msg);
5510    }
5511
5512    static void logCriticalInfo(int priority, String msg) {
5513        Slog.println(priority, TAG, msg);
5514        EventLogTags.writePmCriticalInfo(msg);
5515        try {
5516            File fname = getSettingsProblemFile();
5517            FileOutputStream out = new FileOutputStream(fname, true);
5518            PrintWriter pw = new FastPrintWriter(out);
5519            SimpleDateFormat formatter = new SimpleDateFormat();
5520            String dateString = formatter.format(new Date(System.currentTimeMillis()));
5521            pw.println(dateString + ": " + msg);
5522            pw.close();
5523            FileUtils.setPermissions(
5524                    fname.toString(),
5525                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5526                    -1, -1);
5527        } catch (java.io.IOException e) {
5528        }
5529    }
5530
5531    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5532            PackageParser.Package pkg, File srcFile, int parseFlags)
5533            throws PackageManagerException {
5534        if (ps != null
5535                && ps.codePath.equals(srcFile)
5536                && ps.timeStamp == srcFile.lastModified()
5537                && !isCompatSignatureUpdateNeeded(pkg)
5538                && !isRecoverSignatureUpdateNeeded(pkg)) {
5539            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5540            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5541            ArraySet<PublicKey> signingKs;
5542            synchronized (mPackages) {
5543                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
5544            }
5545            if (ps.signatures.mSignatures != null
5546                    && ps.signatures.mSignatures.length != 0
5547                    && signingKs != null) {
5548                // Optimization: reuse the existing cached certificates
5549                // if the package appears to be unchanged.
5550                pkg.mSignatures = ps.signatures.mSignatures;
5551                pkg.mSigningKeys = signingKs;
5552                return;
5553            }
5554
5555            Slog.w(TAG, "PackageSetting for " + ps.name
5556                    + " is missing signatures.  Collecting certs again to recover them.");
5557        } else {
5558            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
5559        }
5560
5561        try {
5562            pp.collectCertificates(pkg, parseFlags);
5563            pp.collectManifestDigest(pkg);
5564        } catch (PackageParserException e) {
5565            throw PackageManagerException.from(e);
5566        }
5567    }
5568
5569    /*
5570     *  Scan a package and return the newly parsed package.
5571     *  Returns null in case of errors and the error code is stored in mLastScanError
5572     */
5573    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
5574            long currentTime, UserHandle user) throws PackageManagerException {
5575        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
5576        parseFlags |= mDefParseFlags;
5577        PackageParser pp = new PackageParser();
5578        pp.setSeparateProcesses(mSeparateProcesses);
5579        pp.setOnlyCoreApps(mOnlyCore);
5580        pp.setDisplayMetrics(mMetrics);
5581
5582        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
5583            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
5584        }
5585
5586        final PackageParser.Package pkg;
5587        try {
5588            pkg = pp.parsePackage(scanFile, parseFlags);
5589        } catch (PackageParserException e) {
5590            throw PackageManagerException.from(e);
5591        }
5592
5593        PackageSetting ps = null;
5594        PackageSetting updatedPkg;
5595        // reader
5596        synchronized (mPackages) {
5597            // Look to see if we already know about this package.
5598            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
5599            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
5600                // This package has been renamed to its original name.  Let's
5601                // use that.
5602                ps = mSettings.peekPackageLPr(oldName);
5603            }
5604            // If there was no original package, see one for the real package name.
5605            if (ps == null) {
5606                ps = mSettings.peekPackageLPr(pkg.packageName);
5607            }
5608            // Check to see if this package could be hiding/updating a system
5609            // package.  Must look for it either under the original or real
5610            // package name depending on our state.
5611            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
5612            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
5613        }
5614        boolean updatedPkgBetter = false;
5615        // First check if this is a system package that may involve an update
5616        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5617            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
5618            // it needs to drop FLAG_PRIVILEGED.
5619            if (locationIsPrivileged(scanFile)) {
5620                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5621            } else {
5622                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5623            }
5624
5625            if (ps != null && !ps.codePath.equals(scanFile)) {
5626                // The path has changed from what was last scanned...  check the
5627                // version of the new path against what we have stored to determine
5628                // what to do.
5629                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
5630                if (pkg.mVersionCode <= ps.versionCode) {
5631                    // The system package has been updated and the code path does not match
5632                    // Ignore entry. Skip it.
5633                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5634                            + " ignored: updated version " + ps.versionCode
5635                            + " better than this " + pkg.mVersionCode);
5636                    if (!updatedPkg.codePath.equals(scanFile)) {
5637                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5638                                + ps.name + " changing from " + updatedPkg.codePathString
5639                                + " to " + scanFile);
5640                        updatedPkg.codePath = scanFile;
5641                        updatedPkg.codePathString = scanFile.toString();
5642                        updatedPkg.resourcePath = scanFile;
5643                        updatedPkg.resourcePathString = scanFile.toString();
5644                    }
5645                    updatedPkg.pkg = pkg;
5646                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5647                            "Package " + ps.name + " at " + scanFile
5648                                    + " ignored: updated version " + ps.versionCode
5649                                    + " better than this " + pkg.mVersionCode);
5650                } else {
5651                    // The current app on the system partition is better than
5652                    // what we have updated to on the data partition; switch
5653                    // back to the system partition version.
5654                    // At this point, its safely assumed that package installation for
5655                    // apps in system partition will go through. If not there won't be a working
5656                    // version of the app
5657                    // writer
5658                    synchronized (mPackages) {
5659                        // Just remove the loaded entries from package lists.
5660                        mPackages.remove(ps.name);
5661                    }
5662
5663                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5664                            + " reverting from " + ps.codePathString
5665                            + ": new version " + pkg.mVersionCode
5666                            + " better than installed " + ps.versionCode);
5667
5668                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5669                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5670                    synchronized (mInstallLock) {
5671                        args.cleanUpResourcesLI();
5672                    }
5673                    synchronized (mPackages) {
5674                        mSettings.enableSystemPackageLPw(ps.name);
5675                    }
5676                    updatedPkgBetter = true;
5677                }
5678            }
5679        }
5680
5681        if (updatedPkg != null) {
5682            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5683            // initially
5684            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5685
5686            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5687            // flag set initially
5688            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5689                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5690            }
5691        }
5692
5693        // Verify certificates against what was last scanned
5694        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5695
5696        /*
5697         * A new system app appeared, but we already had a non-system one of the
5698         * same name installed earlier.
5699         */
5700        boolean shouldHideSystemApp = false;
5701        if (updatedPkg == null && ps != null
5702                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5703            /*
5704             * Check to make sure the signatures match first. If they don't,
5705             * wipe the installed application and its data.
5706             */
5707            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5708                    != PackageManager.SIGNATURE_MATCH) {
5709                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5710                        + " signatures don't match existing userdata copy; removing");
5711                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5712                ps = null;
5713            } else {
5714                /*
5715                 * If the newly-added system app is an older version than the
5716                 * already installed version, hide it. It will be scanned later
5717                 * and re-added like an update.
5718                 */
5719                if (pkg.mVersionCode <= ps.versionCode) {
5720                    shouldHideSystemApp = true;
5721                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5722                            + " but new version " + pkg.mVersionCode + " better than installed "
5723                            + ps.versionCode + "; hiding system");
5724                } else {
5725                    /*
5726                     * The newly found system app is a newer version that the
5727                     * one previously installed. Simply remove the
5728                     * already-installed application and replace it with our own
5729                     * while keeping the application data.
5730                     */
5731                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5732                            + " reverting from " + ps.codePathString + ": new version "
5733                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5734                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5735                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5736                    synchronized (mInstallLock) {
5737                        args.cleanUpResourcesLI();
5738                    }
5739                }
5740            }
5741        }
5742
5743        // The apk is forward locked (not public) if its code and resources
5744        // are kept in different files. (except for app in either system or
5745        // vendor path).
5746        // TODO grab this value from PackageSettings
5747        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5748            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5749                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5750            }
5751        }
5752
5753        // TODO: extend to support forward-locked splits
5754        String resourcePath = null;
5755        String baseResourcePath = null;
5756        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5757            if (ps != null && ps.resourcePathString != null) {
5758                resourcePath = ps.resourcePathString;
5759                baseResourcePath = ps.resourcePathString;
5760            } else {
5761                // Should not happen at all. Just log an error.
5762                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5763            }
5764        } else {
5765            resourcePath = pkg.codePath;
5766            baseResourcePath = pkg.baseCodePath;
5767        }
5768
5769        // Set application objects path explicitly.
5770        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
5771        pkg.applicationInfo.setCodePath(pkg.codePath);
5772        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5773        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5774        pkg.applicationInfo.setResourcePath(resourcePath);
5775        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5776        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5777
5778        // Note that we invoke the following method only if we are about to unpack an application
5779        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5780                | SCAN_UPDATE_SIGNATURE, currentTime, user);
5781
5782        /*
5783         * If the system app should be overridden by a previously installed
5784         * data, hide the system app now and let the /data/app scan pick it up
5785         * again.
5786         */
5787        if (shouldHideSystemApp) {
5788            synchronized (mPackages) {
5789                /*
5790                 * We have to grant systems permissions before we hide, because
5791                 * grantPermissions will assume the package update is trying to
5792                 * expand its permissions.
5793                 */
5794                grantPermissionsLPw(pkg, true, pkg.packageName);
5795                mSettings.disableSystemPackageLPw(pkg.packageName);
5796            }
5797        }
5798
5799        return scannedPkg;
5800    }
5801
5802    private static String fixProcessName(String defProcessName,
5803            String processName, int uid) {
5804        if (processName == null) {
5805            return defProcessName;
5806        }
5807        return processName;
5808    }
5809
5810    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
5811            throws PackageManagerException {
5812        if (pkgSetting.signatures.mSignatures != null) {
5813            // Already existing package. Make sure signatures match
5814            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
5815                    == PackageManager.SIGNATURE_MATCH;
5816            if (!match) {
5817                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
5818                        == PackageManager.SIGNATURE_MATCH;
5819            }
5820            if (!match) {
5821                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
5822                        == PackageManager.SIGNATURE_MATCH;
5823            }
5824            if (!match) {
5825                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5826                        + pkg.packageName + " signatures do not match the "
5827                        + "previously installed version; ignoring!");
5828            }
5829        }
5830
5831        // Check for shared user signatures
5832        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
5833            // Already existing package. Make sure signatures match
5834            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5835                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
5836            if (!match) {
5837                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
5838                        == PackageManager.SIGNATURE_MATCH;
5839            }
5840            if (!match) {
5841                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
5842                        == PackageManager.SIGNATURE_MATCH;
5843            }
5844            if (!match) {
5845                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
5846                        "Package " + pkg.packageName
5847                        + " has no signatures that match those in shared user "
5848                        + pkgSetting.sharedUser.name + "; ignoring!");
5849            }
5850        }
5851    }
5852
5853    /**
5854     * Enforces that only the system UID or root's UID can call a method exposed
5855     * via Binder.
5856     *
5857     * @param message used as message if SecurityException is thrown
5858     * @throws SecurityException if the caller is not system or root
5859     */
5860    private static final void enforceSystemOrRoot(String message) {
5861        final int uid = Binder.getCallingUid();
5862        if (uid != Process.SYSTEM_UID && uid != 0) {
5863            throw new SecurityException(message);
5864        }
5865    }
5866
5867    @Override
5868    public void performBootDexOpt() {
5869        enforceSystemOrRoot("Only the system can request dexopt be performed");
5870
5871        // Before everything else, see whether we need to fstrim.
5872        try {
5873            IMountService ms = PackageHelper.getMountService();
5874            if (ms != null) {
5875                final boolean isUpgrade = isUpgrade();
5876                boolean doTrim = isUpgrade;
5877                if (doTrim) {
5878                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
5879                } else {
5880                    final long interval = android.provider.Settings.Global.getLong(
5881                            mContext.getContentResolver(),
5882                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
5883                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
5884                    if (interval > 0) {
5885                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
5886                        if (timeSinceLast > interval) {
5887                            doTrim = true;
5888                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
5889                                    + "; running immediately");
5890                        }
5891                    }
5892                }
5893                if (doTrim) {
5894                    if (!isFirstBoot()) {
5895                        try {
5896                            ActivityManagerNative.getDefault().showBootMessage(
5897                                    mContext.getResources().getString(
5898                                            R.string.android_upgrading_fstrim), true);
5899                        } catch (RemoteException e) {
5900                        }
5901                    }
5902                    ms.runMaintenance();
5903                }
5904            } else {
5905                Slog.e(TAG, "Mount service unavailable!");
5906            }
5907        } catch (RemoteException e) {
5908            // Can't happen; MountService is local
5909        }
5910
5911        final ArraySet<PackageParser.Package> pkgs;
5912        synchronized (mPackages) {
5913            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
5914        }
5915
5916        if (pkgs != null) {
5917            // Sort apps by importance for dexopt ordering. Important apps are given more priority
5918            // in case the device runs out of space.
5919            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
5920            // Give priority to core apps.
5921            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5922                PackageParser.Package pkg = it.next();
5923                if (pkg.coreApp) {
5924                    if (DEBUG_DEXOPT) {
5925                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
5926                    }
5927                    sortedPkgs.add(pkg);
5928                    it.remove();
5929                }
5930            }
5931            // Give priority to system apps that listen for pre boot complete.
5932            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
5933            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
5934            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5935                PackageParser.Package pkg = it.next();
5936                if (pkgNames.contains(pkg.packageName)) {
5937                    if (DEBUG_DEXOPT) {
5938                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
5939                    }
5940                    sortedPkgs.add(pkg);
5941                    it.remove();
5942                }
5943            }
5944            // Give priority to system apps.
5945            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5946                PackageParser.Package pkg = it.next();
5947                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
5948                    if (DEBUG_DEXOPT) {
5949                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
5950                    }
5951                    sortedPkgs.add(pkg);
5952                    it.remove();
5953                }
5954            }
5955            // Give priority to updated system apps.
5956            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5957                PackageParser.Package pkg = it.next();
5958                if (pkg.isUpdatedSystemApp()) {
5959                    if (DEBUG_DEXOPT) {
5960                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
5961                    }
5962                    sortedPkgs.add(pkg);
5963                    it.remove();
5964                }
5965            }
5966            // Give priority to apps that listen for boot complete.
5967            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
5968            pkgNames = getPackageNamesForIntent(intent);
5969            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5970                PackageParser.Package pkg = it.next();
5971                if (pkgNames.contains(pkg.packageName)) {
5972                    if (DEBUG_DEXOPT) {
5973                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
5974                    }
5975                    sortedPkgs.add(pkg);
5976                    it.remove();
5977                }
5978            }
5979            // Filter out packages that aren't recently used.
5980            filterRecentlyUsedApps(pkgs);
5981            // Add all remaining apps.
5982            for (PackageParser.Package pkg : pkgs) {
5983                if (DEBUG_DEXOPT) {
5984                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
5985                }
5986                sortedPkgs.add(pkg);
5987            }
5988
5989            // If we want to be lazy, filter everything that wasn't recently used.
5990            if (mLazyDexOpt) {
5991                filterRecentlyUsedApps(sortedPkgs);
5992            }
5993
5994            int i = 0;
5995            int total = sortedPkgs.size();
5996            File dataDir = Environment.getDataDirectory();
5997            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
5998            if (lowThreshold == 0) {
5999                throw new IllegalStateException("Invalid low memory threshold");
6000            }
6001            for (PackageParser.Package pkg : sortedPkgs) {
6002                long usableSpace = dataDir.getUsableSpace();
6003                if (usableSpace < lowThreshold) {
6004                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
6005                    break;
6006                }
6007                performBootDexOpt(pkg, ++i, total);
6008            }
6009        }
6010    }
6011
6012    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
6013        // Filter out packages that aren't recently used.
6014        //
6015        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
6016        // should do a full dexopt.
6017        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
6018            int total = pkgs.size();
6019            int skipped = 0;
6020            long now = System.currentTimeMillis();
6021            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
6022                PackageParser.Package pkg = i.next();
6023                long then = pkg.mLastPackageUsageTimeInMills;
6024                if (then + mDexOptLRUThresholdInMills < now) {
6025                    if (DEBUG_DEXOPT) {
6026                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
6027                              ((then == 0) ? "never" : new Date(then)));
6028                    }
6029                    i.remove();
6030                    skipped++;
6031                }
6032            }
6033            if (DEBUG_DEXOPT) {
6034                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
6035            }
6036        }
6037    }
6038
6039    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
6040        List<ResolveInfo> ris = null;
6041        try {
6042            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6043                    intent, null, 0, UserHandle.USER_OWNER);
6044        } catch (RemoteException e) {
6045        }
6046        ArraySet<String> pkgNames = new ArraySet<String>();
6047        if (ris != null) {
6048            for (ResolveInfo ri : ris) {
6049                pkgNames.add(ri.activityInfo.packageName);
6050            }
6051        }
6052        return pkgNames;
6053    }
6054
6055    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
6056        if (DEBUG_DEXOPT) {
6057            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
6058        }
6059        if (!isFirstBoot()) {
6060            try {
6061                ActivityManagerNative.getDefault().showBootMessage(
6062                        mContext.getResources().getString(R.string.android_upgrading_apk,
6063                                curr, total), true);
6064            } catch (RemoteException e) {
6065            }
6066        }
6067        PackageParser.Package p = pkg;
6068        synchronized (mInstallLock) {
6069            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
6070                    false /* force dex */, false /* defer */, true /* include dependencies */);
6071        }
6072    }
6073
6074    @Override
6075    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6076        return performDexOpt(packageName, instructionSet, false);
6077    }
6078
6079    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
6080        boolean dexopt = mLazyDexOpt || backgroundDexopt;
6081        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
6082        if (!dexopt && !updateUsage) {
6083            // We aren't going to dexopt or update usage, so bail early.
6084            return false;
6085        }
6086        PackageParser.Package p;
6087        final String targetInstructionSet;
6088        synchronized (mPackages) {
6089            p = mPackages.get(packageName);
6090            if (p == null) {
6091                return false;
6092            }
6093            if (updateUsage) {
6094                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6095            }
6096            mPackageUsage.write(false);
6097            if (!dexopt) {
6098                // We aren't going to dexopt, so bail early.
6099                return false;
6100            }
6101
6102            targetInstructionSet = instructionSet != null ? instructionSet :
6103                    getPrimaryInstructionSet(p.applicationInfo);
6104            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
6105                return false;
6106            }
6107        }
6108
6109        synchronized (mInstallLock) {
6110            final String[] instructionSets = new String[] { targetInstructionSet };
6111            int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6112                    false /* forceDex */, false /* defer */, true /* inclDependencies */);
6113            return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6114        }
6115    }
6116
6117    public ArraySet<String> getPackagesThatNeedDexOpt() {
6118        ArraySet<String> pkgs = null;
6119        synchronized (mPackages) {
6120            for (PackageParser.Package p : mPackages.values()) {
6121                if (DEBUG_DEXOPT) {
6122                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6123                }
6124                if (!p.mDexOptPerformed.isEmpty()) {
6125                    continue;
6126                }
6127                if (pkgs == null) {
6128                    pkgs = new ArraySet<String>();
6129                }
6130                pkgs.add(p.packageName);
6131            }
6132        }
6133        return pkgs;
6134    }
6135
6136    public void shutdown() {
6137        mPackageUsage.write(true);
6138    }
6139
6140    @Override
6141    public void forceDexOpt(String packageName) {
6142        enforceSystemOrRoot("forceDexOpt");
6143
6144        PackageParser.Package pkg;
6145        synchronized (mPackages) {
6146            pkg = mPackages.get(packageName);
6147            if (pkg == null) {
6148                throw new IllegalArgumentException("Missing package: " + packageName);
6149            }
6150        }
6151
6152        synchronized (mInstallLock) {
6153            final String[] instructionSets = new String[] {
6154                    getPrimaryInstructionSet(pkg.applicationInfo) };
6155            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6156                    true /*forceDex*/, false /* defer */, true /* inclDependencies */);
6157            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6158                throw new IllegalStateException("Failed to dexopt: " + res);
6159            }
6160        }
6161    }
6162
6163    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6164        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6165            Slog.w(TAG, "Unable to update from " + oldPkg.name
6166                    + " to " + newPkg.packageName
6167                    + ": old package not in system partition");
6168            return false;
6169        } else if (mPackages.get(oldPkg.name) != null) {
6170            Slog.w(TAG, "Unable to update from " + oldPkg.name
6171                    + " to " + newPkg.packageName
6172                    + ": old package still exists");
6173            return false;
6174        }
6175        return true;
6176    }
6177
6178    private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
6179        int[] users = sUserManager.getUserIds();
6180        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
6181        if (res < 0) {
6182            return res;
6183        }
6184        for (int user : users) {
6185            if (user != 0) {
6186                res = mInstaller.createUserData(volumeUuid, packageName,
6187                        UserHandle.getUid(user, uid), user, seinfo);
6188                if (res < 0) {
6189                    return res;
6190                }
6191            }
6192        }
6193        return res;
6194    }
6195
6196    private int removeDataDirsLI(String volumeUuid, String packageName) {
6197        int[] users = sUserManager.getUserIds();
6198        int res = 0;
6199        for (int user : users) {
6200            int resInner = mInstaller.remove(volumeUuid, packageName, user);
6201            if (resInner < 0) {
6202                res = resInner;
6203            }
6204        }
6205
6206        return res;
6207    }
6208
6209    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6210        int[] users = sUserManager.getUserIds();
6211        int res = 0;
6212        for (int user : users) {
6213            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
6214            if (resInner < 0) {
6215                res = resInner;
6216            }
6217        }
6218        return res;
6219    }
6220
6221    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6222            PackageParser.Package changingLib) {
6223        if (file.path != null) {
6224            usesLibraryFiles.add(file.path);
6225            return;
6226        }
6227        PackageParser.Package p = mPackages.get(file.apk);
6228        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6229            // If we are doing this while in the middle of updating a library apk,
6230            // then we need to make sure to use that new apk for determining the
6231            // dependencies here.  (We haven't yet finished committing the new apk
6232            // to the package manager state.)
6233            if (p == null || p.packageName.equals(changingLib.packageName)) {
6234                p = changingLib;
6235            }
6236        }
6237        if (p != null) {
6238            usesLibraryFiles.addAll(p.getAllCodePaths());
6239        }
6240    }
6241
6242    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6243            PackageParser.Package changingLib) throws PackageManagerException {
6244        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6245            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6246            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6247            for (int i=0; i<N; i++) {
6248                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6249                if (file == null) {
6250                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6251                            "Package " + pkg.packageName + " requires unavailable shared library "
6252                            + pkg.usesLibraries.get(i) + "; failing!");
6253                }
6254                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6255            }
6256            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6257            for (int i=0; i<N; i++) {
6258                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6259                if (file == null) {
6260                    Slog.w(TAG, "Package " + pkg.packageName
6261                            + " desires unavailable shared library "
6262                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6263                } else {
6264                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6265                }
6266            }
6267            N = usesLibraryFiles.size();
6268            if (N > 0) {
6269                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6270            } else {
6271                pkg.usesLibraryFiles = null;
6272            }
6273        }
6274    }
6275
6276    private static boolean hasString(List<String> list, List<String> which) {
6277        if (list == null) {
6278            return false;
6279        }
6280        for (int i=list.size()-1; i>=0; i--) {
6281            for (int j=which.size()-1; j>=0; j--) {
6282                if (which.get(j).equals(list.get(i))) {
6283                    return true;
6284                }
6285            }
6286        }
6287        return false;
6288    }
6289
6290    private void updateAllSharedLibrariesLPw() {
6291        for (PackageParser.Package pkg : mPackages.values()) {
6292            try {
6293                updateSharedLibrariesLPw(pkg, null);
6294            } catch (PackageManagerException e) {
6295                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6296            }
6297        }
6298    }
6299
6300    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6301            PackageParser.Package changingPkg) {
6302        ArrayList<PackageParser.Package> res = null;
6303        for (PackageParser.Package pkg : mPackages.values()) {
6304            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6305                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6306                if (res == null) {
6307                    res = new ArrayList<PackageParser.Package>();
6308                }
6309                res.add(pkg);
6310                try {
6311                    updateSharedLibrariesLPw(pkg, changingPkg);
6312                } catch (PackageManagerException e) {
6313                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6314                }
6315            }
6316        }
6317        return res;
6318    }
6319
6320    /**
6321     * Derive the value of the {@code cpuAbiOverride} based on the provided
6322     * value and an optional stored value from the package settings.
6323     */
6324    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6325        String cpuAbiOverride = null;
6326
6327        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6328            cpuAbiOverride = null;
6329        } else if (abiOverride != null) {
6330            cpuAbiOverride = abiOverride;
6331        } else if (settings != null) {
6332            cpuAbiOverride = settings.cpuAbiOverrideString;
6333        }
6334
6335        return cpuAbiOverride;
6336    }
6337
6338    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6339            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6340        boolean success = false;
6341        try {
6342            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6343                    currentTime, user);
6344            success = true;
6345            return res;
6346        } finally {
6347            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6348                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6349            }
6350        }
6351    }
6352
6353    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6354            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6355        final File scanFile = new File(pkg.codePath);
6356        if (pkg.applicationInfo.getCodePath() == null ||
6357                pkg.applicationInfo.getResourcePath() == null) {
6358            // Bail out. The resource and code paths haven't been set.
6359            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6360                    "Code and resource paths haven't been set correctly");
6361        }
6362
6363        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6364            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6365        } else {
6366            // Only allow system apps to be flagged as core apps.
6367            pkg.coreApp = false;
6368        }
6369
6370        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6371            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6372        }
6373
6374        if (mCustomResolverComponentName != null &&
6375                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6376            setUpCustomResolverActivity(pkg);
6377        }
6378
6379        if (pkg.packageName.equals("android")) {
6380            synchronized (mPackages) {
6381                if (mAndroidApplication != null) {
6382                    Slog.w(TAG, "*************************************************");
6383                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6384                    Slog.w(TAG, " file=" + scanFile);
6385                    Slog.w(TAG, "*************************************************");
6386                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6387                            "Core android package being redefined.  Skipping.");
6388                }
6389
6390                // Set up information for our fall-back user intent resolution activity.
6391                mPlatformPackage = pkg;
6392                pkg.mVersionCode = mSdkVersion;
6393                mAndroidApplication = pkg.applicationInfo;
6394
6395                if (!mResolverReplaced) {
6396                    mResolveActivity.applicationInfo = mAndroidApplication;
6397                    mResolveActivity.name = ResolverActivity.class.getName();
6398                    mResolveActivity.packageName = mAndroidApplication.packageName;
6399                    mResolveActivity.processName = "system:ui";
6400                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6401                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6402                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6403                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6404                    mResolveActivity.exported = true;
6405                    mResolveActivity.enabled = true;
6406                    mResolveInfo.activityInfo = mResolveActivity;
6407                    mResolveInfo.priority = 0;
6408                    mResolveInfo.preferredOrder = 0;
6409                    mResolveInfo.match = 0;
6410                    mResolveComponentName = new ComponentName(
6411                            mAndroidApplication.packageName, mResolveActivity.name);
6412                }
6413            }
6414        }
6415
6416        if (DEBUG_PACKAGE_SCANNING) {
6417            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6418                Log.d(TAG, "Scanning package " + pkg.packageName);
6419        }
6420
6421        if (mPackages.containsKey(pkg.packageName)
6422                || mSharedLibraries.containsKey(pkg.packageName)) {
6423            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6424                    "Application package " + pkg.packageName
6425                    + " already installed.  Skipping duplicate.");
6426        }
6427
6428        // If we're only installing presumed-existing packages, require that the
6429        // scanned APK is both already known and at the path previously established
6430        // for it.  Previously unknown packages we pick up normally, but if we have an
6431        // a priori expectation about this package's install presence, enforce it.
6432        // With a singular exception for new system packages. When an OTA contains
6433        // a new system package, we allow the codepath to change from a system location
6434        // to the user-installed location. If we don't allow this change, any newer,
6435        // user-installed version of the application will be ignored.
6436        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6437            if (mExpectingBetter.containsKey(pkg.packageName)) {
6438                logCriticalInfo(Log.WARN,
6439                        "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
6440            } else {
6441                PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6442                if (known != null) {
6443                    if (DEBUG_PACKAGE_SCANNING) {
6444                        Log.d(TAG, "Examining " + pkg.codePath
6445                                + " and requiring known paths " + known.codePathString
6446                                + " & " + known.resourcePathString);
6447                    }
6448                    if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6449                            || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6450                        throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6451                                "Application package " + pkg.packageName
6452                                + " found at " + pkg.applicationInfo.getCodePath()
6453                                + " but expected at " + known.codePathString + "; ignoring.");
6454                    }
6455                }
6456            }
6457        }
6458
6459        // Initialize package source and resource directories
6460        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6461        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6462
6463        SharedUserSetting suid = null;
6464        PackageSetting pkgSetting = null;
6465
6466        if (!isSystemApp(pkg)) {
6467            // Only system apps can use these features.
6468            pkg.mOriginalPackages = null;
6469            pkg.mRealPackage = null;
6470            pkg.mAdoptPermissions = null;
6471        }
6472
6473        // writer
6474        synchronized (mPackages) {
6475            if (pkg.mSharedUserId != null) {
6476                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6477                if (suid == null) {
6478                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6479                            "Creating application package " + pkg.packageName
6480                            + " for shared user failed");
6481                }
6482                if (DEBUG_PACKAGE_SCANNING) {
6483                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6484                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6485                                + "): packages=" + suid.packages);
6486                }
6487            }
6488
6489            // Check if we are renaming from an original package name.
6490            PackageSetting origPackage = null;
6491            String realName = null;
6492            if (pkg.mOriginalPackages != null) {
6493                // This package may need to be renamed to a previously
6494                // installed name.  Let's check on that...
6495                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
6496                if (pkg.mOriginalPackages.contains(renamed)) {
6497                    // This package had originally been installed as the
6498                    // original name, and we have already taken care of
6499                    // transitioning to the new one.  Just update the new
6500                    // one to continue using the old name.
6501                    realName = pkg.mRealPackage;
6502                    if (!pkg.packageName.equals(renamed)) {
6503                        // Callers into this function may have already taken
6504                        // care of renaming the package; only do it here if
6505                        // it is not already done.
6506                        pkg.setPackageName(renamed);
6507                    }
6508
6509                } else {
6510                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
6511                        if ((origPackage = mSettings.peekPackageLPr(
6512                                pkg.mOriginalPackages.get(i))) != null) {
6513                            // We do have the package already installed under its
6514                            // original name...  should we use it?
6515                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
6516                                // New package is not compatible with original.
6517                                origPackage = null;
6518                                continue;
6519                            } else if (origPackage.sharedUser != null) {
6520                                // Make sure uid is compatible between packages.
6521                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6522                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6523                                            + " to " + pkg.packageName + ": old uid "
6524                                            + origPackage.sharedUser.name
6525                                            + " differs from " + pkg.mSharedUserId);
6526                                    origPackage = null;
6527                                    continue;
6528                                }
6529                            } else {
6530                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6531                                        + pkg.packageName + " to old name " + origPackage.name);
6532                            }
6533                            break;
6534                        }
6535                    }
6536                }
6537            }
6538
6539            if (mTransferedPackages.contains(pkg.packageName)) {
6540                Slog.w(TAG, "Package " + pkg.packageName
6541                        + " was transferred to another, but its .apk remains");
6542            }
6543
6544            // Just create the setting, don't add it yet. For already existing packages
6545            // the PkgSetting exists already and doesn't have to be created.
6546            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6547                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6548                    pkg.applicationInfo.primaryCpuAbi,
6549                    pkg.applicationInfo.secondaryCpuAbi,
6550                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6551                    user, false);
6552            if (pkgSetting == null) {
6553                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6554                        "Creating application package " + pkg.packageName + " failed");
6555            }
6556
6557            if (pkgSetting.origPackage != null) {
6558                // If we are first transitioning from an original package,
6559                // fix up the new package's name now.  We need to do this after
6560                // looking up the package under its new name, so getPackageLP
6561                // can take care of fiddling things correctly.
6562                pkg.setPackageName(origPackage.name);
6563
6564                // File a report about this.
6565                String msg = "New package " + pkgSetting.realName
6566                        + " renamed to replace old package " + pkgSetting.name;
6567                reportSettingsProblem(Log.WARN, msg);
6568
6569                // Make a note of it.
6570                mTransferedPackages.add(origPackage.name);
6571
6572                // No longer need to retain this.
6573                pkgSetting.origPackage = null;
6574            }
6575
6576            if (realName != null) {
6577                // Make a note of it.
6578                mTransferedPackages.add(pkg.packageName);
6579            }
6580
6581            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6582                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6583            }
6584
6585            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6586                // Check all shared libraries and map to their actual file path.
6587                // We only do this here for apps not on a system dir, because those
6588                // are the only ones that can fail an install due to this.  We
6589                // will take care of the system apps by updating all of their
6590                // library paths after the scan is done.
6591                updateSharedLibrariesLPw(pkg, null);
6592            }
6593
6594            if (mFoundPolicyFile) {
6595                SELinuxMMAC.assignSeinfoValue(pkg);
6596            }
6597
6598            pkg.applicationInfo.uid = pkgSetting.appId;
6599            pkg.mExtras = pkgSetting;
6600            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
6601                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
6602                    // We just determined the app is signed correctly, so bring
6603                    // over the latest parsed certs.
6604                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6605                } else {
6606                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6607                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6608                                "Package " + pkg.packageName + " upgrade keys do not match the "
6609                                + "previously installed version");
6610                    } else {
6611                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
6612                        String msg = "System package " + pkg.packageName
6613                            + " signature changed; retaining data.";
6614                        reportSettingsProblem(Log.WARN, msg);
6615                    }
6616                }
6617            } else {
6618                try {
6619                    verifySignaturesLP(pkgSetting, pkg);
6620                    // We just determined the app is signed correctly, so bring
6621                    // over the latest parsed certs.
6622                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6623                } catch (PackageManagerException e) {
6624                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6625                        throw e;
6626                    }
6627                    // The signature has changed, but this package is in the system
6628                    // image...  let's recover!
6629                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6630                    // However...  if this package is part of a shared user, but it
6631                    // doesn't match the signature of the shared user, let's fail.
6632                    // What this means is that you can't change the signatures
6633                    // associated with an overall shared user, which doesn't seem all
6634                    // that unreasonable.
6635                    if (pkgSetting.sharedUser != null) {
6636                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6637                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
6638                            throw new PackageManagerException(
6639                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
6640                                            "Signature mismatch for shared user : "
6641                                            + pkgSetting.sharedUser);
6642                        }
6643                    }
6644                    // File a report about this.
6645                    String msg = "System package " + pkg.packageName
6646                        + " signature changed; retaining data.";
6647                    reportSettingsProblem(Log.WARN, msg);
6648                }
6649            }
6650            // Verify that this new package doesn't have any content providers
6651            // that conflict with existing packages.  Only do this if the
6652            // package isn't already installed, since we don't want to break
6653            // things that are installed.
6654            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6655                final int N = pkg.providers.size();
6656                int i;
6657                for (i=0; i<N; i++) {
6658                    PackageParser.Provider p = pkg.providers.get(i);
6659                    if (p.info.authority != null) {
6660                        String names[] = p.info.authority.split(";");
6661                        for (int j = 0; j < names.length; j++) {
6662                            if (mProvidersByAuthority.containsKey(names[j])) {
6663                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6664                                final String otherPackageName =
6665                                        ((other != null && other.getComponentName() != null) ?
6666                                                other.getComponentName().getPackageName() : "?");
6667                                throw new PackageManagerException(
6668                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
6669                                                "Can't install because provider name " + names[j]
6670                                                + " (in package " + pkg.applicationInfo.packageName
6671                                                + ") is already used by " + otherPackageName);
6672                            }
6673                        }
6674                    }
6675                }
6676            }
6677
6678            if (pkg.mAdoptPermissions != null) {
6679                // This package wants to adopt ownership of permissions from
6680                // another package.
6681                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6682                    final String origName = pkg.mAdoptPermissions.get(i);
6683                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
6684                    if (orig != null) {
6685                        if (verifyPackageUpdateLPr(orig, pkg)) {
6686                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
6687                                    + pkg.packageName);
6688                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
6689                        }
6690                    }
6691                }
6692            }
6693        }
6694
6695        final String pkgName = pkg.packageName;
6696
6697        final long scanFileTime = scanFile.lastModified();
6698        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6699        pkg.applicationInfo.processName = fixProcessName(
6700                pkg.applicationInfo.packageName,
6701                pkg.applicationInfo.processName,
6702                pkg.applicationInfo.uid);
6703
6704        File dataPath;
6705        if (mPlatformPackage == pkg) {
6706            // The system package is special.
6707            dataPath = new File(Environment.getDataDirectory(), "system");
6708
6709            pkg.applicationInfo.dataDir = dataPath.getPath();
6710
6711        } else {
6712            // This is a normal package, need to make its data directory.
6713            dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid,
6714                    UserHandle.USER_OWNER, pkg.packageName);
6715
6716            boolean uidError = false;
6717            if (dataPath.exists()) {
6718                int currentUid = 0;
6719                try {
6720                    StructStat stat = Os.stat(dataPath.getPath());
6721                    currentUid = stat.st_uid;
6722                } catch (ErrnoException e) {
6723                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6724                }
6725
6726                // If we have mismatched owners for the data path, we have a problem.
6727                if (currentUid != pkg.applicationInfo.uid) {
6728                    boolean recovered = false;
6729                    if (currentUid == 0) {
6730                        // The directory somehow became owned by root.  Wow.
6731                        // This is probably because the system was stopped while
6732                        // installd was in the middle of messing with its libs
6733                        // directory.  Ask installd to fix that.
6734                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
6735                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
6736                        if (ret >= 0) {
6737                            recovered = true;
6738                            String msg = "Package " + pkg.packageName
6739                                    + " unexpectedly changed to uid 0; recovered to " +
6740                                    + pkg.applicationInfo.uid;
6741                            reportSettingsProblem(Log.WARN, msg);
6742                        }
6743                    }
6744                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6745                            || (scanFlags&SCAN_BOOTING) != 0)) {
6746                        // If this is a system app, we can at least delete its
6747                        // current data so the application will still work.
6748                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
6749                        if (ret >= 0) {
6750                            // TODO: Kill the processes first
6751                            // Old data gone!
6752                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6753                                    ? "System package " : "Third party package ";
6754                            String msg = prefix + pkg.packageName
6755                                    + " has changed from uid: "
6756                                    + currentUid + " to "
6757                                    + pkg.applicationInfo.uid + "; old data erased";
6758                            reportSettingsProblem(Log.WARN, msg);
6759                            recovered = true;
6760
6761                            // And now re-install the app.
6762                            ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6763                                    pkg.applicationInfo.seinfo);
6764                            if (ret == -1) {
6765                                // Ack should not happen!
6766                                msg = prefix + pkg.packageName
6767                                        + " could not have data directory re-created after delete.";
6768                                reportSettingsProblem(Log.WARN, msg);
6769                                throw new PackageManagerException(
6770                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6771                            }
6772                        }
6773                        if (!recovered) {
6774                            mHasSystemUidErrors = true;
6775                        }
6776                    } else if (!recovered) {
6777                        // If we allow this install to proceed, we will be broken.
6778                        // Abort, abort!
6779                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
6780                                "scanPackageLI");
6781                    }
6782                    if (!recovered) {
6783                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
6784                            + pkg.applicationInfo.uid + "/fs_"
6785                            + currentUid;
6786                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
6787                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
6788                        String msg = "Package " + pkg.packageName
6789                                + " has mismatched uid: "
6790                                + currentUid + " on disk, "
6791                                + pkg.applicationInfo.uid + " in settings";
6792                        // writer
6793                        synchronized (mPackages) {
6794                            mSettings.mReadMessages.append(msg);
6795                            mSettings.mReadMessages.append('\n');
6796                            uidError = true;
6797                            if (!pkgSetting.uidError) {
6798                                reportSettingsProblem(Log.ERROR, msg);
6799                            }
6800                        }
6801                    }
6802                }
6803                pkg.applicationInfo.dataDir = dataPath.getPath();
6804                if (mShouldRestoreconData) {
6805                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
6806                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
6807                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
6808                }
6809            } else {
6810                if (DEBUG_PACKAGE_SCANNING) {
6811                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6812                        Log.v(TAG, "Want this data dir: " + dataPath);
6813                }
6814                //invoke installer to do the actual installation
6815                int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6816                        pkg.applicationInfo.seinfo);
6817                if (ret < 0) {
6818                    // Error from installer
6819                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6820                            "Unable to create data dirs [errorCode=" + ret + "]");
6821                }
6822
6823                if (dataPath.exists()) {
6824                    pkg.applicationInfo.dataDir = dataPath.getPath();
6825                } else {
6826                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
6827                    pkg.applicationInfo.dataDir = null;
6828                }
6829            }
6830
6831            pkgSetting.uidError = uidError;
6832        }
6833
6834        final String path = scanFile.getPath();
6835        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
6836
6837        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
6838            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
6839
6840            // Some system apps still use directory structure for native libraries
6841            // in which case we might end up not detecting abi solely based on apk
6842            // structure. Try to detect abi based on directory structure.
6843            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
6844                    pkg.applicationInfo.primaryCpuAbi == null) {
6845                setBundledAppAbisAndRoots(pkg, pkgSetting);
6846                setNativeLibraryPaths(pkg);
6847            }
6848
6849        } else {
6850            if ((scanFlags & SCAN_MOVE) != 0) {
6851                // We haven't run dex-opt for this move (since we've moved the compiled output too)
6852                // but we already have this packages package info in the PackageSetting. We just
6853                // use that and derive the native library path based on the new codepath.
6854                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
6855                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
6856            }
6857
6858            // Set native library paths again. For moves, the path will be updated based on the
6859            // ABIs we've determined above. For non-moves, the path will be updated based on the
6860            // ABIs we determined during compilation, but the path will depend on the final
6861            // package path (after the rename away from the stage path).
6862            setNativeLibraryPaths(pkg);
6863        }
6864
6865        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
6866        final int[] userIds = sUserManager.getUserIds();
6867        synchronized (mInstallLock) {
6868            // Make sure all user data directories are ready to roll; we're okay
6869            // if they already exist
6870            if (!TextUtils.isEmpty(pkg.volumeUuid)) {
6871                for (int userId : userIds) {
6872                    if (userId != 0) {
6873                        mInstaller.createUserData(pkg.volumeUuid, pkg.packageName,
6874                                UserHandle.getUid(userId, pkg.applicationInfo.uid), userId,
6875                                pkg.applicationInfo.seinfo);
6876                    }
6877                }
6878            }
6879
6880            // Create a native library symlink only if we have native libraries
6881            // and if the native libraries are 32 bit libraries. We do not provide
6882            // this symlink for 64 bit libraries.
6883            if (pkg.applicationInfo.primaryCpuAbi != null &&
6884                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
6885                final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
6886                for (int userId : userIds) {
6887                    if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
6888                            nativeLibPath, userId) < 0) {
6889                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
6890                                "Failed linking native library dir (user=" + userId + ")");
6891                    }
6892                }
6893            }
6894        }
6895
6896        // This is a special case for the "system" package, where the ABI is
6897        // dictated by the zygote configuration (and init.rc). We should keep track
6898        // of this ABI so that we can deal with "normal" applications that run under
6899        // the same UID correctly.
6900        if (mPlatformPackage == pkg) {
6901            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
6902                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
6903        }
6904
6905        // If there's a mismatch between the abi-override in the package setting
6906        // and the abiOverride specified for the install. Warn about this because we
6907        // would've already compiled the app without taking the package setting into
6908        // account.
6909        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
6910            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
6911                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
6912                        " for package: " + pkg.packageName);
6913            }
6914        }
6915
6916        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6917        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6918        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
6919
6920        // Copy the derived override back to the parsed package, so that we can
6921        // update the package settings accordingly.
6922        pkg.cpuAbiOverride = cpuAbiOverride;
6923
6924        if (DEBUG_ABI_SELECTION) {
6925            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
6926                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
6927                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
6928        }
6929
6930        // Push the derived path down into PackageSettings so we know what to
6931        // clean up at uninstall time.
6932        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
6933
6934        if (DEBUG_ABI_SELECTION) {
6935            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
6936                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
6937                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
6938        }
6939
6940        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
6941            // We don't do this here during boot because we can do it all
6942            // at once after scanning all existing packages.
6943            //
6944            // We also do this *before* we perform dexopt on this package, so that
6945            // we can avoid redundant dexopts, and also to make sure we've got the
6946            // code and package path correct.
6947            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
6948                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
6949        }
6950
6951        if ((scanFlags & SCAN_NO_DEX) == 0) {
6952            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
6953                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */);
6954            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6955                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
6956            }
6957        }
6958        if (mFactoryTest && pkg.requestedPermissions.contains(
6959                android.Manifest.permission.FACTORY_TEST)) {
6960            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
6961        }
6962
6963        ArrayList<PackageParser.Package> clientLibPkgs = null;
6964
6965        // writer
6966        synchronized (mPackages) {
6967            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6968                // Only system apps can add new shared libraries.
6969                if (pkg.libraryNames != null) {
6970                    for (int i=0; i<pkg.libraryNames.size(); i++) {
6971                        String name = pkg.libraryNames.get(i);
6972                        boolean allowed = false;
6973                        if (pkg.isUpdatedSystemApp()) {
6974                            // New library entries can only be added through the
6975                            // system image.  This is important to get rid of a lot
6976                            // of nasty edge cases: for example if we allowed a non-
6977                            // system update of the app to add a library, then uninstalling
6978                            // the update would make the library go away, and assumptions
6979                            // we made such as through app install filtering would now
6980                            // have allowed apps on the device which aren't compatible
6981                            // with it.  Better to just have the restriction here, be
6982                            // conservative, and create many fewer cases that can negatively
6983                            // impact the user experience.
6984                            final PackageSetting sysPs = mSettings
6985                                    .getDisabledSystemPkgLPr(pkg.packageName);
6986                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
6987                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
6988                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
6989                                        allowed = true;
6990                                        allowed = true;
6991                                        break;
6992                                    }
6993                                }
6994                            }
6995                        } else {
6996                            allowed = true;
6997                        }
6998                        if (allowed) {
6999                            if (!mSharedLibraries.containsKey(name)) {
7000                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7001                            } else if (!name.equals(pkg.packageName)) {
7002                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7003                                        + name + " already exists; skipping");
7004                            }
7005                        } else {
7006                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7007                                    + name + " that is not declared on system image; skipping");
7008                        }
7009                    }
7010                    if ((scanFlags&SCAN_BOOTING) == 0) {
7011                        // If we are not booting, we need to update any applications
7012                        // that are clients of our shared library.  If we are booting,
7013                        // this will all be done once the scan is complete.
7014                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7015                    }
7016                }
7017            }
7018        }
7019
7020        // We also need to dexopt any apps that are dependent on this library.  Note that
7021        // if these fail, we should abort the install since installing the library will
7022        // result in some apps being broken.
7023        if (clientLibPkgs != null) {
7024            if ((scanFlags & SCAN_NO_DEX) == 0) {
7025                for (int i = 0; i < clientLibPkgs.size(); i++) {
7026                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
7027                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
7028                            null /* instruction sets */, forceDex,
7029                            (scanFlags & SCAN_DEFER_DEX) != 0, false);
7030                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7031                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
7032                                "scanPackageLI failed to dexopt clientLibPkgs");
7033                    }
7034                }
7035            }
7036        }
7037
7038        // Also need to kill any apps that are dependent on the library.
7039        if (clientLibPkgs != null) {
7040            for (int i=0; i<clientLibPkgs.size(); i++) {
7041                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7042                killApplication(clientPkg.applicationInfo.packageName,
7043                        clientPkg.applicationInfo.uid, "update lib");
7044            }
7045        }
7046
7047        // Make sure we're not adding any bogus keyset info
7048        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7049        ksms.assertScannedPackageValid(pkg);
7050
7051        // writer
7052        synchronized (mPackages) {
7053            // We don't expect installation to fail beyond this point
7054
7055            // Add the new setting to mSettings
7056            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7057            // Add the new setting to mPackages
7058            mPackages.put(pkg.applicationInfo.packageName, pkg);
7059            // Make sure we don't accidentally delete its data.
7060            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7061            while (iter.hasNext()) {
7062                PackageCleanItem item = iter.next();
7063                if (pkgName.equals(item.packageName)) {
7064                    iter.remove();
7065                }
7066            }
7067
7068            // Take care of first install / last update times.
7069            if (currentTime != 0) {
7070                if (pkgSetting.firstInstallTime == 0) {
7071                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7072                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7073                    pkgSetting.lastUpdateTime = currentTime;
7074                }
7075            } else if (pkgSetting.firstInstallTime == 0) {
7076                // We need *something*.  Take time time stamp of the file.
7077                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7078            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7079                if (scanFileTime != pkgSetting.timeStamp) {
7080                    // A package on the system image has changed; consider this
7081                    // to be an update.
7082                    pkgSetting.lastUpdateTime = scanFileTime;
7083                }
7084            }
7085
7086            // Add the package's KeySets to the global KeySetManagerService
7087            ksms.addScannedPackageLPw(pkg);
7088
7089            int N = pkg.providers.size();
7090            StringBuilder r = null;
7091            int i;
7092            for (i=0; i<N; i++) {
7093                PackageParser.Provider p = pkg.providers.get(i);
7094                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7095                        p.info.processName, pkg.applicationInfo.uid);
7096                mProviders.addProvider(p);
7097                p.syncable = p.info.isSyncable;
7098                if (p.info.authority != null) {
7099                    String names[] = p.info.authority.split(";");
7100                    p.info.authority = null;
7101                    for (int j = 0; j < names.length; j++) {
7102                        if (j == 1 && p.syncable) {
7103                            // We only want the first authority for a provider to possibly be
7104                            // syncable, so if we already added this provider using a different
7105                            // authority clear the syncable flag. We copy the provider before
7106                            // changing it because the mProviders object contains a reference
7107                            // to a provider that we don't want to change.
7108                            // Only do this for the second authority since the resulting provider
7109                            // object can be the same for all future authorities for this provider.
7110                            p = new PackageParser.Provider(p);
7111                            p.syncable = false;
7112                        }
7113                        if (!mProvidersByAuthority.containsKey(names[j])) {
7114                            mProvidersByAuthority.put(names[j], p);
7115                            if (p.info.authority == null) {
7116                                p.info.authority = names[j];
7117                            } else {
7118                                p.info.authority = p.info.authority + ";" + names[j];
7119                            }
7120                            if (DEBUG_PACKAGE_SCANNING) {
7121                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7122                                    Log.d(TAG, "Registered content provider: " + names[j]
7123                                            + ", className = " + p.info.name + ", isSyncable = "
7124                                            + p.info.isSyncable);
7125                            }
7126                        } else {
7127                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7128                            Slog.w(TAG, "Skipping provider name " + names[j] +
7129                                    " (in package " + pkg.applicationInfo.packageName +
7130                                    "): name already used by "
7131                                    + ((other != null && other.getComponentName() != null)
7132                                            ? other.getComponentName().getPackageName() : "?"));
7133                        }
7134                    }
7135                }
7136                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7137                    if (r == null) {
7138                        r = new StringBuilder(256);
7139                    } else {
7140                        r.append(' ');
7141                    }
7142                    r.append(p.info.name);
7143                }
7144            }
7145            if (r != null) {
7146                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7147            }
7148
7149            N = pkg.services.size();
7150            r = null;
7151            for (i=0; i<N; i++) {
7152                PackageParser.Service s = pkg.services.get(i);
7153                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7154                        s.info.processName, pkg.applicationInfo.uid);
7155                mServices.addService(s);
7156                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7157                    if (r == null) {
7158                        r = new StringBuilder(256);
7159                    } else {
7160                        r.append(' ');
7161                    }
7162                    r.append(s.info.name);
7163                }
7164            }
7165            if (r != null) {
7166                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7167            }
7168
7169            N = pkg.receivers.size();
7170            r = null;
7171            for (i=0; i<N; i++) {
7172                PackageParser.Activity a = pkg.receivers.get(i);
7173                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7174                        a.info.processName, pkg.applicationInfo.uid);
7175                mReceivers.addActivity(a, "receiver");
7176                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7177                    if (r == null) {
7178                        r = new StringBuilder(256);
7179                    } else {
7180                        r.append(' ');
7181                    }
7182                    r.append(a.info.name);
7183                }
7184            }
7185            if (r != null) {
7186                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7187            }
7188
7189            N = pkg.activities.size();
7190            r = null;
7191            for (i=0; i<N; i++) {
7192                PackageParser.Activity a = pkg.activities.get(i);
7193                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7194                        a.info.processName, pkg.applicationInfo.uid);
7195                mActivities.addActivity(a, "activity");
7196                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7197                    if (r == null) {
7198                        r = new StringBuilder(256);
7199                    } else {
7200                        r.append(' ');
7201                    }
7202                    r.append(a.info.name);
7203                }
7204            }
7205            if (r != null) {
7206                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7207            }
7208
7209            N = pkg.permissionGroups.size();
7210            r = null;
7211            for (i=0; i<N; i++) {
7212                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7213                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7214                if (cur == null) {
7215                    mPermissionGroups.put(pg.info.name, pg);
7216                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7217                        if (r == null) {
7218                            r = new StringBuilder(256);
7219                        } else {
7220                            r.append(' ');
7221                        }
7222                        r.append(pg.info.name);
7223                    }
7224                } else {
7225                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7226                            + pg.info.packageName + " ignored: original from "
7227                            + cur.info.packageName);
7228                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7229                        if (r == null) {
7230                            r = new StringBuilder(256);
7231                        } else {
7232                            r.append(' ');
7233                        }
7234                        r.append("DUP:");
7235                        r.append(pg.info.name);
7236                    }
7237                }
7238            }
7239            if (r != null) {
7240                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7241            }
7242
7243            N = pkg.permissions.size();
7244            r = null;
7245            for (i=0; i<N; i++) {
7246                PackageParser.Permission p = pkg.permissions.get(i);
7247
7248                // Now that permission groups have a special meaning, we ignore permission
7249                // groups for legacy apps to prevent unexpected behavior. In particular,
7250                // permissions for one app being granted to someone just becuase they happen
7251                // to be in a group defined by another app (before this had no implications).
7252                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7253                    p.group = mPermissionGroups.get(p.info.group);
7254                    // Warn for a permission in an unknown group.
7255                    if (p.info.group != null && p.group == null) {
7256                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7257                                + p.info.packageName + " in an unknown group " + p.info.group);
7258                    }
7259                }
7260
7261                ArrayMap<String, BasePermission> permissionMap =
7262                        p.tree ? mSettings.mPermissionTrees
7263                                : mSettings.mPermissions;
7264                BasePermission bp = permissionMap.get(p.info.name);
7265
7266                // Allow system apps to redefine non-system permissions
7267                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7268                    final boolean currentOwnerIsSystem = (bp.perm != null
7269                            && isSystemApp(bp.perm.owner));
7270                    if (isSystemApp(p.owner)) {
7271                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7272                            // It's a built-in permission and no owner, take ownership now
7273                            bp.packageSetting = pkgSetting;
7274                            bp.perm = p;
7275                            bp.uid = pkg.applicationInfo.uid;
7276                            bp.sourcePackage = p.info.packageName;
7277                        } else if (!currentOwnerIsSystem) {
7278                            String msg = "New decl " + p.owner + " of permission  "
7279                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7280                            reportSettingsProblem(Log.WARN, msg);
7281                            bp = null;
7282                        }
7283                    }
7284                }
7285
7286                if (bp == null) {
7287                    bp = new BasePermission(p.info.name, p.info.packageName,
7288                            BasePermission.TYPE_NORMAL);
7289                    permissionMap.put(p.info.name, bp);
7290                }
7291
7292                if (bp.perm == null) {
7293                    if (bp.sourcePackage == null
7294                            || bp.sourcePackage.equals(p.info.packageName)) {
7295                        BasePermission tree = findPermissionTreeLP(p.info.name);
7296                        if (tree == null
7297                                || tree.sourcePackage.equals(p.info.packageName)) {
7298                            bp.packageSetting = pkgSetting;
7299                            bp.perm = p;
7300                            bp.uid = pkg.applicationInfo.uid;
7301                            bp.sourcePackage = p.info.packageName;
7302                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7303                                if (r == null) {
7304                                    r = new StringBuilder(256);
7305                                } else {
7306                                    r.append(' ');
7307                                }
7308                                r.append(p.info.name);
7309                            }
7310                        } else {
7311                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7312                                    + p.info.packageName + " ignored: base tree "
7313                                    + tree.name + " is from package "
7314                                    + tree.sourcePackage);
7315                        }
7316                    } else {
7317                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7318                                + p.info.packageName + " ignored: original from "
7319                                + bp.sourcePackage);
7320                    }
7321                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7322                    if (r == null) {
7323                        r = new StringBuilder(256);
7324                    } else {
7325                        r.append(' ');
7326                    }
7327                    r.append("DUP:");
7328                    r.append(p.info.name);
7329                }
7330                if (bp.perm == p) {
7331                    bp.protectionLevel = p.info.protectionLevel;
7332                }
7333            }
7334
7335            if (r != null) {
7336                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7337            }
7338
7339            N = pkg.instrumentation.size();
7340            r = null;
7341            for (i=0; i<N; i++) {
7342                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7343                a.info.packageName = pkg.applicationInfo.packageName;
7344                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7345                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7346                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7347                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7348                a.info.dataDir = pkg.applicationInfo.dataDir;
7349
7350                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7351                // need other information about the application, like the ABI and what not ?
7352                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7353                mInstrumentation.put(a.getComponentName(), a);
7354                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7355                    if (r == null) {
7356                        r = new StringBuilder(256);
7357                    } else {
7358                        r.append(' ');
7359                    }
7360                    r.append(a.info.name);
7361                }
7362            }
7363            if (r != null) {
7364                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7365            }
7366
7367            if (pkg.protectedBroadcasts != null) {
7368                N = pkg.protectedBroadcasts.size();
7369                for (i=0; i<N; i++) {
7370                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7371                }
7372            }
7373
7374            pkgSetting.setTimeStamp(scanFileTime);
7375
7376            // Create idmap files for pairs of (packages, overlay packages).
7377            // Note: "android", ie framework-res.apk, is handled by native layers.
7378            if (pkg.mOverlayTarget != null) {
7379                // This is an overlay package.
7380                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7381                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7382                        mOverlays.put(pkg.mOverlayTarget,
7383                                new ArrayMap<String, PackageParser.Package>());
7384                    }
7385                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7386                    map.put(pkg.packageName, pkg);
7387                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7388                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7389                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7390                                "scanPackageLI failed to createIdmap");
7391                    }
7392                }
7393            } else if (mOverlays.containsKey(pkg.packageName) &&
7394                    !pkg.packageName.equals("android")) {
7395                // This is a regular package, with one or more known overlay packages.
7396                createIdmapsForPackageLI(pkg);
7397            }
7398        }
7399
7400        return pkg;
7401    }
7402
7403    /**
7404     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7405     * is derived purely on the basis of the contents of {@code scanFile} and
7406     * {@code cpuAbiOverride}.
7407     *
7408     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7409     */
7410    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7411                                 String cpuAbiOverride, boolean extractLibs)
7412            throws PackageManagerException {
7413        // TODO: We can probably be smarter about this stuff. For installed apps,
7414        // we can calculate this information at install time once and for all. For
7415        // system apps, we can probably assume that this information doesn't change
7416        // after the first boot scan. As things stand, we do lots of unnecessary work.
7417
7418        // Give ourselves some initial paths; we'll come back for another
7419        // pass once we've determined ABI below.
7420        setNativeLibraryPaths(pkg);
7421
7422        // We would never need to extract libs for forward-locked and external packages,
7423        // since the container service will do it for us. We shouldn't attempt to
7424        // extract libs from system app when it was not updated.
7425        if (pkg.isForwardLocked() || isExternal(pkg) ||
7426            (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) {
7427            extractLibs = false;
7428        }
7429
7430        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7431        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7432
7433        NativeLibraryHelper.Handle handle = null;
7434        try {
7435            handle = NativeLibraryHelper.Handle.create(scanFile);
7436            // TODO(multiArch): This can be null for apps that didn't go through the
7437            // usual installation process. We can calculate it again, like we
7438            // do during install time.
7439            //
7440            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7441            // unnecessary.
7442            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7443
7444            // Null out the abis so that they can be recalculated.
7445            pkg.applicationInfo.primaryCpuAbi = null;
7446            pkg.applicationInfo.secondaryCpuAbi = null;
7447            if (isMultiArch(pkg.applicationInfo)) {
7448                // Warn if we've set an abiOverride for multi-lib packages..
7449                // By definition, we need to copy both 32 and 64 bit libraries for
7450                // such packages.
7451                if (pkg.cpuAbiOverride != null
7452                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7453                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7454                }
7455
7456                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7457                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7458                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7459                    if (extractLibs) {
7460                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7461                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7462                                useIsaSpecificSubdirs);
7463                    } else {
7464                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7465                    }
7466                }
7467
7468                maybeThrowExceptionForMultiArchCopy(
7469                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7470
7471                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7472                    if (extractLibs) {
7473                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7474                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7475                                useIsaSpecificSubdirs);
7476                    } else {
7477                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7478                    }
7479                }
7480
7481                maybeThrowExceptionForMultiArchCopy(
7482                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7483
7484                if (abi64 >= 0) {
7485                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7486                }
7487
7488                if (abi32 >= 0) {
7489                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7490                    if (abi64 >= 0) {
7491                        pkg.applicationInfo.secondaryCpuAbi = abi;
7492                    } else {
7493                        pkg.applicationInfo.primaryCpuAbi = abi;
7494                    }
7495                }
7496            } else {
7497                String[] abiList = (cpuAbiOverride != null) ?
7498                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7499
7500                // Enable gross and lame hacks for apps that are built with old
7501                // SDK tools. We must scan their APKs for renderscript bitcode and
7502                // not launch them if it's present. Don't bother checking on devices
7503                // that don't have 64 bit support.
7504                boolean needsRenderScriptOverride = false;
7505                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7506                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7507                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7508                    needsRenderScriptOverride = true;
7509                }
7510
7511                final int copyRet;
7512                if (extractLibs) {
7513                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7514                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7515                } else {
7516                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7517                }
7518
7519                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7520                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7521                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7522                }
7523
7524                if (copyRet >= 0) {
7525                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7526                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7527                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7528                } else if (needsRenderScriptOverride) {
7529                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7530                }
7531            }
7532        } catch (IOException ioe) {
7533            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7534        } finally {
7535            IoUtils.closeQuietly(handle);
7536        }
7537
7538        // Now that we've calculated the ABIs and determined if it's an internal app,
7539        // we will go ahead and populate the nativeLibraryPath.
7540        setNativeLibraryPaths(pkg);
7541    }
7542
7543    /**
7544     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7545     * i.e, so that all packages can be run inside a single process if required.
7546     *
7547     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7548     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7549     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7550     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7551     * updating a package that belongs to a shared user.
7552     *
7553     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7554     * adds unnecessary complexity.
7555     */
7556    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7557            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
7558        String requiredInstructionSet = null;
7559        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7560            requiredInstructionSet = VMRuntime.getInstructionSet(
7561                     scannedPackage.applicationInfo.primaryCpuAbi);
7562        }
7563
7564        PackageSetting requirer = null;
7565        for (PackageSetting ps : packagesForUser) {
7566            // If packagesForUser contains scannedPackage, we skip it. This will happen
7567            // when scannedPackage is an update of an existing package. Without this check,
7568            // we will never be able to change the ABI of any package belonging to a shared
7569            // user, even if it's compatible with other packages.
7570            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7571                if (ps.primaryCpuAbiString == null) {
7572                    continue;
7573                }
7574
7575                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7576                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7577                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7578                    // this but there's not much we can do.
7579                    String errorMessage = "Instruction set mismatch, "
7580                            + ((requirer == null) ? "[caller]" : requirer)
7581                            + " requires " + requiredInstructionSet + " whereas " + ps
7582                            + " requires " + instructionSet;
7583                    Slog.w(TAG, errorMessage);
7584                }
7585
7586                if (requiredInstructionSet == null) {
7587                    requiredInstructionSet = instructionSet;
7588                    requirer = ps;
7589                }
7590            }
7591        }
7592
7593        if (requiredInstructionSet != null) {
7594            String adjustedAbi;
7595            if (requirer != null) {
7596                // requirer != null implies that either scannedPackage was null or that scannedPackage
7597                // did not require an ABI, in which case we have to adjust scannedPackage to match
7598                // the ABI of the set (which is the same as requirer's ABI)
7599                adjustedAbi = requirer.primaryCpuAbiString;
7600                if (scannedPackage != null) {
7601                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7602                }
7603            } else {
7604                // requirer == null implies that we're updating all ABIs in the set to
7605                // match scannedPackage.
7606                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7607            }
7608
7609            for (PackageSetting ps : packagesForUser) {
7610                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7611                    if (ps.primaryCpuAbiString != null) {
7612                        continue;
7613                    }
7614
7615                    ps.primaryCpuAbiString = adjustedAbi;
7616                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7617                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7618                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7619
7620                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
7621                                null /* instruction sets */, forceDexOpt, deferDexOpt, true);
7622                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7623                            ps.primaryCpuAbiString = null;
7624                            ps.pkg.applicationInfo.primaryCpuAbi = null;
7625                            return;
7626                        } else {
7627                            mInstaller.rmdex(ps.codePathString,
7628                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
7629                        }
7630                    }
7631                }
7632            }
7633        }
7634    }
7635
7636    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7637        synchronized (mPackages) {
7638            mResolverReplaced = true;
7639            // Set up information for custom user intent resolution activity.
7640            mResolveActivity.applicationInfo = pkg.applicationInfo;
7641            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7642            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7643            mResolveActivity.processName = pkg.applicationInfo.packageName;
7644            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7645            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7646                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7647            mResolveActivity.theme = 0;
7648            mResolveActivity.exported = true;
7649            mResolveActivity.enabled = true;
7650            mResolveInfo.activityInfo = mResolveActivity;
7651            mResolveInfo.priority = 0;
7652            mResolveInfo.preferredOrder = 0;
7653            mResolveInfo.match = 0;
7654            mResolveComponentName = mCustomResolverComponentName;
7655            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7656                    mResolveComponentName);
7657        }
7658    }
7659
7660    private static String calculateBundledApkRoot(final String codePathString) {
7661        final File codePath = new File(codePathString);
7662        final File codeRoot;
7663        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7664            codeRoot = Environment.getRootDirectory();
7665        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7666            codeRoot = Environment.getOemDirectory();
7667        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7668            codeRoot = Environment.getVendorDirectory();
7669        } else {
7670            // Unrecognized code path; take its top real segment as the apk root:
7671            // e.g. /something/app/blah.apk => /something
7672            try {
7673                File f = codePath.getCanonicalFile();
7674                File parent = f.getParentFile();    // non-null because codePath is a file
7675                File tmp;
7676                while ((tmp = parent.getParentFile()) != null) {
7677                    f = parent;
7678                    parent = tmp;
7679                }
7680                codeRoot = f;
7681                Slog.w(TAG, "Unrecognized code path "
7682                        + codePath + " - using " + codeRoot);
7683            } catch (IOException e) {
7684                // Can't canonicalize the code path -- shenanigans?
7685                Slog.w(TAG, "Can't canonicalize code path " + codePath);
7686                return Environment.getRootDirectory().getPath();
7687            }
7688        }
7689        return codeRoot.getPath();
7690    }
7691
7692    /**
7693     * Derive and set the location of native libraries for the given package,
7694     * which varies depending on where and how the package was installed.
7695     */
7696    private void setNativeLibraryPaths(PackageParser.Package pkg) {
7697        final ApplicationInfo info = pkg.applicationInfo;
7698        final String codePath = pkg.codePath;
7699        final File codeFile = new File(codePath);
7700        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7701        final boolean asecApp = info.isForwardLocked() || isExternal(info);
7702
7703        info.nativeLibraryRootDir = null;
7704        info.nativeLibraryRootRequiresIsa = false;
7705        info.nativeLibraryDir = null;
7706        info.secondaryNativeLibraryDir = null;
7707
7708        if (isApkFile(codeFile)) {
7709            // Monolithic install
7710            if (bundledApp) {
7711                // If "/system/lib64/apkname" exists, assume that is the per-package
7712                // native library directory to use; otherwise use "/system/lib/apkname".
7713                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
7714                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
7715                        getPrimaryInstructionSet(info));
7716
7717                // This is a bundled system app so choose the path based on the ABI.
7718                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
7719                // is just the default path.
7720                final String apkName = deriveCodePathName(codePath);
7721                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
7722                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
7723                        apkName).getAbsolutePath();
7724
7725                if (info.secondaryCpuAbi != null) {
7726                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7727                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7728                            secondaryLibDir, apkName).getAbsolutePath();
7729                }
7730            } else if (asecApp) {
7731                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
7732                        .getAbsolutePath();
7733            } else {
7734                final String apkName = deriveCodePathName(codePath);
7735                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
7736                        .getAbsolutePath();
7737            }
7738
7739            info.nativeLibraryRootRequiresIsa = false;
7740            info.nativeLibraryDir = info.nativeLibraryRootDir;
7741        } else {
7742            // Cluster install
7743            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7744            info.nativeLibraryRootRequiresIsa = true;
7745
7746            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7747                    getPrimaryInstructionSet(info)).getAbsolutePath();
7748
7749            if (info.secondaryCpuAbi != null) {
7750                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7751                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7752            }
7753        }
7754    }
7755
7756    /**
7757     * Calculate the abis and roots for a bundled app. These can uniquely
7758     * be determined from the contents of the system partition, i.e whether
7759     * it contains 64 or 32 bit shared libraries etc. We do not validate any
7760     * of this information, and instead assume that the system was built
7761     * sensibly.
7762     */
7763    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
7764                                           PackageSetting pkgSetting) {
7765        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
7766
7767        // If "/system/lib64/apkname" exists, assume that is the per-package
7768        // native library directory to use; otherwise use "/system/lib/apkname".
7769        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
7770        setBundledAppAbi(pkg, apkRoot, apkName);
7771        // pkgSetting might be null during rescan following uninstall of updates
7772        // to a bundled app, so accommodate that possibility.  The settings in
7773        // that case will be established later from the parsed package.
7774        //
7775        // If the settings aren't null, sync them up with what we've just derived.
7776        // note that apkRoot isn't stored in the package settings.
7777        if (pkgSetting != null) {
7778            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7779            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7780        }
7781    }
7782
7783    /**
7784     * Deduces the ABI of a bundled app and sets the relevant fields on the
7785     * parsed pkg object.
7786     *
7787     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
7788     *        under which system libraries are installed.
7789     * @param apkName the name of the installed package.
7790     */
7791    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7792        final File codeFile = new File(pkg.codePath);
7793
7794        final boolean has64BitLibs;
7795        final boolean has32BitLibs;
7796        if (isApkFile(codeFile)) {
7797            // Monolithic install
7798            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7799            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7800        } else {
7801            // Cluster install
7802            final File rootDir = new File(codeFile, LIB_DIR_NAME);
7803            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7804                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7805                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7806                has64BitLibs = (new File(rootDir, isa)).exists();
7807            } else {
7808                has64BitLibs = false;
7809            }
7810            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7811                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7812                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7813                has32BitLibs = (new File(rootDir, isa)).exists();
7814            } else {
7815                has32BitLibs = false;
7816            }
7817        }
7818
7819        if (has64BitLibs && !has32BitLibs) {
7820            // The package has 64 bit libs, but not 32 bit libs. Its primary
7821            // ABI should be 64 bit. We can safely assume here that the bundled
7822            // native libraries correspond to the most preferred ABI in the list.
7823
7824            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7825            pkg.applicationInfo.secondaryCpuAbi = null;
7826        } else if (has32BitLibs && !has64BitLibs) {
7827            // The package has 32 bit libs but not 64 bit libs. Its primary
7828            // ABI should be 32 bit.
7829
7830            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7831            pkg.applicationInfo.secondaryCpuAbi = null;
7832        } else if (has32BitLibs && has64BitLibs) {
7833            // The application has both 64 and 32 bit bundled libraries. We check
7834            // here that the app declares multiArch support, and warn if it doesn't.
7835            //
7836            // We will be lenient here and record both ABIs. The primary will be the
7837            // ABI that's higher on the list, i.e, a device that's configured to prefer
7838            // 64 bit apps will see a 64 bit primary ABI,
7839
7840            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
7841                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
7842            }
7843
7844            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
7845                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7846                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7847            } else {
7848                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7849                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7850            }
7851        } else {
7852            pkg.applicationInfo.primaryCpuAbi = null;
7853            pkg.applicationInfo.secondaryCpuAbi = null;
7854        }
7855    }
7856
7857    private void killApplication(String pkgName, int appId, String reason) {
7858        // Request the ActivityManager to kill the process(only for existing packages)
7859        // so that we do not end up in a confused state while the user is still using the older
7860        // version of the application while the new one gets installed.
7861        IActivityManager am = ActivityManagerNative.getDefault();
7862        if (am != null) {
7863            try {
7864                am.killApplicationWithAppId(pkgName, appId, reason);
7865            } catch (RemoteException e) {
7866            }
7867        }
7868    }
7869
7870    void removePackageLI(PackageSetting ps, boolean chatty) {
7871        if (DEBUG_INSTALL) {
7872            if (chatty)
7873                Log.d(TAG, "Removing package " + ps.name);
7874        }
7875
7876        // writer
7877        synchronized (mPackages) {
7878            mPackages.remove(ps.name);
7879            final PackageParser.Package pkg = ps.pkg;
7880            if (pkg != null) {
7881                cleanPackageDataStructuresLILPw(pkg, chatty);
7882            }
7883        }
7884    }
7885
7886    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
7887        if (DEBUG_INSTALL) {
7888            if (chatty)
7889                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
7890        }
7891
7892        // writer
7893        synchronized (mPackages) {
7894            mPackages.remove(pkg.applicationInfo.packageName);
7895            cleanPackageDataStructuresLILPw(pkg, chatty);
7896        }
7897    }
7898
7899    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
7900        int N = pkg.providers.size();
7901        StringBuilder r = null;
7902        int i;
7903        for (i=0; i<N; i++) {
7904            PackageParser.Provider p = pkg.providers.get(i);
7905            mProviders.removeProvider(p);
7906            if (p.info.authority == null) {
7907
7908                /* There was another ContentProvider with this authority when
7909                 * this app was installed so this authority is null,
7910                 * Ignore it as we don't have to unregister the provider.
7911                 */
7912                continue;
7913            }
7914            String names[] = p.info.authority.split(";");
7915            for (int j = 0; j < names.length; j++) {
7916                if (mProvidersByAuthority.get(names[j]) == p) {
7917                    mProvidersByAuthority.remove(names[j]);
7918                    if (DEBUG_REMOVE) {
7919                        if (chatty)
7920                            Log.d(TAG, "Unregistered content provider: " + names[j]
7921                                    + ", className = " + p.info.name + ", isSyncable = "
7922                                    + p.info.isSyncable);
7923                    }
7924                }
7925            }
7926            if (DEBUG_REMOVE && chatty) {
7927                if (r == null) {
7928                    r = new StringBuilder(256);
7929                } else {
7930                    r.append(' ');
7931                }
7932                r.append(p.info.name);
7933            }
7934        }
7935        if (r != null) {
7936            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
7937        }
7938
7939        N = pkg.services.size();
7940        r = null;
7941        for (i=0; i<N; i++) {
7942            PackageParser.Service s = pkg.services.get(i);
7943            mServices.removeService(s);
7944            if (chatty) {
7945                if (r == null) {
7946                    r = new StringBuilder(256);
7947                } else {
7948                    r.append(' ');
7949                }
7950                r.append(s.info.name);
7951            }
7952        }
7953        if (r != null) {
7954            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
7955        }
7956
7957        N = pkg.receivers.size();
7958        r = null;
7959        for (i=0; i<N; i++) {
7960            PackageParser.Activity a = pkg.receivers.get(i);
7961            mReceivers.removeActivity(a, "receiver");
7962            if (DEBUG_REMOVE && chatty) {
7963                if (r == null) {
7964                    r = new StringBuilder(256);
7965                } else {
7966                    r.append(' ');
7967                }
7968                r.append(a.info.name);
7969            }
7970        }
7971        if (r != null) {
7972            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
7973        }
7974
7975        N = pkg.activities.size();
7976        r = null;
7977        for (i=0; i<N; i++) {
7978            PackageParser.Activity a = pkg.activities.get(i);
7979            mActivities.removeActivity(a, "activity");
7980            if (DEBUG_REMOVE && chatty) {
7981                if (r == null) {
7982                    r = new StringBuilder(256);
7983                } else {
7984                    r.append(' ');
7985                }
7986                r.append(a.info.name);
7987            }
7988        }
7989        if (r != null) {
7990            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
7991        }
7992
7993        N = pkg.permissions.size();
7994        r = null;
7995        for (i=0; i<N; i++) {
7996            PackageParser.Permission p = pkg.permissions.get(i);
7997            BasePermission bp = mSettings.mPermissions.get(p.info.name);
7998            if (bp == null) {
7999                bp = mSettings.mPermissionTrees.get(p.info.name);
8000            }
8001            if (bp != null && bp.perm == p) {
8002                bp.perm = null;
8003                if (DEBUG_REMOVE && chatty) {
8004                    if (r == null) {
8005                        r = new StringBuilder(256);
8006                    } else {
8007                        r.append(' ');
8008                    }
8009                    r.append(p.info.name);
8010                }
8011            }
8012            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8013                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
8014                if (appOpPerms != null) {
8015                    appOpPerms.remove(pkg.packageName);
8016                }
8017            }
8018        }
8019        if (r != null) {
8020            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8021        }
8022
8023        N = pkg.requestedPermissions.size();
8024        r = null;
8025        for (i=0; i<N; i++) {
8026            String perm = pkg.requestedPermissions.get(i);
8027            BasePermission bp = mSettings.mPermissions.get(perm);
8028            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8029                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
8030                if (appOpPerms != null) {
8031                    appOpPerms.remove(pkg.packageName);
8032                    if (appOpPerms.isEmpty()) {
8033                        mAppOpPermissionPackages.remove(perm);
8034                    }
8035                }
8036            }
8037        }
8038        if (r != null) {
8039            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8040        }
8041
8042        N = pkg.instrumentation.size();
8043        r = null;
8044        for (i=0; i<N; i++) {
8045            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8046            mInstrumentation.remove(a.getComponentName());
8047            if (DEBUG_REMOVE && chatty) {
8048                if (r == null) {
8049                    r = new StringBuilder(256);
8050                } else {
8051                    r.append(' ');
8052                }
8053                r.append(a.info.name);
8054            }
8055        }
8056        if (r != null) {
8057            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8058        }
8059
8060        r = null;
8061        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8062            // Only system apps can hold shared libraries.
8063            if (pkg.libraryNames != null) {
8064                for (i=0; i<pkg.libraryNames.size(); i++) {
8065                    String name = pkg.libraryNames.get(i);
8066                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8067                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8068                        mSharedLibraries.remove(name);
8069                        if (DEBUG_REMOVE && chatty) {
8070                            if (r == null) {
8071                                r = new StringBuilder(256);
8072                            } else {
8073                                r.append(' ');
8074                            }
8075                            r.append(name);
8076                        }
8077                    }
8078                }
8079            }
8080        }
8081        if (r != null) {
8082            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8083        }
8084    }
8085
8086    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8087        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8088            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8089                return true;
8090            }
8091        }
8092        return false;
8093    }
8094
8095    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8096    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8097    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8098
8099    private void updatePermissionsLPw(String changingPkg,
8100            PackageParser.Package pkgInfo, int flags) {
8101        // Make sure there are no dangling permission trees.
8102        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8103        while (it.hasNext()) {
8104            final BasePermission bp = it.next();
8105            if (bp.packageSetting == null) {
8106                // We may not yet have parsed the package, so just see if
8107                // we still know about its settings.
8108                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8109            }
8110            if (bp.packageSetting == null) {
8111                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8112                        + " from package " + bp.sourcePackage);
8113                it.remove();
8114            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8115                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8116                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8117                            + " from package " + bp.sourcePackage);
8118                    flags |= UPDATE_PERMISSIONS_ALL;
8119                    it.remove();
8120                }
8121            }
8122        }
8123
8124        // Make sure all dynamic permissions have been assigned to a package,
8125        // and make sure there are no dangling permissions.
8126        it = mSettings.mPermissions.values().iterator();
8127        while (it.hasNext()) {
8128            final BasePermission bp = it.next();
8129            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8130                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8131                        + bp.name + " pkg=" + bp.sourcePackage
8132                        + " info=" + bp.pendingInfo);
8133                if (bp.packageSetting == null && bp.pendingInfo != null) {
8134                    final BasePermission tree = findPermissionTreeLP(bp.name);
8135                    if (tree != null && tree.perm != null) {
8136                        bp.packageSetting = tree.packageSetting;
8137                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8138                                new PermissionInfo(bp.pendingInfo));
8139                        bp.perm.info.packageName = tree.perm.info.packageName;
8140                        bp.perm.info.name = bp.name;
8141                        bp.uid = tree.uid;
8142                    }
8143                }
8144            }
8145            if (bp.packageSetting == null) {
8146                // We may not yet have parsed the package, so just see if
8147                // we still know about its settings.
8148                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8149            }
8150            if (bp.packageSetting == null) {
8151                Slog.w(TAG, "Removing dangling permission: " + bp.name
8152                        + " from package " + bp.sourcePackage);
8153                it.remove();
8154            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8155                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8156                    Slog.i(TAG, "Removing old permission: " + bp.name
8157                            + " from package " + bp.sourcePackage);
8158                    flags |= UPDATE_PERMISSIONS_ALL;
8159                    it.remove();
8160                }
8161            }
8162        }
8163
8164        // Now update the permissions for all packages, in particular
8165        // replace the granted permissions of the system packages.
8166        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8167            for (PackageParser.Package pkg : mPackages.values()) {
8168                if (pkg != pkgInfo) {
8169                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
8170                            changingPkg);
8171                }
8172            }
8173        }
8174
8175        if (pkgInfo != null) {
8176            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
8177        }
8178    }
8179
8180    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8181            String packageOfInterest) {
8182        // IMPORTANT: There are two types of permissions: install and runtime.
8183        // Install time permissions are granted when the app is installed to
8184        // all device users and users added in the future. Runtime permissions
8185        // are granted at runtime explicitly to specific users. Normal and signature
8186        // protected permissions are install time permissions. Dangerous permissions
8187        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8188        // otherwise they are runtime permissions. This function does not manage
8189        // runtime permissions except for the case an app targeting Lollipop MR1
8190        // being upgraded to target a newer SDK, in which case dangerous permissions
8191        // are transformed from install time to runtime ones.
8192
8193        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8194        if (ps == null) {
8195            return;
8196        }
8197
8198        PermissionsState permissionsState = ps.getPermissionsState();
8199        PermissionsState origPermissions = permissionsState;
8200
8201        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8202
8203        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8204
8205        boolean changedInstallPermission = false;
8206
8207        if (replace) {
8208            ps.installPermissionsFixed = false;
8209            if (!ps.isSharedUser()) {
8210                origPermissions = new PermissionsState(permissionsState);
8211                permissionsState.reset();
8212            }
8213        }
8214
8215        permissionsState.setGlobalGids(mGlobalGids);
8216
8217        final int N = pkg.requestedPermissions.size();
8218        for (int i=0; i<N; i++) {
8219            final String name = pkg.requestedPermissions.get(i);
8220            final BasePermission bp = mSettings.mPermissions.get(name);
8221
8222            if (DEBUG_INSTALL) {
8223                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8224            }
8225
8226            if (bp == null || bp.packageSetting == null) {
8227                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8228                    Slog.w(TAG, "Unknown permission " + name
8229                            + " in package " + pkg.packageName);
8230                }
8231                continue;
8232            }
8233
8234            final String perm = bp.name;
8235            boolean allowedSig = false;
8236            int grant = GRANT_DENIED;
8237
8238            // Keep track of app op permissions.
8239            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8240                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8241                if (pkgs == null) {
8242                    pkgs = new ArraySet<>();
8243                    mAppOpPermissionPackages.put(bp.name, pkgs);
8244                }
8245                pkgs.add(pkg.packageName);
8246            }
8247
8248            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8249            switch (level) {
8250                case PermissionInfo.PROTECTION_NORMAL: {
8251                    // For all apps normal permissions are install time ones.
8252                    grant = GRANT_INSTALL;
8253                } break;
8254
8255                case PermissionInfo.PROTECTION_DANGEROUS: {
8256                    if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
8257                        // For legacy apps dangerous permissions are install time ones.
8258                        grant = GRANT_INSTALL_LEGACY;
8259                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8260                        // For legacy apps that became modern, install becomes runtime.
8261                        grant = GRANT_UPGRADE;
8262                    } else {
8263                        // For modern apps keep runtime permissions unchanged.
8264                        grant = GRANT_RUNTIME;
8265                    }
8266                } break;
8267
8268                case PermissionInfo.PROTECTION_SIGNATURE: {
8269                    // For all apps signature permissions are install time ones.
8270                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8271                    if (allowedSig) {
8272                        grant = GRANT_INSTALL;
8273                    }
8274                } break;
8275            }
8276
8277            if (DEBUG_INSTALL) {
8278                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8279            }
8280
8281            if (grant != GRANT_DENIED) {
8282                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8283                    // If this is an existing, non-system package, then
8284                    // we can't add any new permissions to it.
8285                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8286                        // Except...  if this is a permission that was added
8287                        // to the platform (note: need to only do this when
8288                        // updating the platform).
8289                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8290                            grant = GRANT_DENIED;
8291                        }
8292                    }
8293                }
8294
8295                switch (grant) {
8296                    case GRANT_INSTALL: {
8297                        // Revoke this as runtime permission to handle the case of
8298                        // a runtime permission being downgraded to an install one.
8299                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8300                            if (origPermissions.getRuntimePermissionState(
8301                                    bp.name, userId) != null) {
8302                                // Revoke the runtime permission and clear the flags.
8303                                origPermissions.revokeRuntimePermission(bp, userId);
8304                                origPermissions.updatePermissionFlags(bp, userId,
8305                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8306                                // If we revoked a permission permission, we have to write.
8307                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8308                                        changedRuntimePermissionUserIds, userId);
8309                            }
8310                        }
8311                        // Grant an install permission.
8312                        if (permissionsState.grantInstallPermission(bp) !=
8313                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8314                            changedInstallPermission = true;
8315                        }
8316                    } break;
8317
8318                    case GRANT_INSTALL_LEGACY: {
8319                        // Grant an install permission.
8320                        if (permissionsState.grantInstallPermission(bp) !=
8321                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8322                            changedInstallPermission = true;
8323                        }
8324                    } break;
8325
8326                    case GRANT_RUNTIME: {
8327                        // Grant previously granted runtime permissions.
8328                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8329                            PermissionState permissionState = origPermissions
8330                                    .getRuntimePermissionState(bp.name, userId);
8331                            final int flags = permissionState != null
8332                                    ? permissionState.getFlags() : 0;
8333                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8334                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8335                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8336                                    // If we cannot put the permission as it was, we have to write.
8337                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8338                                            changedRuntimePermissionUserIds, userId);
8339                                }
8340                            }
8341                            // Propagate the permission flags.
8342                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8343                        }
8344                    } break;
8345
8346                    case GRANT_UPGRADE: {
8347                        // Grant runtime permissions for a previously held install permission.
8348                        PermissionState permissionState = origPermissions
8349                                .getInstallPermissionState(bp.name);
8350                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8351
8352                        if (origPermissions.revokeInstallPermission(bp)
8353                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8354                            // We will be transferring the permission flags, so clear them.
8355                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8356                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8357                            changedInstallPermission = true;
8358                        }
8359
8360                        // If the permission is not to be promoted to runtime we ignore it and
8361                        // also its other flags as they are not applicable to install permissions.
8362                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8363                            for (int userId : currentUserIds) {
8364                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8365                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8366                                    // Transfer the permission flags.
8367                                    permissionsState.updatePermissionFlags(bp, userId,
8368                                            flags, flags);
8369                                    // If we granted the permission, we have to write.
8370                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8371                                            changedRuntimePermissionUserIds, userId);
8372                                }
8373                            }
8374                        }
8375                    } break;
8376
8377                    default: {
8378                        if (packageOfInterest == null
8379                                || packageOfInterest.equals(pkg.packageName)) {
8380                            Slog.w(TAG, "Not granting permission " + perm
8381                                    + " to package " + pkg.packageName
8382                                    + " because it was previously installed without");
8383                        }
8384                    } break;
8385                }
8386            } else {
8387                if (permissionsState.revokeInstallPermission(bp) !=
8388                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8389                    // Also drop the permission flags.
8390                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8391                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8392                    changedInstallPermission = true;
8393                    Slog.i(TAG, "Un-granting permission " + perm
8394                            + " from package " + pkg.packageName
8395                            + " (protectionLevel=" + bp.protectionLevel
8396                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8397                            + ")");
8398                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8399                    // Don't print warning for app op permissions, since it is fine for them
8400                    // not to be granted, there is a UI for the user to decide.
8401                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8402                        Slog.w(TAG, "Not granting permission " + perm
8403                                + " to package " + pkg.packageName
8404                                + " (protectionLevel=" + bp.protectionLevel
8405                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8406                                + ")");
8407                    }
8408                }
8409            }
8410        }
8411
8412        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8413                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8414            // This is the first that we have heard about this package, so the
8415            // permissions we have now selected are fixed until explicitly
8416            // changed.
8417            ps.installPermissionsFixed = true;
8418        }
8419
8420        // Persist the runtime permissions state for users with changes.
8421        for (int userId : changedRuntimePermissionUserIds) {
8422            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
8423        }
8424    }
8425
8426    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8427        boolean allowed = false;
8428        final int NP = PackageParser.NEW_PERMISSIONS.length;
8429        for (int ip=0; ip<NP; ip++) {
8430            final PackageParser.NewPermissionInfo npi
8431                    = PackageParser.NEW_PERMISSIONS[ip];
8432            if (npi.name.equals(perm)
8433                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8434                allowed = true;
8435                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8436                        + pkg.packageName);
8437                break;
8438            }
8439        }
8440        return allowed;
8441    }
8442
8443    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8444            BasePermission bp, PermissionsState origPermissions) {
8445        boolean allowed;
8446        allowed = (compareSignatures(
8447                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8448                        == PackageManager.SIGNATURE_MATCH)
8449                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8450                        == PackageManager.SIGNATURE_MATCH);
8451        if (!allowed && (bp.protectionLevel
8452                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
8453            if (isSystemApp(pkg)) {
8454                // For updated system applications, a system permission
8455                // is granted only if it had been defined by the original application.
8456                if (pkg.isUpdatedSystemApp()) {
8457                    final PackageSetting sysPs = mSettings
8458                            .getDisabledSystemPkgLPr(pkg.packageName);
8459                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8460                        // If the original was granted this permission, we take
8461                        // that grant decision as read and propagate it to the
8462                        // update.
8463                        if (sysPs.isPrivileged()) {
8464                            allowed = true;
8465                        }
8466                    } else {
8467                        // The system apk may have been updated with an older
8468                        // version of the one on the data partition, but which
8469                        // granted a new system permission that it didn't have
8470                        // before.  In this case we do want to allow the app to
8471                        // now get the new permission if the ancestral apk is
8472                        // privileged to get it.
8473                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
8474                            for (int j=0;
8475                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
8476                                if (perm.equals(
8477                                        sysPs.pkg.requestedPermissions.get(j))) {
8478                                    allowed = true;
8479                                    break;
8480                                }
8481                            }
8482                        }
8483                    }
8484                } else {
8485                    allowed = isPrivilegedApp(pkg);
8486                }
8487            }
8488        }
8489        if (!allowed) {
8490            if (!allowed && (bp.protectionLevel
8491                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
8492                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.MNC) {
8493                // If this was a previously normal/dangerous permission that got moved
8494                // to a system permission as part of the runtime permission redesign, then
8495                // we still want to blindly grant it to old apps.
8496                allowed = true;
8497            }
8498            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
8499                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
8500                // If this permission is to be granted to the system installer and
8501                // this app is an installer, then it gets the permission.
8502                allowed = true;
8503            }
8504            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
8505                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
8506                // If this permission is to be granted to the system verifier and
8507                // this app is a verifier, then it gets the permission.
8508                allowed = true;
8509            }
8510            if (!allowed && (bp.protectionLevel
8511                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
8512                    && isSystemApp(pkg)) {
8513                // Any pre-installed system app is allowed to get this permission.
8514                allowed = true;
8515            }
8516            if (!allowed && (bp.protectionLevel
8517                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8518                // For development permissions, a development permission
8519                // is granted only if it was already granted.
8520                allowed = origPermissions.hasInstallPermission(perm);
8521            }
8522        }
8523        return allowed;
8524    }
8525
8526    final class ActivityIntentResolver
8527            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8528        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8529                boolean defaultOnly, int userId) {
8530            if (!sUserManager.exists(userId)) return null;
8531            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8532            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8533        }
8534
8535        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8536                int userId) {
8537            if (!sUserManager.exists(userId)) return null;
8538            mFlags = flags;
8539            return super.queryIntent(intent, resolvedType,
8540                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8541        }
8542
8543        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8544                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8545            if (!sUserManager.exists(userId)) return null;
8546            if (packageActivities == null) {
8547                return null;
8548            }
8549            mFlags = flags;
8550            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8551            final int N = packageActivities.size();
8552            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8553                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8554
8555            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8556            for (int i = 0; i < N; ++i) {
8557                intentFilters = packageActivities.get(i).intents;
8558                if (intentFilters != null && intentFilters.size() > 0) {
8559                    PackageParser.ActivityIntentInfo[] array =
8560                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
8561                    intentFilters.toArray(array);
8562                    listCut.add(array);
8563                }
8564            }
8565            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8566        }
8567
8568        public final void addActivity(PackageParser.Activity a, String type) {
8569            final boolean systemApp = a.info.applicationInfo.isSystemApp();
8570            mActivities.put(a.getComponentName(), a);
8571            if (DEBUG_SHOW_INFO)
8572                Log.v(
8573                TAG, "  " + type + " " +
8574                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8575            if (DEBUG_SHOW_INFO)
8576                Log.v(TAG, "    Class=" + a.info.name);
8577            final int NI = a.intents.size();
8578            for (int j=0; j<NI; j++) {
8579                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8580                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
8581                    intent.setPriority(0);
8582                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
8583                            + a.className + " with priority > 0, forcing to 0");
8584                }
8585                if (DEBUG_SHOW_INFO) {
8586                    Log.v(TAG, "    IntentFilter:");
8587                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8588                }
8589                if (!intent.debugCheck()) {
8590                    Log.w(TAG, "==> For Activity " + a.info.name);
8591                }
8592                addFilter(intent);
8593            }
8594        }
8595
8596        public final void removeActivity(PackageParser.Activity a, String type) {
8597            mActivities.remove(a.getComponentName());
8598            if (DEBUG_SHOW_INFO) {
8599                Log.v(TAG, "  " + type + " "
8600                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
8601                                : a.info.name) + ":");
8602                Log.v(TAG, "    Class=" + a.info.name);
8603            }
8604            final int NI = a.intents.size();
8605            for (int j=0; j<NI; j++) {
8606                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8607                if (DEBUG_SHOW_INFO) {
8608                    Log.v(TAG, "    IntentFilter:");
8609                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8610                }
8611                removeFilter(intent);
8612            }
8613        }
8614
8615        @Override
8616        protected boolean allowFilterResult(
8617                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
8618            ActivityInfo filterAi = filter.activity.info;
8619            for (int i=dest.size()-1; i>=0; i--) {
8620                ActivityInfo destAi = dest.get(i).activityInfo;
8621                if (destAi.name == filterAi.name
8622                        && destAi.packageName == filterAi.packageName) {
8623                    return false;
8624                }
8625            }
8626            return true;
8627        }
8628
8629        @Override
8630        protected ActivityIntentInfo[] newArray(int size) {
8631            return new ActivityIntentInfo[size];
8632        }
8633
8634        @Override
8635        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
8636            if (!sUserManager.exists(userId)) return true;
8637            PackageParser.Package p = filter.activity.owner;
8638            if (p != null) {
8639                PackageSetting ps = (PackageSetting)p.mExtras;
8640                if (ps != null) {
8641                    // System apps are never considered stopped for purposes of
8642                    // filtering, because there may be no way for the user to
8643                    // actually re-launch them.
8644                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
8645                            && ps.getStopped(userId);
8646                }
8647            }
8648            return false;
8649        }
8650
8651        @Override
8652        protected boolean isPackageForFilter(String packageName,
8653                PackageParser.ActivityIntentInfo info) {
8654            return packageName.equals(info.activity.owner.packageName);
8655        }
8656
8657        @Override
8658        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
8659                int match, int userId) {
8660            if (!sUserManager.exists(userId)) return null;
8661            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
8662                return null;
8663            }
8664            final PackageParser.Activity activity = info.activity;
8665            if (mSafeMode && (activity.info.applicationInfo.flags
8666                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8667                return null;
8668            }
8669            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
8670            if (ps == null) {
8671                return null;
8672            }
8673            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
8674                    ps.readUserState(userId), userId);
8675            if (ai == null) {
8676                return null;
8677            }
8678            final ResolveInfo res = new ResolveInfo();
8679            res.activityInfo = ai;
8680            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8681                res.filter = info;
8682            }
8683            if (info != null) {
8684                res.handleAllWebDataURI = info.handleAllWebDataURI();
8685            }
8686            res.priority = info.getPriority();
8687            res.preferredOrder = activity.owner.mPreferredOrder;
8688            //System.out.println("Result: " + res.activityInfo.className +
8689            //                   " = " + res.priority);
8690            res.match = match;
8691            res.isDefault = info.hasDefault;
8692            res.labelRes = info.labelRes;
8693            res.nonLocalizedLabel = info.nonLocalizedLabel;
8694            if (userNeedsBadging(userId)) {
8695                res.noResourceId = true;
8696            } else {
8697                res.icon = info.icon;
8698            }
8699            res.iconResourceId = info.icon;
8700            res.system = res.activityInfo.applicationInfo.isSystemApp();
8701            return res;
8702        }
8703
8704        @Override
8705        protected void sortResults(List<ResolveInfo> results) {
8706            Collections.sort(results, mResolvePrioritySorter);
8707        }
8708
8709        @Override
8710        protected void dumpFilter(PrintWriter out, String prefix,
8711                PackageParser.ActivityIntentInfo filter) {
8712            out.print(prefix); out.print(
8713                    Integer.toHexString(System.identityHashCode(filter.activity)));
8714                    out.print(' ');
8715                    filter.activity.printComponentShortName(out);
8716                    out.print(" filter ");
8717                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8718        }
8719
8720        @Override
8721        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
8722            return filter.activity;
8723        }
8724
8725        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8726            PackageParser.Activity activity = (PackageParser.Activity)label;
8727            out.print(prefix); out.print(
8728                    Integer.toHexString(System.identityHashCode(activity)));
8729                    out.print(' ');
8730                    activity.printComponentShortName(out);
8731            if (count > 1) {
8732                out.print(" ("); out.print(count); out.print(" filters)");
8733            }
8734            out.println();
8735        }
8736
8737//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8738//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8739//            final List<ResolveInfo> retList = Lists.newArrayList();
8740//            while (i.hasNext()) {
8741//                final ResolveInfo resolveInfo = i.next();
8742//                if (isEnabledLP(resolveInfo.activityInfo)) {
8743//                    retList.add(resolveInfo);
8744//                }
8745//            }
8746//            return retList;
8747//        }
8748
8749        // Keys are String (activity class name), values are Activity.
8750        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
8751                = new ArrayMap<ComponentName, PackageParser.Activity>();
8752        private int mFlags;
8753    }
8754
8755    private final class ServiceIntentResolver
8756            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
8757        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8758                boolean defaultOnly, int userId) {
8759            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8760            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8761        }
8762
8763        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8764                int userId) {
8765            if (!sUserManager.exists(userId)) return null;
8766            mFlags = flags;
8767            return super.queryIntent(intent, resolvedType,
8768                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8769        }
8770
8771        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8772                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
8773            if (!sUserManager.exists(userId)) return null;
8774            if (packageServices == null) {
8775                return null;
8776            }
8777            mFlags = flags;
8778            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8779            final int N = packageServices.size();
8780            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
8781                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
8782
8783            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
8784            for (int i = 0; i < N; ++i) {
8785                intentFilters = packageServices.get(i).intents;
8786                if (intentFilters != null && intentFilters.size() > 0) {
8787                    PackageParser.ServiceIntentInfo[] array =
8788                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
8789                    intentFilters.toArray(array);
8790                    listCut.add(array);
8791                }
8792            }
8793            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8794        }
8795
8796        public final void addService(PackageParser.Service s) {
8797            mServices.put(s.getComponentName(), s);
8798            if (DEBUG_SHOW_INFO) {
8799                Log.v(TAG, "  "
8800                        + (s.info.nonLocalizedLabel != null
8801                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8802                Log.v(TAG, "    Class=" + s.info.name);
8803            }
8804            final int NI = s.intents.size();
8805            int j;
8806            for (j=0; j<NI; j++) {
8807                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8808                if (DEBUG_SHOW_INFO) {
8809                    Log.v(TAG, "    IntentFilter:");
8810                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8811                }
8812                if (!intent.debugCheck()) {
8813                    Log.w(TAG, "==> For Service " + s.info.name);
8814                }
8815                addFilter(intent);
8816            }
8817        }
8818
8819        public final void removeService(PackageParser.Service s) {
8820            mServices.remove(s.getComponentName());
8821            if (DEBUG_SHOW_INFO) {
8822                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
8823                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8824                Log.v(TAG, "    Class=" + s.info.name);
8825            }
8826            final int NI = s.intents.size();
8827            int j;
8828            for (j=0; j<NI; j++) {
8829                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8830                if (DEBUG_SHOW_INFO) {
8831                    Log.v(TAG, "    IntentFilter:");
8832                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8833                }
8834                removeFilter(intent);
8835            }
8836        }
8837
8838        @Override
8839        protected boolean allowFilterResult(
8840                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
8841            ServiceInfo filterSi = filter.service.info;
8842            for (int i=dest.size()-1; i>=0; i--) {
8843                ServiceInfo destAi = dest.get(i).serviceInfo;
8844                if (destAi.name == filterSi.name
8845                        && destAi.packageName == filterSi.packageName) {
8846                    return false;
8847                }
8848            }
8849            return true;
8850        }
8851
8852        @Override
8853        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
8854            return new PackageParser.ServiceIntentInfo[size];
8855        }
8856
8857        @Override
8858        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
8859            if (!sUserManager.exists(userId)) return true;
8860            PackageParser.Package p = filter.service.owner;
8861            if (p != null) {
8862                PackageSetting ps = (PackageSetting)p.mExtras;
8863                if (ps != null) {
8864                    // System apps are never considered stopped for purposes of
8865                    // filtering, because there may be no way for the user to
8866                    // actually re-launch them.
8867                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8868                            && ps.getStopped(userId);
8869                }
8870            }
8871            return false;
8872        }
8873
8874        @Override
8875        protected boolean isPackageForFilter(String packageName,
8876                PackageParser.ServiceIntentInfo info) {
8877            return packageName.equals(info.service.owner.packageName);
8878        }
8879
8880        @Override
8881        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
8882                int match, int userId) {
8883            if (!sUserManager.exists(userId)) return null;
8884            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
8885            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
8886                return null;
8887            }
8888            final PackageParser.Service service = info.service;
8889            if (mSafeMode && (service.info.applicationInfo.flags
8890                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8891                return null;
8892            }
8893            PackageSetting ps = (PackageSetting) service.owner.mExtras;
8894            if (ps == null) {
8895                return null;
8896            }
8897            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
8898                    ps.readUserState(userId), userId);
8899            if (si == null) {
8900                return null;
8901            }
8902            final ResolveInfo res = new ResolveInfo();
8903            res.serviceInfo = si;
8904            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8905                res.filter = filter;
8906            }
8907            res.priority = info.getPriority();
8908            res.preferredOrder = service.owner.mPreferredOrder;
8909            res.match = match;
8910            res.isDefault = info.hasDefault;
8911            res.labelRes = info.labelRes;
8912            res.nonLocalizedLabel = info.nonLocalizedLabel;
8913            res.icon = info.icon;
8914            res.system = res.serviceInfo.applicationInfo.isSystemApp();
8915            return res;
8916        }
8917
8918        @Override
8919        protected void sortResults(List<ResolveInfo> results) {
8920            Collections.sort(results, mResolvePrioritySorter);
8921        }
8922
8923        @Override
8924        protected void dumpFilter(PrintWriter out, String prefix,
8925                PackageParser.ServiceIntentInfo filter) {
8926            out.print(prefix); out.print(
8927                    Integer.toHexString(System.identityHashCode(filter.service)));
8928                    out.print(' ');
8929                    filter.service.printComponentShortName(out);
8930                    out.print(" filter ");
8931                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8932        }
8933
8934        @Override
8935        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
8936            return filter.service;
8937        }
8938
8939        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8940            PackageParser.Service service = (PackageParser.Service)label;
8941            out.print(prefix); out.print(
8942                    Integer.toHexString(System.identityHashCode(service)));
8943                    out.print(' ');
8944                    service.printComponentShortName(out);
8945            if (count > 1) {
8946                out.print(" ("); out.print(count); out.print(" filters)");
8947            }
8948            out.println();
8949        }
8950
8951//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8952//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8953//            final List<ResolveInfo> retList = Lists.newArrayList();
8954//            while (i.hasNext()) {
8955//                final ResolveInfo resolveInfo = (ResolveInfo) i;
8956//                if (isEnabledLP(resolveInfo.serviceInfo)) {
8957//                    retList.add(resolveInfo);
8958//                }
8959//            }
8960//            return retList;
8961//        }
8962
8963        // Keys are String (activity class name), values are Activity.
8964        private final ArrayMap<ComponentName, PackageParser.Service> mServices
8965                = new ArrayMap<ComponentName, PackageParser.Service>();
8966        private int mFlags;
8967    };
8968
8969    private final class ProviderIntentResolver
8970            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
8971        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8972                boolean defaultOnly, int userId) {
8973            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8974            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8975        }
8976
8977        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8978                int userId) {
8979            if (!sUserManager.exists(userId))
8980                return null;
8981            mFlags = flags;
8982            return super.queryIntent(intent, resolvedType,
8983                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8984        }
8985
8986        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8987                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
8988            if (!sUserManager.exists(userId))
8989                return null;
8990            if (packageProviders == null) {
8991                return null;
8992            }
8993            mFlags = flags;
8994            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
8995            final int N = packageProviders.size();
8996            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
8997                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
8998
8999            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9000            for (int i = 0; i < N; ++i) {
9001                intentFilters = packageProviders.get(i).intents;
9002                if (intentFilters != null && intentFilters.size() > 0) {
9003                    PackageParser.ProviderIntentInfo[] array =
9004                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
9005                    intentFilters.toArray(array);
9006                    listCut.add(array);
9007                }
9008            }
9009            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9010        }
9011
9012        public final void addProvider(PackageParser.Provider p) {
9013            if (mProviders.containsKey(p.getComponentName())) {
9014                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9015                return;
9016            }
9017
9018            mProviders.put(p.getComponentName(), p);
9019            if (DEBUG_SHOW_INFO) {
9020                Log.v(TAG, "  "
9021                        + (p.info.nonLocalizedLabel != null
9022                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
9023                Log.v(TAG, "    Class=" + p.info.name);
9024            }
9025            final int NI = p.intents.size();
9026            int j;
9027            for (j = 0; j < NI; j++) {
9028                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9029                if (DEBUG_SHOW_INFO) {
9030                    Log.v(TAG, "    IntentFilter:");
9031                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9032                }
9033                if (!intent.debugCheck()) {
9034                    Log.w(TAG, "==> For Provider " + p.info.name);
9035                }
9036                addFilter(intent);
9037            }
9038        }
9039
9040        public final void removeProvider(PackageParser.Provider p) {
9041            mProviders.remove(p.getComponentName());
9042            if (DEBUG_SHOW_INFO) {
9043                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9044                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
9045                Log.v(TAG, "    Class=" + p.info.name);
9046            }
9047            final int NI = p.intents.size();
9048            int j;
9049            for (j = 0; j < NI; j++) {
9050                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9051                if (DEBUG_SHOW_INFO) {
9052                    Log.v(TAG, "    IntentFilter:");
9053                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9054                }
9055                removeFilter(intent);
9056            }
9057        }
9058
9059        @Override
9060        protected boolean allowFilterResult(
9061                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9062            ProviderInfo filterPi = filter.provider.info;
9063            for (int i = dest.size() - 1; i >= 0; i--) {
9064                ProviderInfo destPi = dest.get(i).providerInfo;
9065                if (destPi.name == filterPi.name
9066                        && destPi.packageName == filterPi.packageName) {
9067                    return false;
9068                }
9069            }
9070            return true;
9071        }
9072
9073        @Override
9074        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9075            return new PackageParser.ProviderIntentInfo[size];
9076        }
9077
9078        @Override
9079        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9080            if (!sUserManager.exists(userId))
9081                return true;
9082            PackageParser.Package p = filter.provider.owner;
9083            if (p != null) {
9084                PackageSetting ps = (PackageSetting) p.mExtras;
9085                if (ps != null) {
9086                    // System apps are never considered stopped for purposes of
9087                    // filtering, because there may be no way for the user to
9088                    // actually re-launch them.
9089                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9090                            && ps.getStopped(userId);
9091                }
9092            }
9093            return false;
9094        }
9095
9096        @Override
9097        protected boolean isPackageForFilter(String packageName,
9098                PackageParser.ProviderIntentInfo info) {
9099            return packageName.equals(info.provider.owner.packageName);
9100        }
9101
9102        @Override
9103        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9104                int match, int userId) {
9105            if (!sUserManager.exists(userId))
9106                return null;
9107            final PackageParser.ProviderIntentInfo info = filter;
9108            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
9109                return null;
9110            }
9111            final PackageParser.Provider provider = info.provider;
9112            if (mSafeMode && (provider.info.applicationInfo.flags
9113                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
9114                return null;
9115            }
9116            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9117            if (ps == null) {
9118                return null;
9119            }
9120            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9121                    ps.readUserState(userId), userId);
9122            if (pi == null) {
9123                return null;
9124            }
9125            final ResolveInfo res = new ResolveInfo();
9126            res.providerInfo = pi;
9127            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9128                res.filter = filter;
9129            }
9130            res.priority = info.getPriority();
9131            res.preferredOrder = provider.owner.mPreferredOrder;
9132            res.match = match;
9133            res.isDefault = info.hasDefault;
9134            res.labelRes = info.labelRes;
9135            res.nonLocalizedLabel = info.nonLocalizedLabel;
9136            res.icon = info.icon;
9137            res.system = res.providerInfo.applicationInfo.isSystemApp();
9138            return res;
9139        }
9140
9141        @Override
9142        protected void sortResults(List<ResolveInfo> results) {
9143            Collections.sort(results, mResolvePrioritySorter);
9144        }
9145
9146        @Override
9147        protected void dumpFilter(PrintWriter out, String prefix,
9148                PackageParser.ProviderIntentInfo filter) {
9149            out.print(prefix);
9150            out.print(
9151                    Integer.toHexString(System.identityHashCode(filter.provider)));
9152            out.print(' ');
9153            filter.provider.printComponentShortName(out);
9154            out.print(" filter ");
9155            out.println(Integer.toHexString(System.identityHashCode(filter)));
9156        }
9157
9158        @Override
9159        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9160            return filter.provider;
9161        }
9162
9163        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9164            PackageParser.Provider provider = (PackageParser.Provider)label;
9165            out.print(prefix); out.print(
9166                    Integer.toHexString(System.identityHashCode(provider)));
9167                    out.print(' ');
9168                    provider.printComponentShortName(out);
9169            if (count > 1) {
9170                out.print(" ("); out.print(count); out.print(" filters)");
9171            }
9172            out.println();
9173        }
9174
9175        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9176                = new ArrayMap<ComponentName, PackageParser.Provider>();
9177        private int mFlags;
9178    };
9179
9180    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9181            new Comparator<ResolveInfo>() {
9182        public int compare(ResolveInfo r1, ResolveInfo r2) {
9183            int v1 = r1.priority;
9184            int v2 = r2.priority;
9185            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9186            if (v1 != v2) {
9187                return (v1 > v2) ? -1 : 1;
9188            }
9189            v1 = r1.preferredOrder;
9190            v2 = r2.preferredOrder;
9191            if (v1 != v2) {
9192                return (v1 > v2) ? -1 : 1;
9193            }
9194            if (r1.isDefault != r2.isDefault) {
9195                return r1.isDefault ? -1 : 1;
9196            }
9197            v1 = r1.match;
9198            v2 = r2.match;
9199            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9200            if (v1 != v2) {
9201                return (v1 > v2) ? -1 : 1;
9202            }
9203            if (r1.system != r2.system) {
9204                return r1.system ? -1 : 1;
9205            }
9206            return 0;
9207        }
9208    };
9209
9210    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9211            new Comparator<ProviderInfo>() {
9212        public int compare(ProviderInfo p1, ProviderInfo p2) {
9213            final int v1 = p1.initOrder;
9214            final int v2 = p2.initOrder;
9215            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9216        }
9217    };
9218
9219    final void sendPackageBroadcast(final String action, final String pkg,
9220            final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
9221            final int[] userIds) {
9222        mHandler.post(new Runnable() {
9223            @Override
9224            public void run() {
9225                try {
9226                    final IActivityManager am = ActivityManagerNative.getDefault();
9227                    if (am == null) return;
9228                    final int[] resolvedUserIds;
9229                    if (userIds == null) {
9230                        resolvedUserIds = am.getRunningUserIds();
9231                    } else {
9232                        resolvedUserIds = userIds;
9233                    }
9234                    for (int id : resolvedUserIds) {
9235                        final Intent intent = new Intent(action,
9236                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9237                        if (extras != null) {
9238                            intent.putExtras(extras);
9239                        }
9240                        if (targetPkg != null) {
9241                            intent.setPackage(targetPkg);
9242                        }
9243                        // Modify the UID when posting to other users
9244                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9245                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9246                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9247                            intent.putExtra(Intent.EXTRA_UID, uid);
9248                        }
9249                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9250                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
9251                        if (DEBUG_BROADCASTS) {
9252                            RuntimeException here = new RuntimeException("here");
9253                            here.fillInStackTrace();
9254                            Slog.d(TAG, "Sending to user " + id + ": "
9255                                    + intent.toShortString(false, true, false, false)
9256                                    + " " + intent.getExtras(), here);
9257                        }
9258                        am.broadcastIntent(null, intent, null, finishedReceiver,
9259                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9260                                null, finishedReceiver != null, false, id);
9261                    }
9262                } catch (RemoteException ex) {
9263                }
9264            }
9265        });
9266    }
9267
9268    /**
9269     * Check if the external storage media is available. This is true if there
9270     * is a mounted external storage medium or if the external storage is
9271     * emulated.
9272     */
9273    private boolean isExternalMediaAvailable() {
9274        return mMediaMounted || Environment.isExternalStorageEmulated();
9275    }
9276
9277    @Override
9278    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9279        // writer
9280        synchronized (mPackages) {
9281            if (!isExternalMediaAvailable()) {
9282                // If the external storage is no longer mounted at this point,
9283                // the caller may not have been able to delete all of this
9284                // packages files and can not delete any more.  Bail.
9285                return null;
9286            }
9287            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9288            if (lastPackage != null) {
9289                pkgs.remove(lastPackage);
9290            }
9291            if (pkgs.size() > 0) {
9292                return pkgs.get(0);
9293            }
9294        }
9295        return null;
9296    }
9297
9298    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9299        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9300                userId, andCode ? 1 : 0, packageName);
9301        if (mSystemReady) {
9302            msg.sendToTarget();
9303        } else {
9304            if (mPostSystemReadyMessages == null) {
9305                mPostSystemReadyMessages = new ArrayList<>();
9306            }
9307            mPostSystemReadyMessages.add(msg);
9308        }
9309    }
9310
9311    void startCleaningPackages() {
9312        // reader
9313        synchronized (mPackages) {
9314            if (!isExternalMediaAvailable()) {
9315                return;
9316            }
9317            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9318                return;
9319            }
9320        }
9321        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9322        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9323        IActivityManager am = ActivityManagerNative.getDefault();
9324        if (am != null) {
9325            try {
9326                am.startService(null, intent, null, mContext.getOpPackageName(),
9327                        UserHandle.USER_OWNER);
9328            } catch (RemoteException e) {
9329            }
9330        }
9331    }
9332
9333    @Override
9334    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9335            int installFlags, String installerPackageName, VerificationParams verificationParams,
9336            String packageAbiOverride) {
9337        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9338                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9339    }
9340
9341    @Override
9342    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9343            int installFlags, String installerPackageName, VerificationParams verificationParams,
9344            String packageAbiOverride, int userId) {
9345        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9346
9347        final int callingUid = Binder.getCallingUid();
9348        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9349
9350        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9351            try {
9352                if (observer != null) {
9353                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9354                }
9355            } catch (RemoteException re) {
9356            }
9357            return;
9358        }
9359
9360        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9361            installFlags |= PackageManager.INSTALL_FROM_ADB;
9362
9363        } else {
9364            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9365            // about installerPackageName.
9366
9367            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9368            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9369        }
9370
9371        UserHandle user;
9372        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9373            user = UserHandle.ALL;
9374        } else {
9375            user = new UserHandle(userId);
9376        }
9377
9378        // Only system components can circumvent runtime permissions when installing.
9379        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9380                && mContext.checkCallingOrSelfPermission(Manifest.permission
9381                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9382            throw new SecurityException("You need the "
9383                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9384                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9385        }
9386
9387        verificationParams.setInstallerUid(callingUid);
9388
9389        final File originFile = new File(originPath);
9390        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9391
9392        final Message msg = mHandler.obtainMessage(INIT_COPY);
9393        msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName,
9394                null, verificationParams, user, packageAbiOverride);
9395        mHandler.sendMessage(msg);
9396    }
9397
9398    void installStage(String packageName, File stagedDir, String stagedCid,
9399            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
9400            String installerPackageName, int installerUid, UserHandle user) {
9401        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
9402                params.referrerUri, installerUid, null);
9403        verifParams.setInstallerUid(installerUid);
9404
9405        final OriginInfo origin;
9406        if (stagedDir != null) {
9407            origin = OriginInfo.fromStagedFile(stagedDir);
9408        } else {
9409            origin = OriginInfo.fromStagedContainer(stagedCid);
9410        }
9411
9412        final Message msg = mHandler.obtainMessage(INIT_COPY);
9413        msg.obj = new InstallParams(origin, null, observer, params.installFlags,
9414                installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride);
9415        mHandler.sendMessage(msg);
9416    }
9417
9418    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
9419        Bundle extras = new Bundle(1);
9420        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
9421
9422        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
9423                packageName, extras, null, null, new int[] {userId});
9424        try {
9425            IActivityManager am = ActivityManagerNative.getDefault();
9426            final boolean isSystem =
9427                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
9428            if (isSystem && am.isUserRunning(userId, false)) {
9429                // The just-installed/enabled app is bundled on the system, so presumed
9430                // to be able to run automatically without needing an explicit launch.
9431                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
9432                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
9433                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
9434                        .setPackage(packageName);
9435                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
9436                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
9437            }
9438        } catch (RemoteException e) {
9439            // shouldn't happen
9440            Slog.w(TAG, "Unable to bootstrap installed package", e);
9441        }
9442    }
9443
9444    @Override
9445    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9446            int userId) {
9447        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9448        PackageSetting pkgSetting;
9449        final int uid = Binder.getCallingUid();
9450        enforceCrossUserPermission(uid, userId, true, true,
9451                "setApplicationHiddenSetting for user " + userId);
9452
9453        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9454            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9455            return false;
9456        }
9457
9458        long callingId = Binder.clearCallingIdentity();
9459        try {
9460            boolean sendAdded = false;
9461            boolean sendRemoved = false;
9462            // writer
9463            synchronized (mPackages) {
9464                pkgSetting = mSettings.mPackages.get(packageName);
9465                if (pkgSetting == null) {
9466                    return false;
9467                }
9468                if (pkgSetting.getHidden(userId) != hidden) {
9469                    pkgSetting.setHidden(hidden, userId);
9470                    mSettings.writePackageRestrictionsLPr(userId);
9471                    if (hidden) {
9472                        sendRemoved = true;
9473                    } else {
9474                        sendAdded = true;
9475                    }
9476                }
9477            }
9478            if (sendAdded) {
9479                sendPackageAddedForUser(packageName, pkgSetting, userId);
9480                return true;
9481            }
9482            if (sendRemoved) {
9483                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
9484                        "hiding pkg");
9485                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
9486            }
9487        } finally {
9488            Binder.restoreCallingIdentity(callingId);
9489        }
9490        return false;
9491    }
9492
9493    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9494            int userId) {
9495        final PackageRemovedInfo info = new PackageRemovedInfo();
9496        info.removedPackage = packageName;
9497        info.removedUsers = new int[] {userId};
9498        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9499        info.sendBroadcast(false, false, false);
9500    }
9501
9502    /**
9503     * Returns true if application is not found or there was an error. Otherwise it returns
9504     * the hidden state of the package for the given user.
9505     */
9506    @Override
9507    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9508        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9509        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9510                false, "getApplicationHidden for user " + userId);
9511        PackageSetting pkgSetting;
9512        long callingId = Binder.clearCallingIdentity();
9513        try {
9514            // writer
9515            synchronized (mPackages) {
9516                pkgSetting = mSettings.mPackages.get(packageName);
9517                if (pkgSetting == null) {
9518                    return true;
9519                }
9520                return pkgSetting.getHidden(userId);
9521            }
9522        } finally {
9523            Binder.restoreCallingIdentity(callingId);
9524        }
9525    }
9526
9527    /**
9528     * @hide
9529     */
9530    @Override
9531    public int installExistingPackageAsUser(String packageName, int userId) {
9532        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9533                null);
9534        PackageSetting pkgSetting;
9535        final int uid = Binder.getCallingUid();
9536        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9537                + userId);
9538        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9539            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9540        }
9541
9542        long callingId = Binder.clearCallingIdentity();
9543        try {
9544            boolean sendAdded = false;
9545
9546            // writer
9547            synchronized (mPackages) {
9548                pkgSetting = mSettings.mPackages.get(packageName);
9549                if (pkgSetting == null) {
9550                    return PackageManager.INSTALL_FAILED_INVALID_URI;
9551                }
9552                if (!pkgSetting.getInstalled(userId)) {
9553                    pkgSetting.setInstalled(true, userId);
9554                    pkgSetting.setHidden(false, userId);
9555                    mSettings.writePackageRestrictionsLPr(userId);
9556                    sendAdded = true;
9557                }
9558            }
9559
9560            if (sendAdded) {
9561                sendPackageAddedForUser(packageName, pkgSetting, userId);
9562            }
9563        } finally {
9564            Binder.restoreCallingIdentity(callingId);
9565        }
9566
9567        return PackageManager.INSTALL_SUCCEEDED;
9568    }
9569
9570    boolean isUserRestricted(int userId, String restrictionKey) {
9571        Bundle restrictions = sUserManager.getUserRestrictions(userId);
9572        if (restrictions.getBoolean(restrictionKey, false)) {
9573            Log.w(TAG, "User is restricted: " + restrictionKey);
9574            return true;
9575        }
9576        return false;
9577    }
9578
9579    @Override
9580    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
9581        mContext.enforceCallingOrSelfPermission(
9582                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9583                "Only package verification agents can verify applications");
9584
9585        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9586        final PackageVerificationResponse response = new PackageVerificationResponse(
9587                verificationCode, Binder.getCallingUid());
9588        msg.arg1 = id;
9589        msg.obj = response;
9590        mHandler.sendMessage(msg);
9591    }
9592
9593    @Override
9594    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
9595            long millisecondsToDelay) {
9596        mContext.enforceCallingOrSelfPermission(
9597                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9598                "Only package verification agents can extend verification timeouts");
9599
9600        final PackageVerificationState state = mPendingVerification.get(id);
9601        final PackageVerificationResponse response = new PackageVerificationResponse(
9602                verificationCodeAtTimeout, Binder.getCallingUid());
9603
9604        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
9605            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
9606        }
9607        if (millisecondsToDelay < 0) {
9608            millisecondsToDelay = 0;
9609        }
9610        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9611                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9612            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9613        }
9614
9615        if ((state != null) && !state.timeoutExtended()) {
9616            state.extendTimeout();
9617
9618            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9619            msg.arg1 = id;
9620            msg.obj = response;
9621            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
9622        }
9623    }
9624
9625    private void broadcastPackageVerified(int verificationId, Uri packageUri,
9626            int verificationCode, UserHandle user) {
9627        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
9628        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
9629        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9630        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9631        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
9632
9633        mContext.sendBroadcastAsUser(intent, user,
9634                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
9635    }
9636
9637    private ComponentName matchComponentForVerifier(String packageName,
9638            List<ResolveInfo> receivers) {
9639        ActivityInfo targetReceiver = null;
9640
9641        final int NR = receivers.size();
9642        for (int i = 0; i < NR; i++) {
9643            final ResolveInfo info = receivers.get(i);
9644            if (info.activityInfo == null) {
9645                continue;
9646            }
9647
9648            if (packageName.equals(info.activityInfo.packageName)) {
9649                targetReceiver = info.activityInfo;
9650                break;
9651            }
9652        }
9653
9654        if (targetReceiver == null) {
9655            return null;
9656        }
9657
9658        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
9659    }
9660
9661    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
9662            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
9663        if (pkgInfo.verifiers.length == 0) {
9664            return null;
9665        }
9666
9667        final int N = pkgInfo.verifiers.length;
9668        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
9669        for (int i = 0; i < N; i++) {
9670            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
9671
9672            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
9673                    receivers);
9674            if (comp == null) {
9675                continue;
9676            }
9677
9678            final int verifierUid = getUidForVerifier(verifierInfo);
9679            if (verifierUid == -1) {
9680                continue;
9681            }
9682
9683            if (DEBUG_VERIFY) {
9684                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
9685                        + " with the correct signature");
9686            }
9687            sufficientVerifiers.add(comp);
9688            verificationState.addSufficientVerifier(verifierUid);
9689        }
9690
9691        return sufficientVerifiers;
9692    }
9693
9694    private int getUidForVerifier(VerifierInfo verifierInfo) {
9695        synchronized (mPackages) {
9696            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
9697            if (pkg == null) {
9698                return -1;
9699            } else if (pkg.mSignatures.length != 1) {
9700                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9701                        + " has more than one signature; ignoring");
9702                return -1;
9703            }
9704
9705            /*
9706             * If the public key of the package's signature does not match
9707             * our expected public key, then this is a different package and
9708             * we should skip.
9709             */
9710
9711            final byte[] expectedPublicKey;
9712            try {
9713                final Signature verifierSig = pkg.mSignatures[0];
9714                final PublicKey publicKey = verifierSig.getPublicKey();
9715                expectedPublicKey = publicKey.getEncoded();
9716            } catch (CertificateException e) {
9717                return -1;
9718            }
9719
9720            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
9721
9722            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
9723                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9724                        + " does not have the expected public key; ignoring");
9725                return -1;
9726            }
9727
9728            return pkg.applicationInfo.uid;
9729        }
9730    }
9731
9732    @Override
9733    public void finishPackageInstall(int token) {
9734        enforceSystemOrRoot("Only the system is allowed to finish installs");
9735
9736        if (DEBUG_INSTALL) {
9737            Slog.v(TAG, "BM finishing package install for " + token);
9738        }
9739
9740        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9741        mHandler.sendMessage(msg);
9742    }
9743
9744    /**
9745     * Get the verification agent timeout.
9746     *
9747     * @return verification timeout in milliseconds
9748     */
9749    private long getVerificationTimeout() {
9750        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
9751                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
9752                DEFAULT_VERIFICATION_TIMEOUT);
9753    }
9754
9755    /**
9756     * Get the default verification agent response code.
9757     *
9758     * @return default verification response code
9759     */
9760    private int getDefaultVerificationResponse() {
9761        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9762                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
9763                DEFAULT_VERIFICATION_RESPONSE);
9764    }
9765
9766    /**
9767     * Check whether or not package verification has been enabled.
9768     *
9769     * @return true if verification should be performed
9770     */
9771    private boolean isVerificationEnabled(int userId, int installFlags) {
9772        if (!DEFAULT_VERIFY_ENABLE) {
9773            return false;
9774        }
9775
9776        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
9777
9778        // Check if installing from ADB
9779        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
9780            // Do not run verification in a test harness environment
9781            if (ActivityManager.isRunningInTestHarness()) {
9782                return false;
9783            }
9784            if (ensureVerifyAppsEnabled) {
9785                return true;
9786            }
9787            // Check if the developer does not want package verification for ADB installs
9788            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9789                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
9790                return false;
9791            }
9792        }
9793
9794        if (ensureVerifyAppsEnabled) {
9795            return true;
9796        }
9797
9798        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9799                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9800    }
9801
9802    @Override
9803    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9804            throws RemoteException {
9805        mContext.enforceCallingOrSelfPermission(
9806                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9807                "Only intentfilter verification agents can verify applications");
9808
9809        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9810        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9811                Binder.getCallingUid(), verificationCode, failedDomains);
9812        msg.arg1 = id;
9813        msg.obj = response;
9814        mHandler.sendMessage(msg);
9815    }
9816
9817    @Override
9818    public int getIntentVerificationStatus(String packageName, int userId) {
9819        synchronized (mPackages) {
9820            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
9821        }
9822    }
9823
9824    @Override
9825    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
9826        mContext.enforceCallingOrSelfPermission(
9827                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9828
9829        boolean result = false;
9830        synchronized (mPackages) {
9831            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
9832        }
9833        if (result) {
9834            scheduleWritePackageRestrictionsLocked(userId);
9835        }
9836        return result;
9837    }
9838
9839    @Override
9840    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
9841        synchronized (mPackages) {
9842            return mSettings.getIntentFilterVerificationsLPr(packageName);
9843        }
9844    }
9845
9846    @Override
9847    public List<IntentFilter> getAllIntentFilters(String packageName) {
9848        if (TextUtils.isEmpty(packageName)) {
9849            return Collections.<IntentFilter>emptyList();
9850        }
9851        synchronized (mPackages) {
9852            PackageParser.Package pkg = mPackages.get(packageName);
9853            if (pkg == null || pkg.activities == null) {
9854                return Collections.<IntentFilter>emptyList();
9855            }
9856            final int count = pkg.activities.size();
9857            ArrayList<IntentFilter> result = new ArrayList<>();
9858            for (int n=0; n<count; n++) {
9859                PackageParser.Activity activity = pkg.activities.get(n);
9860                if (activity.intents != null || activity.intents.size() > 0) {
9861                    result.addAll(activity.intents);
9862                }
9863            }
9864            return result;
9865        }
9866    }
9867
9868    @Override
9869    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
9870        mContext.enforceCallingOrSelfPermission(
9871                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9872
9873        synchronized (mPackages) {
9874            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
9875            if (packageName != null) {
9876                result |= updateIntentVerificationStatus(packageName,
9877                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
9878                        UserHandle.myUserId());
9879                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
9880                        packageName, userId);
9881            }
9882            return result;
9883        }
9884    }
9885
9886    @Override
9887    public String getDefaultBrowserPackageName(int userId) {
9888        synchronized (mPackages) {
9889            return mSettings.getDefaultBrowserPackageNameLPw(userId);
9890        }
9891    }
9892
9893    /**
9894     * Get the "allow unknown sources" setting.
9895     *
9896     * @return the current "allow unknown sources" setting
9897     */
9898    private int getUnknownSourcesSettings() {
9899        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9900                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
9901                -1);
9902    }
9903
9904    @Override
9905    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
9906        final int uid = Binder.getCallingUid();
9907        // writer
9908        synchronized (mPackages) {
9909            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
9910            if (targetPackageSetting == null) {
9911                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
9912            }
9913
9914            PackageSetting installerPackageSetting;
9915            if (installerPackageName != null) {
9916                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
9917                if (installerPackageSetting == null) {
9918                    throw new IllegalArgumentException("Unknown installer package: "
9919                            + installerPackageName);
9920                }
9921            } else {
9922                installerPackageSetting = null;
9923            }
9924
9925            Signature[] callerSignature;
9926            Object obj = mSettings.getUserIdLPr(uid);
9927            if (obj != null) {
9928                if (obj instanceof SharedUserSetting) {
9929                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
9930                } else if (obj instanceof PackageSetting) {
9931                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
9932                } else {
9933                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
9934                }
9935            } else {
9936                throw new SecurityException("Unknown calling uid " + uid);
9937            }
9938
9939            // Verify: can't set installerPackageName to a package that is
9940            // not signed with the same cert as the caller.
9941            if (installerPackageSetting != null) {
9942                if (compareSignatures(callerSignature,
9943                        installerPackageSetting.signatures.mSignatures)
9944                        != PackageManager.SIGNATURE_MATCH) {
9945                    throw new SecurityException(
9946                            "Caller does not have same cert as new installer package "
9947                            + installerPackageName);
9948                }
9949            }
9950
9951            // Verify: if target already has an installer package, it must
9952            // be signed with the same cert as the caller.
9953            if (targetPackageSetting.installerPackageName != null) {
9954                PackageSetting setting = mSettings.mPackages.get(
9955                        targetPackageSetting.installerPackageName);
9956                // If the currently set package isn't valid, then it's always
9957                // okay to change it.
9958                if (setting != null) {
9959                    if (compareSignatures(callerSignature,
9960                            setting.signatures.mSignatures)
9961                            != PackageManager.SIGNATURE_MATCH) {
9962                        throw new SecurityException(
9963                                "Caller does not have same cert as old installer package "
9964                                + targetPackageSetting.installerPackageName);
9965                    }
9966                }
9967            }
9968
9969            // Okay!
9970            targetPackageSetting.installerPackageName = installerPackageName;
9971            scheduleWriteSettingsLocked();
9972        }
9973    }
9974
9975    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
9976        // Queue up an async operation since the package installation may take a little while.
9977        mHandler.post(new Runnable() {
9978            public void run() {
9979                mHandler.removeCallbacks(this);
9980                 // Result object to be returned
9981                PackageInstalledInfo res = new PackageInstalledInfo();
9982                res.returnCode = currentStatus;
9983                res.uid = -1;
9984                res.pkg = null;
9985                res.removedInfo = new PackageRemovedInfo();
9986                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
9987                    args.doPreInstall(res.returnCode);
9988                    synchronized (mInstallLock) {
9989                        installPackageLI(args, res);
9990                    }
9991                    args.doPostInstall(res.returnCode, res.uid);
9992                }
9993
9994                // A restore should be performed at this point if (a) the install
9995                // succeeded, (b) the operation is not an update, and (c) the new
9996                // package has not opted out of backup participation.
9997                final boolean update = res.removedInfo.removedPackage != null;
9998                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
9999                boolean doRestore = !update
10000                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
10001
10002                // Set up the post-install work request bookkeeping.  This will be used
10003                // and cleaned up by the post-install event handling regardless of whether
10004                // there's a restore pass performed.  Token values are >= 1.
10005                int token;
10006                if (mNextInstallToken < 0) mNextInstallToken = 1;
10007                token = mNextInstallToken++;
10008
10009                PostInstallData data = new PostInstallData(args, res);
10010                mRunningInstalls.put(token, data);
10011                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10012
10013                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10014                    // Pass responsibility to the Backup Manager.  It will perform a
10015                    // restore if appropriate, then pass responsibility back to the
10016                    // Package Manager to run the post-install observer callbacks
10017                    // and broadcasts.
10018                    IBackupManager bm = IBackupManager.Stub.asInterface(
10019                            ServiceManager.getService(Context.BACKUP_SERVICE));
10020                    if (bm != null) {
10021                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10022                                + " to BM for possible restore");
10023                        try {
10024                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
10025                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10026                            } else {
10027                                doRestore = false;
10028                            }
10029                        } catch (RemoteException e) {
10030                            // can't happen; the backup manager is local
10031                        } catch (Exception e) {
10032                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10033                            doRestore = false;
10034                        }
10035                    } else {
10036                        Slog.e(TAG, "Backup Manager not found!");
10037                        doRestore = false;
10038                    }
10039                }
10040
10041                if (!doRestore) {
10042                    // No restore possible, or the Backup Manager was mysteriously not
10043                    // available -- just fire the post-install work request directly.
10044                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10045                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10046                    mHandler.sendMessage(msg);
10047                }
10048            }
10049        });
10050    }
10051
10052    private abstract class HandlerParams {
10053        private static final int MAX_RETRIES = 4;
10054
10055        /**
10056         * Number of times startCopy() has been attempted and had a non-fatal
10057         * error.
10058         */
10059        private int mRetries = 0;
10060
10061        /** User handle for the user requesting the information or installation. */
10062        private final UserHandle mUser;
10063
10064        HandlerParams(UserHandle user) {
10065            mUser = user;
10066        }
10067
10068        UserHandle getUser() {
10069            return mUser;
10070        }
10071
10072        final boolean startCopy() {
10073            boolean res;
10074            try {
10075                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10076
10077                if (++mRetries > MAX_RETRIES) {
10078                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10079                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10080                    handleServiceError();
10081                    return false;
10082                } else {
10083                    handleStartCopy();
10084                    res = true;
10085                }
10086            } catch (RemoteException e) {
10087                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10088                mHandler.sendEmptyMessage(MCS_RECONNECT);
10089                res = false;
10090            }
10091            handleReturnCode();
10092            return res;
10093        }
10094
10095        final void serviceError() {
10096            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10097            handleServiceError();
10098            handleReturnCode();
10099        }
10100
10101        abstract void handleStartCopy() throws RemoteException;
10102        abstract void handleServiceError();
10103        abstract void handleReturnCode();
10104    }
10105
10106    class MeasureParams extends HandlerParams {
10107        private final PackageStats mStats;
10108        private boolean mSuccess;
10109
10110        private final IPackageStatsObserver mObserver;
10111
10112        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10113            super(new UserHandle(stats.userHandle));
10114            mObserver = observer;
10115            mStats = stats;
10116        }
10117
10118        @Override
10119        public String toString() {
10120            return "MeasureParams{"
10121                + Integer.toHexString(System.identityHashCode(this))
10122                + " " + mStats.packageName + "}";
10123        }
10124
10125        @Override
10126        void handleStartCopy() throws RemoteException {
10127            synchronized (mInstallLock) {
10128                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10129            }
10130
10131            if (mSuccess) {
10132                final boolean mounted;
10133                if (Environment.isExternalStorageEmulated()) {
10134                    mounted = true;
10135                } else {
10136                    final String status = Environment.getExternalStorageState();
10137                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10138                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10139                }
10140
10141                if (mounted) {
10142                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10143
10144                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10145                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10146
10147                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10148                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10149
10150                    // Always subtract cache size, since it's a subdirectory
10151                    mStats.externalDataSize -= mStats.externalCacheSize;
10152
10153                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10154                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10155
10156                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10157                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10158                }
10159            }
10160        }
10161
10162        @Override
10163        void handleReturnCode() {
10164            if (mObserver != null) {
10165                try {
10166                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10167                } catch (RemoteException e) {
10168                    Slog.i(TAG, "Observer no longer exists.");
10169                }
10170            }
10171        }
10172
10173        @Override
10174        void handleServiceError() {
10175            Slog.e(TAG, "Could not measure application " + mStats.packageName
10176                            + " external storage");
10177        }
10178    }
10179
10180    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10181            throws RemoteException {
10182        long result = 0;
10183        for (File path : paths) {
10184            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10185        }
10186        return result;
10187    }
10188
10189    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10190        for (File path : paths) {
10191            try {
10192                mcs.clearDirectory(path.getAbsolutePath());
10193            } catch (RemoteException e) {
10194            }
10195        }
10196    }
10197
10198    static class OriginInfo {
10199        /**
10200         * Location where install is coming from, before it has been
10201         * copied/renamed into place. This could be a single monolithic APK
10202         * file, or a cluster directory. This location may be untrusted.
10203         */
10204        final File file;
10205        final String cid;
10206
10207        /**
10208         * Flag indicating that {@link #file} or {@link #cid} has already been
10209         * staged, meaning downstream users don't need to defensively copy the
10210         * contents.
10211         */
10212        final boolean staged;
10213
10214        /**
10215         * Flag indicating that {@link #file} or {@link #cid} is an already
10216         * installed app that is being moved.
10217         */
10218        final boolean existing;
10219
10220        final String resolvedPath;
10221        final File resolvedFile;
10222
10223        static OriginInfo fromNothing() {
10224            return new OriginInfo(null, null, false, false);
10225        }
10226
10227        static OriginInfo fromUntrustedFile(File file) {
10228            return new OriginInfo(file, null, false, false);
10229        }
10230
10231        static OriginInfo fromExistingFile(File file) {
10232            return new OriginInfo(file, null, false, true);
10233        }
10234
10235        static OriginInfo fromStagedFile(File file) {
10236            return new OriginInfo(file, null, true, false);
10237        }
10238
10239        static OriginInfo fromStagedContainer(String cid) {
10240            return new OriginInfo(null, cid, true, false);
10241        }
10242
10243        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10244            this.file = file;
10245            this.cid = cid;
10246            this.staged = staged;
10247            this.existing = existing;
10248
10249            if (cid != null) {
10250                resolvedPath = PackageHelper.getSdDir(cid);
10251                resolvedFile = new File(resolvedPath);
10252            } else if (file != null) {
10253                resolvedPath = file.getAbsolutePath();
10254                resolvedFile = file;
10255            } else {
10256                resolvedPath = null;
10257                resolvedFile = null;
10258            }
10259        }
10260    }
10261
10262    class MoveInfo {
10263        final int moveId;
10264        final String fromUuid;
10265        final String toUuid;
10266        final String packageName;
10267        final String dataAppName;
10268        final int appId;
10269        final String seinfo;
10270
10271        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10272                String dataAppName, int appId, String seinfo) {
10273            this.moveId = moveId;
10274            this.fromUuid = fromUuid;
10275            this.toUuid = toUuid;
10276            this.packageName = packageName;
10277            this.dataAppName = dataAppName;
10278            this.appId = appId;
10279            this.seinfo = seinfo;
10280        }
10281    }
10282
10283    class InstallParams extends HandlerParams {
10284        final OriginInfo origin;
10285        final MoveInfo move;
10286        final IPackageInstallObserver2 observer;
10287        int installFlags;
10288        final String installerPackageName;
10289        final String volumeUuid;
10290        final VerificationParams verificationParams;
10291        private InstallArgs mArgs;
10292        private int mRet;
10293        final String packageAbiOverride;
10294
10295        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10296                int installFlags, String installerPackageName, String volumeUuid,
10297                VerificationParams verificationParams, UserHandle user, String packageAbiOverride) {
10298            super(user);
10299            this.origin = origin;
10300            this.move = move;
10301            this.observer = observer;
10302            this.installFlags = installFlags;
10303            this.installerPackageName = installerPackageName;
10304            this.volumeUuid = volumeUuid;
10305            this.verificationParams = verificationParams;
10306            this.packageAbiOverride = packageAbiOverride;
10307        }
10308
10309        @Override
10310        public String toString() {
10311            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10312                    + " file=" + origin.file + " cid=" + origin.cid + "}";
10313        }
10314
10315        public ManifestDigest getManifestDigest() {
10316            if (verificationParams == null) {
10317                return null;
10318            }
10319            return verificationParams.getManifestDigest();
10320        }
10321
10322        private int installLocationPolicy(PackageInfoLite pkgLite) {
10323            String packageName = pkgLite.packageName;
10324            int installLocation = pkgLite.installLocation;
10325            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10326            // reader
10327            synchronized (mPackages) {
10328                PackageParser.Package pkg = mPackages.get(packageName);
10329                if (pkg != null) {
10330                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10331                        // Check for downgrading.
10332                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10333                            try {
10334                                checkDowngrade(pkg, pkgLite);
10335                            } catch (PackageManagerException e) {
10336                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10337                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
10338                            }
10339                        }
10340                        // Check for updated system application.
10341                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10342                            if (onSd) {
10343                                Slog.w(TAG, "Cannot install update to system app on sdcard");
10344                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
10345                            }
10346                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10347                        } else {
10348                            if (onSd) {
10349                                // Install flag overrides everything.
10350                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10351                            }
10352                            // If current upgrade specifies particular preference
10353                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
10354                                // Application explicitly specified internal.
10355                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10356                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
10357                                // App explictly prefers external. Let policy decide
10358                            } else {
10359                                // Prefer previous location
10360                                if (isExternal(pkg)) {
10361                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10362                                }
10363                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10364                            }
10365                        }
10366                    } else {
10367                        // Invalid install. Return error code
10368                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
10369                    }
10370                }
10371            }
10372            // All the special cases have been taken care of.
10373            // Return result based on recommended install location.
10374            if (onSd) {
10375                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10376            }
10377            return pkgLite.recommendedInstallLocation;
10378        }
10379
10380        /*
10381         * Invoke remote method to get package information and install
10382         * location values. Override install location based on default
10383         * policy if needed and then create install arguments based
10384         * on the install location.
10385         */
10386        public void handleStartCopy() throws RemoteException {
10387            int ret = PackageManager.INSTALL_SUCCEEDED;
10388
10389            // If we're already staged, we've firmly committed to an install location
10390            if (origin.staged) {
10391                if (origin.file != null) {
10392                    installFlags |= PackageManager.INSTALL_INTERNAL;
10393                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10394                } else if (origin.cid != null) {
10395                    installFlags |= PackageManager.INSTALL_EXTERNAL;
10396                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
10397                } else {
10398                    throw new IllegalStateException("Invalid stage location");
10399                }
10400            }
10401
10402            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10403            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
10404
10405            PackageInfoLite pkgLite = null;
10406
10407            if (onInt && onSd) {
10408                // Check if both bits are set.
10409                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
10410                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10411            } else {
10412                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
10413                        packageAbiOverride);
10414
10415                /*
10416                 * If we have too little free space, try to free cache
10417                 * before giving up.
10418                 */
10419                if (!origin.staged && pkgLite.recommendedInstallLocation
10420                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10421                    // TODO: focus freeing disk space on the target device
10422                    final StorageManager storage = StorageManager.from(mContext);
10423                    final long lowThreshold = storage.getStorageLowBytes(
10424                            Environment.getDataDirectory());
10425
10426                    final long sizeBytes = mContainerService.calculateInstalledSize(
10427                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
10428
10429                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
10430                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
10431                                installFlags, packageAbiOverride);
10432                    }
10433
10434                    /*
10435                     * The cache free must have deleted the file we
10436                     * downloaded to install.
10437                     *
10438                     * TODO: fix the "freeCache" call to not delete
10439                     *       the file we care about.
10440                     */
10441                    if (pkgLite.recommendedInstallLocation
10442                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10443                        pkgLite.recommendedInstallLocation
10444                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
10445                    }
10446                }
10447            }
10448
10449            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10450                int loc = pkgLite.recommendedInstallLocation;
10451                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
10452                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10453                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
10454                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
10455                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10456                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10457                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
10458                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
10459                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10460                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
10461                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
10462                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
10463                } else {
10464                    // Override with defaults if needed.
10465                    loc = installLocationPolicy(pkgLite);
10466                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
10467                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
10468                    } else if (!onSd && !onInt) {
10469                        // Override install location with flags
10470                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
10471                            // Set the flag to install on external media.
10472                            installFlags |= PackageManager.INSTALL_EXTERNAL;
10473                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
10474                        } else {
10475                            // Make sure the flag for installing on external
10476                            // media is unset
10477                            installFlags |= PackageManager.INSTALL_INTERNAL;
10478                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10479                        }
10480                    }
10481                }
10482            }
10483
10484            final InstallArgs args = createInstallArgs(this);
10485            mArgs = args;
10486
10487            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10488                 /*
10489                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
10490                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
10491                 */
10492                int userIdentifier = getUser().getIdentifier();
10493                if (userIdentifier == UserHandle.USER_ALL
10494                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
10495                    userIdentifier = UserHandle.USER_OWNER;
10496                }
10497
10498                /*
10499                 * Determine if we have any installed package verifiers. If we
10500                 * do, then we'll defer to them to verify the packages.
10501                 */
10502                final int requiredUid = mRequiredVerifierPackage == null ? -1
10503                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
10504                if (!origin.existing && requiredUid != -1
10505                        && isVerificationEnabled(userIdentifier, installFlags)) {
10506                    final Intent verification = new Intent(
10507                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
10508                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10509                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
10510                            PACKAGE_MIME_TYPE);
10511                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10512
10513                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
10514                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10515                            0 /* TODO: Which userId? */);
10516
10517                    if (DEBUG_VERIFY) {
10518                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10519                                + verification.toString() + " with " + pkgLite.verifiers.length
10520                                + " optional verifiers");
10521                    }
10522
10523                    final int verificationId = mPendingVerificationToken++;
10524
10525                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10526
10527                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10528                            installerPackageName);
10529
10530                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10531                            installFlags);
10532
10533                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10534                            pkgLite.packageName);
10535
10536                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10537                            pkgLite.versionCode);
10538
10539                    if (verificationParams != null) {
10540                        if (verificationParams.getVerificationURI() != null) {
10541                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10542                                 verificationParams.getVerificationURI());
10543                        }
10544                        if (verificationParams.getOriginatingURI() != null) {
10545                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10546                                  verificationParams.getOriginatingURI());
10547                        }
10548                        if (verificationParams.getReferrer() != null) {
10549                            verification.putExtra(Intent.EXTRA_REFERRER,
10550                                  verificationParams.getReferrer());
10551                        }
10552                        if (verificationParams.getOriginatingUid() >= 0) {
10553                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
10554                                  verificationParams.getOriginatingUid());
10555                        }
10556                        if (verificationParams.getInstallerUid() >= 0) {
10557                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
10558                                  verificationParams.getInstallerUid());
10559                        }
10560                    }
10561
10562                    final PackageVerificationState verificationState = new PackageVerificationState(
10563                            requiredUid, args);
10564
10565                    mPendingVerification.append(verificationId, verificationState);
10566
10567                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
10568                            receivers, verificationState);
10569
10570                    /*
10571                     * If any sufficient verifiers were listed in the package
10572                     * manifest, attempt to ask them.
10573                     */
10574                    if (sufficientVerifiers != null) {
10575                        final int N = sufficientVerifiers.size();
10576                        if (N == 0) {
10577                            Slog.i(TAG, "Additional verifiers required, but none installed.");
10578                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
10579                        } else {
10580                            for (int i = 0; i < N; i++) {
10581                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
10582
10583                                final Intent sufficientIntent = new Intent(verification);
10584                                sufficientIntent.setComponent(verifierComponent);
10585
10586                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
10587                            }
10588                        }
10589                    }
10590
10591                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
10592                            mRequiredVerifierPackage, receivers);
10593                    if (ret == PackageManager.INSTALL_SUCCEEDED
10594                            && mRequiredVerifierPackage != null) {
10595                        /*
10596                         * Send the intent to the required verification agent,
10597                         * but only start the verification timeout after the
10598                         * target BroadcastReceivers have run.
10599                         */
10600                        verification.setComponent(requiredVerifierComponent);
10601                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
10602                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10603                                new BroadcastReceiver() {
10604                                    @Override
10605                                    public void onReceive(Context context, Intent intent) {
10606                                        final Message msg = mHandler
10607                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
10608                                        msg.arg1 = verificationId;
10609                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
10610                                    }
10611                                }, null, 0, null, null);
10612
10613                        /*
10614                         * We don't want the copy to proceed until verification
10615                         * succeeds, so null out this field.
10616                         */
10617                        mArgs = null;
10618                    }
10619                } else {
10620                    /*
10621                     * No package verification is enabled, so immediately start
10622                     * the remote call to initiate copy using temporary file.
10623                     */
10624                    ret = args.copyApk(mContainerService, true);
10625                }
10626            }
10627
10628            mRet = ret;
10629        }
10630
10631        @Override
10632        void handleReturnCode() {
10633            // If mArgs is null, then MCS couldn't be reached. When it
10634            // reconnects, it will try again to install. At that point, this
10635            // will succeed.
10636            if (mArgs != null) {
10637                processPendingInstall(mArgs, mRet);
10638            }
10639        }
10640
10641        @Override
10642        void handleServiceError() {
10643            mArgs = createInstallArgs(this);
10644            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10645        }
10646
10647        public boolean isForwardLocked() {
10648            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10649        }
10650    }
10651
10652    /**
10653     * Used during creation of InstallArgs
10654     *
10655     * @param installFlags package installation flags
10656     * @return true if should be installed on external storage
10657     */
10658    private static boolean installOnExternalAsec(int installFlags) {
10659        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
10660            return false;
10661        }
10662        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
10663            return true;
10664        }
10665        return false;
10666    }
10667
10668    /**
10669     * Used during creation of InstallArgs
10670     *
10671     * @param installFlags package installation flags
10672     * @return true if should be installed as forward locked
10673     */
10674    private static boolean installForwardLocked(int installFlags) {
10675        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10676    }
10677
10678    private InstallArgs createInstallArgs(InstallParams params) {
10679        if (params.move != null) {
10680            return new MoveInstallArgs(params);
10681        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
10682            return new AsecInstallArgs(params);
10683        } else {
10684            return new FileInstallArgs(params);
10685        }
10686    }
10687
10688    /**
10689     * Create args that describe an existing installed package. Typically used
10690     * when cleaning up old installs, or used as a move source.
10691     */
10692    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
10693            String resourcePath, String[] instructionSets) {
10694        final boolean isInAsec;
10695        if (installOnExternalAsec(installFlags)) {
10696            /* Apps on SD card are always in ASEC containers. */
10697            isInAsec = true;
10698        } else if (installForwardLocked(installFlags)
10699                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
10700            /*
10701             * Forward-locked apps are only in ASEC containers if they're the
10702             * new style
10703             */
10704            isInAsec = true;
10705        } else {
10706            isInAsec = false;
10707        }
10708
10709        if (isInAsec) {
10710            return new AsecInstallArgs(codePath, instructionSets,
10711                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
10712        } else {
10713            return new FileInstallArgs(codePath, resourcePath, instructionSets);
10714        }
10715    }
10716
10717    static abstract class InstallArgs {
10718        /** @see InstallParams#origin */
10719        final OriginInfo origin;
10720        /** @see InstallParams#move */
10721        final MoveInfo move;
10722
10723        final IPackageInstallObserver2 observer;
10724        // Always refers to PackageManager flags only
10725        final int installFlags;
10726        final String installerPackageName;
10727        final String volumeUuid;
10728        final ManifestDigest manifestDigest;
10729        final UserHandle user;
10730        final String abiOverride;
10731
10732        // The list of instruction sets supported by this app. This is currently
10733        // only used during the rmdex() phase to clean up resources. We can get rid of this
10734        // if we move dex files under the common app path.
10735        /* nullable */ String[] instructionSets;
10736
10737        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10738                int installFlags, String installerPackageName, String volumeUuid,
10739                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
10740                String abiOverride) {
10741            this.origin = origin;
10742            this.move = move;
10743            this.installFlags = installFlags;
10744            this.observer = observer;
10745            this.installerPackageName = installerPackageName;
10746            this.volumeUuid = volumeUuid;
10747            this.manifestDigest = manifestDigest;
10748            this.user = user;
10749            this.instructionSets = instructionSets;
10750            this.abiOverride = abiOverride;
10751        }
10752
10753        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
10754        abstract int doPreInstall(int status);
10755
10756        /**
10757         * Rename package into final resting place. All paths on the given
10758         * scanned package should be updated to reflect the rename.
10759         */
10760        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
10761        abstract int doPostInstall(int status, int uid);
10762
10763        /** @see PackageSettingBase#codePathString */
10764        abstract String getCodePath();
10765        /** @see PackageSettingBase#resourcePathString */
10766        abstract String getResourcePath();
10767
10768        // Need installer lock especially for dex file removal.
10769        abstract void cleanUpResourcesLI();
10770        abstract boolean doPostDeleteLI(boolean delete);
10771
10772        /**
10773         * Called before the source arguments are copied. This is used mostly
10774         * for MoveParams when it needs to read the source file to put it in the
10775         * destination.
10776         */
10777        int doPreCopy() {
10778            return PackageManager.INSTALL_SUCCEEDED;
10779        }
10780
10781        /**
10782         * Called after the source arguments are copied. This is used mostly for
10783         * MoveParams when it needs to read the source file to put it in the
10784         * destination.
10785         *
10786         * @return
10787         */
10788        int doPostCopy(int uid) {
10789            return PackageManager.INSTALL_SUCCEEDED;
10790        }
10791
10792        protected boolean isFwdLocked() {
10793            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10794        }
10795
10796        protected boolean isExternalAsec() {
10797            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10798        }
10799
10800        UserHandle getUser() {
10801            return user;
10802        }
10803    }
10804
10805    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
10806        if (!allCodePaths.isEmpty()) {
10807            if (instructionSets == null) {
10808                throw new IllegalStateException("instructionSet == null");
10809            }
10810            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
10811            for (String codePath : allCodePaths) {
10812                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
10813                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
10814                    if (retCode < 0) {
10815                        Slog.w(TAG, "Couldn't remove dex file for package: "
10816                                + " at location " + codePath + ", retcode=" + retCode);
10817                        // we don't consider this to be a failure of the core package deletion
10818                    }
10819                }
10820            }
10821        }
10822    }
10823
10824    /**
10825     * Logic to handle installation of non-ASEC applications, including copying
10826     * and renaming logic.
10827     */
10828    class FileInstallArgs extends InstallArgs {
10829        private File codeFile;
10830        private File resourceFile;
10831
10832        // Example topology:
10833        // /data/app/com.example/base.apk
10834        // /data/app/com.example/split_foo.apk
10835        // /data/app/com.example/lib/arm/libfoo.so
10836        // /data/app/com.example/lib/arm64/libfoo.so
10837        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
10838
10839        /** New install */
10840        FileInstallArgs(InstallParams params) {
10841            super(params.origin, params.move, params.observer, params.installFlags,
10842                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10843                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10844            if (isFwdLocked()) {
10845                throw new IllegalArgumentException("Forward locking only supported in ASEC");
10846            }
10847        }
10848
10849        /** Existing install */
10850        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
10851            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
10852                    null);
10853            this.codeFile = (codePath != null) ? new File(codePath) : null;
10854            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
10855        }
10856
10857        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10858            if (origin.staged) {
10859                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
10860                codeFile = origin.file;
10861                resourceFile = origin.file;
10862                return PackageManager.INSTALL_SUCCEEDED;
10863            }
10864
10865            try {
10866                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
10867                codeFile = tempDir;
10868                resourceFile = tempDir;
10869            } catch (IOException e) {
10870                Slog.w(TAG, "Failed to create copy file: " + e);
10871                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10872            }
10873
10874            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
10875                @Override
10876                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
10877                    if (!FileUtils.isValidExtFilename(name)) {
10878                        throw new IllegalArgumentException("Invalid filename: " + name);
10879                    }
10880                    try {
10881                        final File file = new File(codeFile, name);
10882                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
10883                                O_RDWR | O_CREAT, 0644);
10884                        Os.chmod(file.getAbsolutePath(), 0644);
10885                        return new ParcelFileDescriptor(fd);
10886                    } catch (ErrnoException e) {
10887                        throw new RemoteException("Failed to open: " + e.getMessage());
10888                    }
10889                }
10890            };
10891
10892            int ret = PackageManager.INSTALL_SUCCEEDED;
10893            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
10894            if (ret != PackageManager.INSTALL_SUCCEEDED) {
10895                Slog.e(TAG, "Failed to copy package");
10896                return ret;
10897            }
10898
10899            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
10900            NativeLibraryHelper.Handle handle = null;
10901            try {
10902                handle = NativeLibraryHelper.Handle.create(codeFile);
10903                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
10904                        abiOverride);
10905            } catch (IOException e) {
10906                Slog.e(TAG, "Copying native libraries failed", e);
10907                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10908            } finally {
10909                IoUtils.closeQuietly(handle);
10910            }
10911
10912            return ret;
10913        }
10914
10915        int doPreInstall(int status) {
10916            if (status != PackageManager.INSTALL_SUCCEEDED) {
10917                cleanUp();
10918            }
10919            return status;
10920        }
10921
10922        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10923            if (status != PackageManager.INSTALL_SUCCEEDED) {
10924                cleanUp();
10925                return false;
10926            }
10927
10928            final File targetDir = codeFile.getParentFile();
10929            final File beforeCodeFile = codeFile;
10930            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
10931
10932            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
10933            try {
10934                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
10935            } catch (ErrnoException e) {
10936                Slog.w(TAG, "Failed to rename", e);
10937                return false;
10938            }
10939
10940            if (!SELinux.restoreconRecursive(afterCodeFile)) {
10941                Slog.w(TAG, "Failed to restorecon");
10942                return false;
10943            }
10944
10945            // Reflect the rename internally
10946            codeFile = afterCodeFile;
10947            resourceFile = afterCodeFile;
10948
10949            // Reflect the rename in scanned details
10950            pkg.codePath = afterCodeFile.getAbsolutePath();
10951            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10952                    pkg.baseCodePath);
10953            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10954                    pkg.splitCodePaths);
10955
10956            // Reflect the rename in app info
10957            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10958            pkg.applicationInfo.setCodePath(pkg.codePath);
10959            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10960            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10961            pkg.applicationInfo.setResourcePath(pkg.codePath);
10962            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10963            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10964
10965            return true;
10966        }
10967
10968        int doPostInstall(int status, int uid) {
10969            if (status != PackageManager.INSTALL_SUCCEEDED) {
10970                cleanUp();
10971            }
10972            return status;
10973        }
10974
10975        @Override
10976        String getCodePath() {
10977            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
10978        }
10979
10980        @Override
10981        String getResourcePath() {
10982            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
10983        }
10984
10985        private boolean cleanUp() {
10986            if (codeFile == null || !codeFile.exists()) {
10987                return false;
10988            }
10989
10990            if (codeFile.isDirectory()) {
10991                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
10992            } else {
10993                codeFile.delete();
10994            }
10995
10996            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
10997                resourceFile.delete();
10998            }
10999
11000            return true;
11001        }
11002
11003        void cleanUpResourcesLI() {
11004            // Try enumerating all code paths before deleting
11005            List<String> allCodePaths = Collections.EMPTY_LIST;
11006            if (codeFile != null && codeFile.exists()) {
11007                try {
11008                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11009                    allCodePaths = pkg.getAllCodePaths();
11010                } catch (PackageParserException e) {
11011                    // Ignored; we tried our best
11012                }
11013            }
11014
11015            cleanUp();
11016            removeDexFiles(allCodePaths, instructionSets);
11017        }
11018
11019        boolean doPostDeleteLI(boolean delete) {
11020            // XXX err, shouldn't we respect the delete flag?
11021            cleanUpResourcesLI();
11022            return true;
11023        }
11024    }
11025
11026    private boolean isAsecExternal(String cid) {
11027        final String asecPath = PackageHelper.getSdFilesystem(cid);
11028        return !asecPath.startsWith(mAsecInternalPath);
11029    }
11030
11031    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11032            PackageManagerException {
11033        if (copyRet < 0) {
11034            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11035                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11036                throw new PackageManagerException(copyRet, message);
11037            }
11038        }
11039    }
11040
11041    /**
11042     * Extract the MountService "container ID" from the full code path of an
11043     * .apk.
11044     */
11045    static String cidFromCodePath(String fullCodePath) {
11046        int eidx = fullCodePath.lastIndexOf("/");
11047        String subStr1 = fullCodePath.substring(0, eidx);
11048        int sidx = subStr1.lastIndexOf("/");
11049        return subStr1.substring(sidx+1, eidx);
11050    }
11051
11052    /**
11053     * Logic to handle installation of ASEC applications, including copying and
11054     * renaming logic.
11055     */
11056    class AsecInstallArgs extends InstallArgs {
11057        static final String RES_FILE_NAME = "pkg.apk";
11058        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11059
11060        String cid;
11061        String packagePath;
11062        String resourcePath;
11063
11064        /** New install */
11065        AsecInstallArgs(InstallParams params) {
11066            super(params.origin, params.move, params.observer, params.installFlags,
11067                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11068                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
11069        }
11070
11071        /** Existing install */
11072        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11073                        boolean isExternal, boolean isForwardLocked) {
11074            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11075                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11076                    instructionSets, null);
11077            // Hackily pretend we're still looking at a full code path
11078            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11079                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11080            }
11081
11082            // Extract cid from fullCodePath
11083            int eidx = fullCodePath.lastIndexOf("/");
11084            String subStr1 = fullCodePath.substring(0, eidx);
11085            int sidx = subStr1.lastIndexOf("/");
11086            cid = subStr1.substring(sidx+1, eidx);
11087            setMountPath(subStr1);
11088        }
11089
11090        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11091            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11092                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11093                    instructionSets, null);
11094            this.cid = cid;
11095            setMountPath(PackageHelper.getSdDir(cid));
11096        }
11097
11098        void createCopyFile() {
11099            cid = mInstallerService.allocateExternalStageCidLegacy();
11100        }
11101
11102        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11103            if (origin.staged) {
11104                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11105                cid = origin.cid;
11106                setMountPath(PackageHelper.getSdDir(cid));
11107                return PackageManager.INSTALL_SUCCEEDED;
11108            }
11109
11110            if (temp) {
11111                createCopyFile();
11112            } else {
11113                /*
11114                 * Pre-emptively destroy the container since it's destroyed if
11115                 * copying fails due to it existing anyway.
11116                 */
11117                PackageHelper.destroySdDir(cid);
11118            }
11119
11120            final String newMountPath = imcs.copyPackageToContainer(
11121                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11122                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11123
11124            if (newMountPath != null) {
11125                setMountPath(newMountPath);
11126                return PackageManager.INSTALL_SUCCEEDED;
11127            } else {
11128                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11129            }
11130        }
11131
11132        @Override
11133        String getCodePath() {
11134            return packagePath;
11135        }
11136
11137        @Override
11138        String getResourcePath() {
11139            return resourcePath;
11140        }
11141
11142        int doPreInstall(int status) {
11143            if (status != PackageManager.INSTALL_SUCCEEDED) {
11144                // Destroy container
11145                PackageHelper.destroySdDir(cid);
11146            } else {
11147                boolean mounted = PackageHelper.isContainerMounted(cid);
11148                if (!mounted) {
11149                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11150                            Process.SYSTEM_UID);
11151                    if (newMountPath != null) {
11152                        setMountPath(newMountPath);
11153                    } else {
11154                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11155                    }
11156                }
11157            }
11158            return status;
11159        }
11160
11161        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11162            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11163            String newMountPath = null;
11164            if (PackageHelper.isContainerMounted(cid)) {
11165                // Unmount the container
11166                if (!PackageHelper.unMountSdDir(cid)) {
11167                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11168                    return false;
11169                }
11170            }
11171            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11172                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11173                        " which might be stale. Will try to clean up.");
11174                // Clean up the stale container and proceed to recreate.
11175                if (!PackageHelper.destroySdDir(newCacheId)) {
11176                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11177                    return false;
11178                }
11179                // Successfully cleaned up stale container. Try to rename again.
11180                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11181                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11182                            + " inspite of cleaning it up.");
11183                    return false;
11184                }
11185            }
11186            if (!PackageHelper.isContainerMounted(newCacheId)) {
11187                Slog.w(TAG, "Mounting container " + newCacheId);
11188                newMountPath = PackageHelper.mountSdDir(newCacheId,
11189                        getEncryptKey(), Process.SYSTEM_UID);
11190            } else {
11191                newMountPath = PackageHelper.getSdDir(newCacheId);
11192            }
11193            if (newMountPath == null) {
11194                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11195                return false;
11196            }
11197            Log.i(TAG, "Succesfully renamed " + cid +
11198                    " to " + newCacheId +
11199                    " at new path: " + newMountPath);
11200            cid = newCacheId;
11201
11202            final File beforeCodeFile = new File(packagePath);
11203            setMountPath(newMountPath);
11204            final File afterCodeFile = new File(packagePath);
11205
11206            // Reflect the rename in scanned details
11207            pkg.codePath = afterCodeFile.getAbsolutePath();
11208            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11209                    pkg.baseCodePath);
11210            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11211                    pkg.splitCodePaths);
11212
11213            // Reflect the rename in app info
11214            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11215            pkg.applicationInfo.setCodePath(pkg.codePath);
11216            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11217            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11218            pkg.applicationInfo.setResourcePath(pkg.codePath);
11219            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11220            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11221
11222            return true;
11223        }
11224
11225        private void setMountPath(String mountPath) {
11226            final File mountFile = new File(mountPath);
11227
11228            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11229            if (monolithicFile.exists()) {
11230                packagePath = monolithicFile.getAbsolutePath();
11231                if (isFwdLocked()) {
11232                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11233                } else {
11234                    resourcePath = packagePath;
11235                }
11236            } else {
11237                packagePath = mountFile.getAbsolutePath();
11238                resourcePath = packagePath;
11239            }
11240        }
11241
11242        int doPostInstall(int status, int uid) {
11243            if (status != PackageManager.INSTALL_SUCCEEDED) {
11244                cleanUp();
11245            } else {
11246                final int groupOwner;
11247                final String protectedFile;
11248                if (isFwdLocked()) {
11249                    groupOwner = UserHandle.getSharedAppGid(uid);
11250                    protectedFile = RES_FILE_NAME;
11251                } else {
11252                    groupOwner = -1;
11253                    protectedFile = null;
11254                }
11255
11256                if (uid < Process.FIRST_APPLICATION_UID
11257                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11258                    Slog.e(TAG, "Failed to finalize " + cid);
11259                    PackageHelper.destroySdDir(cid);
11260                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11261                }
11262
11263                boolean mounted = PackageHelper.isContainerMounted(cid);
11264                if (!mounted) {
11265                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11266                }
11267            }
11268            return status;
11269        }
11270
11271        private void cleanUp() {
11272            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11273
11274            // Destroy secure container
11275            PackageHelper.destroySdDir(cid);
11276        }
11277
11278        private List<String> getAllCodePaths() {
11279            final File codeFile = new File(getCodePath());
11280            if (codeFile != null && codeFile.exists()) {
11281                try {
11282                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11283                    return pkg.getAllCodePaths();
11284                } catch (PackageParserException e) {
11285                    // Ignored; we tried our best
11286                }
11287            }
11288            return Collections.EMPTY_LIST;
11289        }
11290
11291        void cleanUpResourcesLI() {
11292            // Enumerate all code paths before deleting
11293            cleanUpResourcesLI(getAllCodePaths());
11294        }
11295
11296        private void cleanUpResourcesLI(List<String> allCodePaths) {
11297            cleanUp();
11298            removeDexFiles(allCodePaths, instructionSets);
11299        }
11300
11301        String getPackageName() {
11302            return getAsecPackageName(cid);
11303        }
11304
11305        boolean doPostDeleteLI(boolean delete) {
11306            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
11307            final List<String> allCodePaths = getAllCodePaths();
11308            boolean mounted = PackageHelper.isContainerMounted(cid);
11309            if (mounted) {
11310                // Unmount first
11311                if (PackageHelper.unMountSdDir(cid)) {
11312                    mounted = false;
11313                }
11314            }
11315            if (!mounted && delete) {
11316                cleanUpResourcesLI(allCodePaths);
11317            }
11318            return !mounted;
11319        }
11320
11321        @Override
11322        int doPreCopy() {
11323            if (isFwdLocked()) {
11324                if (!PackageHelper.fixSdPermissions(cid,
11325                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
11326                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11327                }
11328            }
11329
11330            return PackageManager.INSTALL_SUCCEEDED;
11331        }
11332
11333        @Override
11334        int doPostCopy(int uid) {
11335            if (isFwdLocked()) {
11336                if (uid < Process.FIRST_APPLICATION_UID
11337                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
11338                                RES_FILE_NAME)) {
11339                    Slog.e(TAG, "Failed to finalize " + cid);
11340                    PackageHelper.destroySdDir(cid);
11341                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11342                }
11343            }
11344
11345            return PackageManager.INSTALL_SUCCEEDED;
11346        }
11347    }
11348
11349    /**
11350     * Logic to handle movement of existing installed applications.
11351     */
11352    class MoveInstallArgs extends InstallArgs {
11353        private File codeFile;
11354        private File resourceFile;
11355
11356        /** New install */
11357        MoveInstallArgs(InstallParams params) {
11358            super(params.origin, params.move, params.observer, params.installFlags,
11359                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11360                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
11361        }
11362
11363        int copyApk(IMediaContainerService imcs, boolean temp) {
11364            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
11365                    + move.fromUuid + " to " + move.toUuid);
11366            synchronized (mInstaller) {
11367                if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName,
11368                        move.dataAppName, move.appId, move.seinfo) != 0) {
11369                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11370                }
11371            }
11372
11373            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
11374            resourceFile = codeFile;
11375            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
11376
11377            return PackageManager.INSTALL_SUCCEEDED;
11378        }
11379
11380        int doPreInstall(int status) {
11381            if (status != PackageManager.INSTALL_SUCCEEDED) {
11382                cleanUp(move.toUuid);
11383            }
11384            return status;
11385        }
11386
11387        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11388            if (status != PackageManager.INSTALL_SUCCEEDED) {
11389                cleanUp(move.toUuid);
11390                return false;
11391            }
11392
11393            // Reflect the move in app info
11394            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11395            pkg.applicationInfo.setCodePath(pkg.codePath);
11396            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11397            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11398            pkg.applicationInfo.setResourcePath(pkg.codePath);
11399            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11400            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11401
11402            return true;
11403        }
11404
11405        int doPostInstall(int status, int uid) {
11406            if (status == PackageManager.INSTALL_SUCCEEDED) {
11407                cleanUp(move.fromUuid);
11408            } else {
11409                cleanUp(move.toUuid);
11410            }
11411            return status;
11412        }
11413
11414        @Override
11415        String getCodePath() {
11416            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11417        }
11418
11419        @Override
11420        String getResourcePath() {
11421            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11422        }
11423
11424        private boolean cleanUp(String volumeUuid) {
11425            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
11426                    move.dataAppName);
11427            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
11428            synchronized (mInstallLock) {
11429                // Clean up both app data and code
11430                removeDataDirsLI(volumeUuid, move.packageName);
11431                if (codeFile.isDirectory()) {
11432                    mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11433                } else {
11434                    codeFile.delete();
11435                }
11436            }
11437            return true;
11438        }
11439
11440        void cleanUpResourcesLI() {
11441            throw new UnsupportedOperationException();
11442        }
11443
11444        boolean doPostDeleteLI(boolean delete) {
11445            throw new UnsupportedOperationException();
11446        }
11447    }
11448
11449    static String getAsecPackageName(String packageCid) {
11450        int idx = packageCid.lastIndexOf("-");
11451        if (idx == -1) {
11452            return packageCid;
11453        }
11454        return packageCid.substring(0, idx);
11455    }
11456
11457    // Utility method used to create code paths based on package name and available index.
11458    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
11459        String idxStr = "";
11460        int idx = 1;
11461        // Fall back to default value of idx=1 if prefix is not
11462        // part of oldCodePath
11463        if (oldCodePath != null) {
11464            String subStr = oldCodePath;
11465            // Drop the suffix right away
11466            if (suffix != null && subStr.endsWith(suffix)) {
11467                subStr = subStr.substring(0, subStr.length() - suffix.length());
11468            }
11469            // If oldCodePath already contains prefix find out the
11470            // ending index to either increment or decrement.
11471            int sidx = subStr.lastIndexOf(prefix);
11472            if (sidx != -1) {
11473                subStr = subStr.substring(sidx + prefix.length());
11474                if (subStr != null) {
11475                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
11476                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
11477                    }
11478                    try {
11479                        idx = Integer.parseInt(subStr);
11480                        if (idx <= 1) {
11481                            idx++;
11482                        } else {
11483                            idx--;
11484                        }
11485                    } catch(NumberFormatException e) {
11486                    }
11487                }
11488            }
11489        }
11490        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
11491        return prefix + idxStr;
11492    }
11493
11494    private File getNextCodePath(File targetDir, String packageName) {
11495        int suffix = 1;
11496        File result;
11497        do {
11498            result = new File(targetDir, packageName + "-" + suffix);
11499            suffix++;
11500        } while (result.exists());
11501        return result;
11502    }
11503
11504    // Utility method that returns the relative package path with respect
11505    // to the installation directory. Like say for /data/data/com.test-1.apk
11506    // string com.test-1 is returned.
11507    static String deriveCodePathName(String codePath) {
11508        if (codePath == null) {
11509            return null;
11510        }
11511        final File codeFile = new File(codePath);
11512        final String name = codeFile.getName();
11513        if (codeFile.isDirectory()) {
11514            return name;
11515        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
11516            final int lastDot = name.lastIndexOf('.');
11517            return name.substring(0, lastDot);
11518        } else {
11519            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11520            return null;
11521        }
11522    }
11523
11524    class PackageInstalledInfo {
11525        String name;
11526        int uid;
11527        // The set of users that originally had this package installed.
11528        int[] origUsers;
11529        // The set of users that now have this package installed.
11530        int[] newUsers;
11531        PackageParser.Package pkg;
11532        int returnCode;
11533        String returnMsg;
11534        PackageRemovedInfo removedInfo;
11535
11536        public void setError(int code, String msg) {
11537            returnCode = code;
11538            returnMsg = msg;
11539            Slog.w(TAG, msg);
11540        }
11541
11542        public void setError(String msg, PackageParserException e) {
11543            returnCode = e.error;
11544            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11545            Slog.w(TAG, msg, e);
11546        }
11547
11548        public void setError(String msg, PackageManagerException e) {
11549            returnCode = e.error;
11550            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11551            Slog.w(TAG, msg, e);
11552        }
11553
11554        // In some error cases we want to convey more info back to the observer
11555        String origPackage;
11556        String origPermission;
11557    }
11558
11559    /*
11560     * Install a non-existing package.
11561     */
11562    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11563            UserHandle user, String installerPackageName, String volumeUuid,
11564            PackageInstalledInfo res) {
11565        // Remember this for later, in case we need to rollback this install
11566        String pkgName = pkg.packageName;
11567
11568        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
11569        final boolean dataDirExists = Environment
11570                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists();
11571        synchronized(mPackages) {
11572            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
11573                // A package with the same name is already installed, though
11574                // it has been renamed to an older name.  The package we
11575                // are trying to install should be installed as an update to
11576                // the existing one, but that has not been requested, so bail.
11577                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11578                        + " without first uninstalling package running as "
11579                        + mSettings.mRenamedPackages.get(pkgName));
11580                return;
11581            }
11582            if (mPackages.containsKey(pkgName)) {
11583                // Don't allow installation over an existing package with the same name.
11584                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11585                        + " without first uninstalling.");
11586                return;
11587            }
11588        }
11589
11590        try {
11591            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
11592                    System.currentTimeMillis(), user);
11593
11594            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
11595            // delete the partially installed application. the data directory will have to be
11596            // restored if it was already existing
11597            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11598                // remove package from internal structures.  Note that we want deletePackageX to
11599                // delete the package data and cache directories that it created in
11600                // scanPackageLocked, unless those directories existed before we even tried to
11601                // install.
11602                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
11603                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
11604                                res.removedInfo, true);
11605            }
11606
11607        } catch (PackageManagerException e) {
11608            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11609        }
11610    }
11611
11612    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
11613        // Can't rotate keys during boot or if sharedUser.
11614        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
11615                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
11616            return false;
11617        }
11618        // app is using upgradeKeySets; make sure all are valid
11619        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11620        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
11621        for (int i = 0; i < upgradeKeySets.length; i++) {
11622            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
11623                Slog.wtf(TAG, "Package "
11624                         + (oldPs.name != null ? oldPs.name : "<null>")
11625                         + " contains upgrade-key-set reference to unknown key-set: "
11626                         + upgradeKeySets[i]
11627                         + " reverting to signatures check.");
11628                return false;
11629            }
11630        }
11631        return true;
11632    }
11633
11634    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
11635        // Upgrade keysets are being used.  Determine if new package has a superset of the
11636        // required keys.
11637        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
11638        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11639        for (int i = 0; i < upgradeKeySets.length; i++) {
11640            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
11641            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
11642                return true;
11643            }
11644        }
11645        return false;
11646    }
11647
11648    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11649            UserHandle user, String installerPackageName, String volumeUuid,
11650            PackageInstalledInfo res) {
11651        final PackageParser.Package oldPackage;
11652        final String pkgName = pkg.packageName;
11653        final int[] allUsers;
11654        final boolean[] perUserInstalled;
11655        final boolean weFroze;
11656
11657        // First find the old package info and check signatures
11658        synchronized(mPackages) {
11659            oldPackage = mPackages.get(pkgName);
11660            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
11661            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11662            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11663                if(!checkUpgradeKeySetLP(ps, pkg)) {
11664                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11665                            "New package not signed by keys specified by upgrade-keysets: "
11666                            + pkgName);
11667                    return;
11668                }
11669            } else {
11670                // default to original signature matching
11671                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
11672                    != PackageManager.SIGNATURE_MATCH) {
11673                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11674                            "New package has a different signature: " + pkgName);
11675                    return;
11676                }
11677            }
11678
11679            // In case of rollback, remember per-user/profile install state
11680            allUsers = sUserManager.getUserIds();
11681            perUserInstalled = new boolean[allUsers.length];
11682            for (int i = 0; i < allUsers.length; i++) {
11683                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11684            }
11685
11686            // Mark the app as frozen to prevent launching during the upgrade
11687            // process, and then kill all running instances
11688            if (!ps.frozen) {
11689                ps.frozen = true;
11690                weFroze = true;
11691            } else {
11692                weFroze = false;
11693            }
11694        }
11695
11696        // Now that we're guarded by frozen state, kill app during upgrade
11697        killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg");
11698
11699        try {
11700            boolean sysPkg = (isSystemApp(oldPackage));
11701            if (sysPkg) {
11702                replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11703                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11704            } else {
11705                replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11706                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11707            }
11708        } finally {
11709            // Regardless of success or failure of upgrade steps above, always
11710            // unfreeze the package if we froze it
11711            if (weFroze) {
11712                unfreezePackage(pkgName);
11713            }
11714        }
11715    }
11716
11717    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
11718            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11719            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11720            String volumeUuid, PackageInstalledInfo res) {
11721        String pkgName = deletedPackage.packageName;
11722        boolean deletedPkg = true;
11723        boolean updatedSettings = false;
11724
11725        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
11726                + deletedPackage);
11727        long origUpdateTime;
11728        if (pkg.mExtras != null) {
11729            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
11730        } else {
11731            origUpdateTime = 0;
11732        }
11733
11734        // First delete the existing package while retaining the data directory
11735        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
11736                res.removedInfo, true)) {
11737            // If the existing package wasn't successfully deleted
11738            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
11739            deletedPkg = false;
11740        } else {
11741            // Successfully deleted the old package; proceed with replace.
11742
11743            // If deleted package lived in a container, give users a chance to
11744            // relinquish resources before killing.
11745            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
11746                if (DEBUG_INSTALL) {
11747                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
11748                }
11749                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
11750                final ArrayList<String> pkgList = new ArrayList<String>(1);
11751                pkgList.add(deletedPackage.applicationInfo.packageName);
11752                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
11753            }
11754
11755            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
11756            try {
11757                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
11758                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
11759                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11760                        perUserInstalled, res, user);
11761                updatedSettings = true;
11762            } catch (PackageManagerException e) {
11763                res.setError("Package couldn't be installed in " + pkg.codePath, e);
11764            }
11765        }
11766
11767        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11768            // remove package from internal structures.  Note that we want deletePackageX to
11769            // delete the package data and cache directories that it created in
11770            // scanPackageLocked, unless those directories existed before we even tried to
11771            // install.
11772            if(updatedSettings) {
11773                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
11774                deletePackageLI(
11775                        pkgName, null, true, allUsers, perUserInstalled,
11776                        PackageManager.DELETE_KEEP_DATA,
11777                                res.removedInfo, true);
11778            }
11779            // Since we failed to install the new package we need to restore the old
11780            // package that we deleted.
11781            if (deletedPkg) {
11782                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
11783                File restoreFile = new File(deletedPackage.codePath);
11784                // Parse old package
11785                boolean oldExternal = isExternal(deletedPackage);
11786                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
11787                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
11788                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11789                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
11790                try {
11791                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
11792                } catch (PackageManagerException e) {
11793                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
11794                            + e.getMessage());
11795                    return;
11796                }
11797                // Restore of old package succeeded. Update permissions.
11798                // writer
11799                synchronized (mPackages) {
11800                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
11801                            UPDATE_PERMISSIONS_ALL);
11802                    // can downgrade to reader
11803                    mSettings.writeLPr();
11804                }
11805                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
11806            }
11807        }
11808    }
11809
11810    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
11811            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11812            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11813            String volumeUuid, PackageInstalledInfo res) {
11814        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
11815                + ", old=" + deletedPackage);
11816        boolean disabledSystem = false;
11817        boolean updatedSettings = false;
11818        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
11819        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
11820                != 0) {
11821            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11822        }
11823        String packageName = deletedPackage.packageName;
11824        if (packageName == null) {
11825            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11826                    "Attempt to delete null packageName.");
11827            return;
11828        }
11829        PackageParser.Package oldPkg;
11830        PackageSetting oldPkgSetting;
11831        // reader
11832        synchronized (mPackages) {
11833            oldPkg = mPackages.get(packageName);
11834            oldPkgSetting = mSettings.mPackages.get(packageName);
11835            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
11836                    (oldPkgSetting == null)) {
11837                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11838                        "Couldn't find package:" + packageName + " information");
11839                return;
11840            }
11841        }
11842
11843        res.removedInfo.uid = oldPkg.applicationInfo.uid;
11844        res.removedInfo.removedPackage = packageName;
11845        // Remove existing system package
11846        removePackageLI(oldPkgSetting, true);
11847        // writer
11848        synchronized (mPackages) {
11849            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
11850            if (!disabledSystem && deletedPackage != null) {
11851                // We didn't need to disable the .apk as a current system package,
11852                // which means we are replacing another update that is already
11853                // installed.  We need to make sure to delete the older one's .apk.
11854                res.removedInfo.args = createInstallArgsForExisting(0,
11855                        deletedPackage.applicationInfo.getCodePath(),
11856                        deletedPackage.applicationInfo.getResourcePath(),
11857                        getAppDexInstructionSets(deletedPackage.applicationInfo));
11858            } else {
11859                res.removedInfo.args = null;
11860            }
11861        }
11862
11863        // Successfully disabled the old package. Now proceed with re-installation
11864        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
11865
11866        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11867        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
11868
11869        PackageParser.Package newPackage = null;
11870        try {
11871            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
11872            if (newPackage.mExtras != null) {
11873                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
11874                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
11875                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
11876
11877                // is the update attempting to change shared user? that isn't going to work...
11878                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
11879                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
11880                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
11881                            + " to " + newPkgSetting.sharedUser);
11882                    updatedSettings = true;
11883                }
11884            }
11885
11886            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11887                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11888                        perUserInstalled, res, user);
11889                updatedSettings = true;
11890            }
11891
11892        } catch (PackageManagerException e) {
11893            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11894        }
11895
11896        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11897            // Re installation failed. Restore old information
11898            // Remove new pkg information
11899            if (newPackage != null) {
11900                removeInstalledPackageLI(newPackage, true);
11901            }
11902            // Add back the old system package
11903            try {
11904                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
11905            } catch (PackageManagerException e) {
11906                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
11907            }
11908            // Restore the old system information in Settings
11909            synchronized (mPackages) {
11910                if (disabledSystem) {
11911                    mSettings.enableSystemPackageLPw(packageName);
11912                }
11913                if (updatedSettings) {
11914                    mSettings.setInstallerPackageName(packageName,
11915                            oldPkgSetting.installerPackageName);
11916                }
11917                mSettings.writeLPr();
11918            }
11919        }
11920    }
11921
11922    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
11923            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
11924            UserHandle user) {
11925        String pkgName = newPackage.packageName;
11926        synchronized (mPackages) {
11927            //write settings. the installStatus will be incomplete at this stage.
11928            //note that the new package setting would have already been
11929            //added to mPackages. It hasn't been persisted yet.
11930            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
11931            mSettings.writeLPr();
11932        }
11933
11934        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
11935
11936        synchronized (mPackages) {
11937            updatePermissionsLPw(newPackage.packageName, newPackage,
11938                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
11939                            ? UPDATE_PERMISSIONS_ALL : 0));
11940            // For system-bundled packages, we assume that installing an upgraded version
11941            // of the package implies that the user actually wants to run that new code,
11942            // so we enable the package.
11943            PackageSetting ps = mSettings.mPackages.get(pkgName);
11944            if (ps != null) {
11945                if (isSystemApp(newPackage)) {
11946                    // NB: implicit assumption that system package upgrades apply to all users
11947                    if (DEBUG_INSTALL) {
11948                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
11949                    }
11950                    if (res.origUsers != null) {
11951                        for (int userHandle : res.origUsers) {
11952                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
11953                                    userHandle, installerPackageName);
11954                        }
11955                    }
11956                    // Also convey the prior install/uninstall state
11957                    if (allUsers != null && perUserInstalled != null) {
11958                        for (int i = 0; i < allUsers.length; i++) {
11959                            if (DEBUG_INSTALL) {
11960                                Slog.d(TAG, "    user " + allUsers[i]
11961                                        + " => " + perUserInstalled[i]);
11962                            }
11963                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
11964                        }
11965                        // these install state changes will be persisted in the
11966                        // upcoming call to mSettings.writeLPr().
11967                    }
11968                }
11969                // It's implied that when a user requests installation, they want the app to be
11970                // installed and enabled.
11971                int userId = user.getIdentifier();
11972                if (userId != UserHandle.USER_ALL) {
11973                    ps.setInstalled(true, userId);
11974                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
11975                }
11976            }
11977            res.name = pkgName;
11978            res.uid = newPackage.applicationInfo.uid;
11979            res.pkg = newPackage;
11980            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
11981            mSettings.setInstallerPackageName(pkgName, installerPackageName);
11982            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11983            //to update install status
11984            mSettings.writeLPr();
11985        }
11986    }
11987
11988    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
11989        final int installFlags = args.installFlags;
11990        final String installerPackageName = args.installerPackageName;
11991        final String volumeUuid = args.volumeUuid;
11992        final File tmpPackageFile = new File(args.getCodePath());
11993        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
11994        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
11995                || (args.volumeUuid != null));
11996        boolean replace = false;
11997        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
11998        if (args.move != null) {
11999            // moving a complete application; perfom an initial scan on the new install location
12000            scanFlags |= SCAN_INITIAL;
12001        }
12002        // Result object to be returned
12003        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12004
12005        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12006        // Retrieve PackageSettings and parse package
12007        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12008                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12009                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12010        PackageParser pp = new PackageParser();
12011        pp.setSeparateProcesses(mSeparateProcesses);
12012        pp.setDisplayMetrics(mMetrics);
12013
12014        final PackageParser.Package pkg;
12015        try {
12016            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12017        } catch (PackageParserException e) {
12018            res.setError("Failed parse during installPackageLI", e);
12019            return;
12020        }
12021
12022        // Mark that we have an install time CPU ABI override.
12023        pkg.cpuAbiOverride = args.abiOverride;
12024
12025        String pkgName = res.name = pkg.packageName;
12026        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12027            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12028                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12029                return;
12030            }
12031        }
12032
12033        try {
12034            pp.collectCertificates(pkg, parseFlags);
12035            pp.collectManifestDigest(pkg);
12036        } catch (PackageParserException e) {
12037            res.setError("Failed collect during installPackageLI", e);
12038            return;
12039        }
12040
12041        /* If the installer passed in a manifest digest, compare it now. */
12042        if (args.manifestDigest != null) {
12043            if (DEBUG_INSTALL) {
12044                final String parsedManifest = pkg.manifestDigest == null ? "null"
12045                        : pkg.manifestDigest.toString();
12046                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
12047                        + parsedManifest);
12048            }
12049
12050            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
12051                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
12052                return;
12053            }
12054        } else if (DEBUG_INSTALL) {
12055            final String parsedManifest = pkg.manifestDigest == null
12056                    ? "null" : pkg.manifestDigest.toString();
12057            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
12058        }
12059
12060        // Get rid of all references to package scan path via parser.
12061        pp = null;
12062        String oldCodePath = null;
12063        boolean systemApp = false;
12064        synchronized (mPackages) {
12065            // Check if installing already existing package
12066            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12067                String oldName = mSettings.mRenamedPackages.get(pkgName);
12068                if (pkg.mOriginalPackages != null
12069                        && pkg.mOriginalPackages.contains(oldName)
12070                        && mPackages.containsKey(oldName)) {
12071                    // This package is derived from an original package,
12072                    // and this device has been updating from that original
12073                    // name.  We must continue using the original name, so
12074                    // rename the new package here.
12075                    pkg.setPackageName(oldName);
12076                    pkgName = pkg.packageName;
12077                    replace = true;
12078                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12079                            + oldName + " pkgName=" + pkgName);
12080                } else if (mPackages.containsKey(pkgName)) {
12081                    // This package, under its official name, already exists
12082                    // on the device; we should replace it.
12083                    replace = true;
12084                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12085                }
12086
12087                // Prevent apps opting out from runtime permissions
12088                if (replace) {
12089                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12090                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12091                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12092                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12093                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12094                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12095                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12096                                        + " doesn't support runtime permissions but the old"
12097                                        + " target SDK " + oldTargetSdk + " does.");
12098                        return;
12099                    }
12100                }
12101            }
12102
12103            PackageSetting ps = mSettings.mPackages.get(pkgName);
12104            if (ps != null) {
12105                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12106
12107                // Quick sanity check that we're signed correctly if updating;
12108                // we'll check this again later when scanning, but we want to
12109                // bail early here before tripping over redefined permissions.
12110                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12111                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12112                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12113                                + pkg.packageName + " upgrade keys do not match the "
12114                                + "previously installed version");
12115                        return;
12116                    }
12117                } else {
12118                    try {
12119                        verifySignaturesLP(ps, pkg);
12120                    } catch (PackageManagerException e) {
12121                        res.setError(e.error, e.getMessage());
12122                        return;
12123                    }
12124                }
12125
12126                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12127                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12128                    systemApp = (ps.pkg.applicationInfo.flags &
12129                            ApplicationInfo.FLAG_SYSTEM) != 0;
12130                }
12131                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12132            }
12133
12134            // Check whether the newly-scanned package wants to define an already-defined perm
12135            int N = pkg.permissions.size();
12136            for (int i = N-1; i >= 0; i--) {
12137                PackageParser.Permission perm = pkg.permissions.get(i);
12138                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12139                if (bp != null) {
12140                    // If the defining package is signed with our cert, it's okay.  This
12141                    // also includes the "updating the same package" case, of course.
12142                    // "updating same package" could also involve key-rotation.
12143                    final boolean sigsOk;
12144                    if (bp.sourcePackage.equals(pkg.packageName)
12145                            && (bp.packageSetting instanceof PackageSetting)
12146                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12147                                    scanFlags))) {
12148                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12149                    } else {
12150                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12151                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12152                    }
12153                    if (!sigsOk) {
12154                        // If the owning package is the system itself, we log but allow
12155                        // install to proceed; we fail the install on all other permission
12156                        // redefinitions.
12157                        if (!bp.sourcePackage.equals("android")) {
12158                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12159                                    + pkg.packageName + " attempting to redeclare permission "
12160                                    + perm.info.name + " already owned by " + bp.sourcePackage);
12161                            res.origPermission = perm.info.name;
12162                            res.origPackage = bp.sourcePackage;
12163                            return;
12164                        } else {
12165                            Slog.w(TAG, "Package " + pkg.packageName
12166                                    + " attempting to redeclare system permission "
12167                                    + perm.info.name + "; ignoring new declaration");
12168                            pkg.permissions.remove(i);
12169                        }
12170                    }
12171                }
12172            }
12173
12174        }
12175
12176        if (systemApp && onExternal) {
12177            // Disable updates to system apps on sdcard
12178            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12179                    "Cannot install updates to system apps on sdcard");
12180            return;
12181        }
12182
12183        if (args.move != null) {
12184            // We did an in-place move, so dex is ready to roll
12185            scanFlags |= SCAN_NO_DEX;
12186            scanFlags |= SCAN_MOVE;
12187        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
12188            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
12189            scanFlags |= SCAN_NO_DEX;
12190
12191            try {
12192                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
12193                        true /* extract libs */);
12194            } catch (PackageManagerException pme) {
12195                Slog.e(TAG, "Error deriving application ABI", pme);
12196                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
12197                return;
12198            }
12199
12200            // Run dexopt before old package gets removed, to minimize time when app is unavailable
12201            int result = mPackageDexOptimizer
12202                    .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */,
12203                            false /* defer */, false /* inclDependencies */);
12204            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
12205                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
12206                return;
12207            }
12208        }
12209
12210        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
12211            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
12212            return;
12213        }
12214
12215        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
12216
12217        if (replace) {
12218            replacePackageLI(pkg, parseFlags, scanFlags, args.user,
12219                    installerPackageName, volumeUuid, res);
12220        } else {
12221            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
12222                    args.user, installerPackageName, volumeUuid, res);
12223        }
12224        synchronized (mPackages) {
12225            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12226            if (ps != null) {
12227                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12228            }
12229        }
12230    }
12231
12232    private void startIntentFilterVerifications(int userId, boolean replacing,
12233            PackageParser.Package pkg) {
12234        if (mIntentFilterVerifierComponent == null) {
12235            Slog.w(TAG, "No IntentFilter verification will not be done as "
12236                    + "there is no IntentFilterVerifier available!");
12237            return;
12238        }
12239
12240        final int verifierUid = getPackageUid(
12241                mIntentFilterVerifierComponent.getPackageName(),
12242                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
12243
12244        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
12245        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
12246        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
12247        mHandler.sendMessage(msg);
12248    }
12249
12250    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
12251            PackageParser.Package pkg) {
12252        int size = pkg.activities.size();
12253        if (size == 0) {
12254            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12255                    "No activity, so no need to verify any IntentFilter!");
12256            return;
12257        }
12258
12259        final boolean hasDomainURLs = hasDomainURLs(pkg);
12260        if (!hasDomainURLs) {
12261            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12262                    "No domain URLs, so no need to verify any IntentFilter!");
12263            return;
12264        }
12265
12266        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
12267                + " if any IntentFilter from the " + size
12268                + " Activities needs verification ...");
12269
12270        int count = 0;
12271        final String packageName = pkg.packageName;
12272
12273        synchronized (mPackages) {
12274            // If this is a new install and we see that we've already run verification for this
12275            // package, we have nothing to do: it means the state was restored from backup.
12276            if (!replacing) {
12277                IntentFilterVerificationInfo ivi =
12278                        mSettings.getIntentFilterVerificationLPr(packageName);
12279                if (ivi != null) {
12280                    if (DEBUG_DOMAIN_VERIFICATION) {
12281                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
12282                                + ivi.getStatusString());
12283                    }
12284                    return;
12285                }
12286            }
12287
12288            // If any filters need to be verified, then all need to be.
12289            boolean needToVerify = false;
12290            for (PackageParser.Activity a : pkg.activities) {
12291                for (ActivityIntentInfo filter : a.intents) {
12292                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
12293                        if (DEBUG_DOMAIN_VERIFICATION) {
12294                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
12295                        }
12296                        needToVerify = true;
12297                        break;
12298                    }
12299                }
12300            }
12301
12302            if (needToVerify) {
12303                final int verificationId = mIntentFilterVerificationToken++;
12304                for (PackageParser.Activity a : pkg.activities) {
12305                    for (ActivityIntentInfo filter : a.intents) {
12306                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
12307                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12308                                    "Verification needed for IntentFilter:" + filter.toString());
12309                            mIntentFilterVerifier.addOneIntentFilterVerification(
12310                                    verifierUid, userId, verificationId, filter, packageName);
12311                            count++;
12312                        }
12313                    }
12314                }
12315            }
12316        }
12317
12318        if (count > 0) {
12319            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
12320                    + " IntentFilter verification" + (count > 1 ? "s" : "")
12321                    +  " for userId:" + userId);
12322            mIntentFilterVerifier.startVerifications(userId);
12323        } else {
12324            if (DEBUG_DOMAIN_VERIFICATION) {
12325                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
12326            }
12327        }
12328    }
12329
12330    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
12331        final ComponentName cn  = filter.activity.getComponentName();
12332        final String packageName = cn.getPackageName();
12333
12334        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
12335                packageName);
12336        if (ivi == null) {
12337            return true;
12338        }
12339        int status = ivi.getStatus();
12340        switch (status) {
12341            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
12342            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
12343                return true;
12344
12345            default:
12346                // Nothing to do
12347                return false;
12348        }
12349    }
12350
12351    private static boolean isMultiArch(PackageSetting ps) {
12352        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12353    }
12354
12355    private static boolean isMultiArch(ApplicationInfo info) {
12356        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12357    }
12358
12359    private static boolean isExternal(PackageParser.Package pkg) {
12360        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12361    }
12362
12363    private static boolean isExternal(PackageSetting ps) {
12364        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12365    }
12366
12367    private static boolean isExternal(ApplicationInfo info) {
12368        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12369    }
12370
12371    private static boolean isSystemApp(PackageParser.Package pkg) {
12372        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
12373    }
12374
12375    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
12376        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
12377    }
12378
12379    private static boolean hasDomainURLs(PackageParser.Package pkg) {
12380        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
12381    }
12382
12383    private static boolean isSystemApp(PackageSetting ps) {
12384        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
12385    }
12386
12387    private static boolean isUpdatedSystemApp(PackageSetting ps) {
12388        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
12389    }
12390
12391    private int packageFlagsToInstallFlags(PackageSetting ps) {
12392        int installFlags = 0;
12393        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
12394            // This existing package was an external ASEC install when we have
12395            // the external flag without a UUID
12396            installFlags |= PackageManager.INSTALL_EXTERNAL;
12397        }
12398        if (ps.isForwardLocked()) {
12399            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12400        }
12401        return installFlags;
12402    }
12403
12404    private void deleteTempPackageFiles() {
12405        final FilenameFilter filter = new FilenameFilter() {
12406            public boolean accept(File dir, String name) {
12407                return name.startsWith("vmdl") && name.endsWith(".tmp");
12408            }
12409        };
12410        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
12411            file.delete();
12412        }
12413    }
12414
12415    @Override
12416    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
12417            int flags) {
12418        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
12419                flags);
12420    }
12421
12422    @Override
12423    public void deletePackage(final String packageName,
12424            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
12425        mContext.enforceCallingOrSelfPermission(
12426                android.Manifest.permission.DELETE_PACKAGES, null);
12427        Preconditions.checkNotNull(packageName);
12428        Preconditions.checkNotNull(observer);
12429        final int uid = Binder.getCallingUid();
12430        if (UserHandle.getUserId(uid) != userId) {
12431            mContext.enforceCallingPermission(
12432                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
12433                    "deletePackage for user " + userId);
12434        }
12435        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
12436            try {
12437                observer.onPackageDeleted(packageName,
12438                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
12439            } catch (RemoteException re) {
12440            }
12441            return;
12442        }
12443
12444        boolean uninstallBlocked = false;
12445        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
12446            int[] users = sUserManager.getUserIds();
12447            for (int i = 0; i < users.length; ++i) {
12448                if (getBlockUninstallForUser(packageName, users[i])) {
12449                    uninstallBlocked = true;
12450                    break;
12451                }
12452            }
12453        } else {
12454            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
12455        }
12456        if (uninstallBlocked) {
12457            try {
12458                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
12459                        null);
12460            } catch (RemoteException re) {
12461            }
12462            return;
12463        }
12464
12465        if (DEBUG_REMOVE) {
12466            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
12467        }
12468        // Queue up an async operation since the package deletion may take a little while.
12469        mHandler.post(new Runnable() {
12470            public void run() {
12471                mHandler.removeCallbacks(this);
12472                final int returnCode = deletePackageX(packageName, userId, flags);
12473                if (observer != null) {
12474                    try {
12475                        observer.onPackageDeleted(packageName, returnCode, null);
12476                    } catch (RemoteException e) {
12477                        Log.i(TAG, "Observer no longer exists.");
12478                    } //end catch
12479                } //end if
12480            } //end run
12481        });
12482    }
12483
12484    private boolean isPackageDeviceAdmin(String packageName, int userId) {
12485        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12486                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12487        try {
12488            if (dpm != null) {
12489                if (dpm.isDeviceOwner(packageName)) {
12490                    return true;
12491                }
12492                int[] users;
12493                if (userId == UserHandle.USER_ALL) {
12494                    users = sUserManager.getUserIds();
12495                } else {
12496                    users = new int[]{userId};
12497                }
12498                for (int i = 0; i < users.length; ++i) {
12499                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
12500                        return true;
12501                    }
12502                }
12503            }
12504        } catch (RemoteException e) {
12505        }
12506        return false;
12507    }
12508
12509    /**
12510     *  This method is an internal method that could be get invoked either
12511     *  to delete an installed package or to clean up a failed installation.
12512     *  After deleting an installed package, a broadcast is sent to notify any
12513     *  listeners that the package has been installed. For cleaning up a failed
12514     *  installation, the broadcast is not necessary since the package's
12515     *  installation wouldn't have sent the initial broadcast either
12516     *  The key steps in deleting a package are
12517     *  deleting the package information in internal structures like mPackages,
12518     *  deleting the packages base directories through installd
12519     *  updating mSettings to reflect current status
12520     *  persisting settings for later use
12521     *  sending a broadcast if necessary
12522     */
12523    private int deletePackageX(String packageName, int userId, int flags) {
12524        final PackageRemovedInfo info = new PackageRemovedInfo();
12525        final boolean res;
12526
12527        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
12528                ? UserHandle.ALL : new UserHandle(userId);
12529
12530        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
12531            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
12532            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
12533        }
12534
12535        boolean removedForAllUsers = false;
12536        boolean systemUpdate = false;
12537
12538        // for the uninstall-updates case and restricted profiles, remember the per-
12539        // userhandle installed state
12540        int[] allUsers;
12541        boolean[] perUserInstalled;
12542        synchronized (mPackages) {
12543            PackageSetting ps = mSettings.mPackages.get(packageName);
12544            allUsers = sUserManager.getUserIds();
12545            perUserInstalled = new boolean[allUsers.length];
12546            for (int i = 0; i < allUsers.length; i++) {
12547                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12548            }
12549        }
12550
12551        synchronized (mInstallLock) {
12552            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
12553            res = deletePackageLI(packageName, removeForUser,
12554                    true, allUsers, perUserInstalled,
12555                    flags | REMOVE_CHATTY, info, true);
12556            systemUpdate = info.isRemovedPackageSystemUpdate;
12557            if (res && !systemUpdate && mPackages.get(packageName) == null) {
12558                removedForAllUsers = true;
12559            }
12560            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
12561                    + " removedForAllUsers=" + removedForAllUsers);
12562        }
12563
12564        if (res) {
12565            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
12566
12567            // If the removed package was a system update, the old system package
12568            // was re-enabled; we need to broadcast this information
12569            if (systemUpdate) {
12570                Bundle extras = new Bundle(1);
12571                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
12572                        ? info.removedAppId : info.uid);
12573                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12574
12575                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
12576                        extras, null, null, null);
12577                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
12578                        extras, null, null, null);
12579                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
12580                        null, packageName, null, null);
12581            }
12582        }
12583        // Force a gc here.
12584        Runtime.getRuntime().gc();
12585        // Delete the resources here after sending the broadcast to let
12586        // other processes clean up before deleting resources.
12587        if (info.args != null) {
12588            synchronized (mInstallLock) {
12589                info.args.doPostDeleteLI(true);
12590            }
12591        }
12592
12593        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
12594    }
12595
12596    class PackageRemovedInfo {
12597        String removedPackage;
12598        int uid = -1;
12599        int removedAppId = -1;
12600        int[] removedUsers = null;
12601        boolean isRemovedPackageSystemUpdate = false;
12602        // Clean up resources deleted packages.
12603        InstallArgs args = null;
12604
12605        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
12606            Bundle extras = new Bundle(1);
12607            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
12608            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
12609            if (replacing) {
12610                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12611            }
12612            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
12613            if (removedPackage != null) {
12614                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
12615                        extras, null, null, removedUsers);
12616                if (fullRemove && !replacing) {
12617                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
12618                            extras, null, null, removedUsers);
12619                }
12620            }
12621            if (removedAppId >= 0) {
12622                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
12623                        removedUsers);
12624            }
12625        }
12626    }
12627
12628    /*
12629     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
12630     * flag is not set, the data directory is removed as well.
12631     * make sure this flag is set for partially installed apps. If not its meaningless to
12632     * delete a partially installed application.
12633     */
12634    private void removePackageDataLI(PackageSetting ps,
12635            int[] allUserHandles, boolean[] perUserInstalled,
12636            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
12637        String packageName = ps.name;
12638        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
12639        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
12640        // Retrieve object to delete permissions for shared user later on
12641        final PackageSetting deletedPs;
12642        // reader
12643        synchronized (mPackages) {
12644            deletedPs = mSettings.mPackages.get(packageName);
12645            if (outInfo != null) {
12646                outInfo.removedPackage = packageName;
12647                outInfo.removedUsers = deletedPs != null
12648                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
12649                        : null;
12650            }
12651        }
12652        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12653            removeDataDirsLI(ps.volumeUuid, packageName);
12654            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
12655        }
12656        // writer
12657        synchronized (mPackages) {
12658            if (deletedPs != null) {
12659                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12660                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
12661                    clearDefaultBrowserIfNeeded(packageName);
12662                    if (outInfo != null) {
12663                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
12664                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
12665                    }
12666                    updatePermissionsLPw(deletedPs.name, null, 0);
12667                    if (deletedPs.sharedUser != null) {
12668                        // Remove permissions associated with package. Since runtime
12669                        // permissions are per user we have to kill the removed package
12670                        // or packages running under the shared user of the removed
12671                        // package if revoking the permissions requested only by the removed
12672                        // package is successful and this causes a change in gids.
12673                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12674                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
12675                                    userId);
12676                            if (userIdToKill == UserHandle.USER_ALL
12677                                    || userIdToKill >= UserHandle.USER_OWNER) {
12678                                // If gids changed for this user, kill all affected packages.
12679                                mHandler.post(new Runnable() {
12680                                    @Override
12681                                    public void run() {
12682                                        // This has to happen with no lock held.
12683                                        killSettingPackagesForUser(deletedPs, userIdToKill,
12684                                                KILL_APP_REASON_GIDS_CHANGED);
12685                                    }
12686                                });
12687                            break;
12688                            }
12689                        }
12690                    }
12691                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
12692                }
12693                // make sure to preserve per-user disabled state if this removal was just
12694                // a downgrade of a system app to the factory package
12695                if (allUserHandles != null && perUserInstalled != null) {
12696                    if (DEBUG_REMOVE) {
12697                        Slog.d(TAG, "Propagating install state across downgrade");
12698                    }
12699                    for (int i = 0; i < allUserHandles.length; i++) {
12700                        if (DEBUG_REMOVE) {
12701                            Slog.d(TAG, "    user " + allUserHandles[i]
12702                                    + " => " + perUserInstalled[i]);
12703                        }
12704                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12705                    }
12706                }
12707            }
12708            // can downgrade to reader
12709            if (writeSettings) {
12710                // Save settings now
12711                mSettings.writeLPr();
12712            }
12713        }
12714        if (outInfo != null) {
12715            // A user ID was deleted here. Go through all users and remove it
12716            // from KeyStore.
12717            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
12718        }
12719    }
12720
12721    static boolean locationIsPrivileged(File path) {
12722        try {
12723            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
12724                    .getCanonicalPath();
12725            return path.getCanonicalPath().startsWith(privilegedAppDir);
12726        } catch (IOException e) {
12727            Slog.e(TAG, "Unable to access code path " + path);
12728        }
12729        return false;
12730    }
12731
12732    /*
12733     * Tries to delete system package.
12734     */
12735    private boolean deleteSystemPackageLI(PackageSetting newPs,
12736            int[] allUserHandles, boolean[] perUserInstalled,
12737            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
12738        final boolean applyUserRestrictions
12739                = (allUserHandles != null) && (perUserInstalled != null);
12740        PackageSetting disabledPs = null;
12741        // Confirm if the system package has been updated
12742        // An updated system app can be deleted. This will also have to restore
12743        // the system pkg from system partition
12744        // reader
12745        synchronized (mPackages) {
12746            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
12747        }
12748        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
12749                + " disabledPs=" + disabledPs);
12750        if (disabledPs == null) {
12751            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
12752            return false;
12753        } else if (DEBUG_REMOVE) {
12754            Slog.d(TAG, "Deleting system pkg from data partition");
12755        }
12756        if (DEBUG_REMOVE) {
12757            if (applyUserRestrictions) {
12758                Slog.d(TAG, "Remembering install states:");
12759                for (int i = 0; i < allUserHandles.length; i++) {
12760                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
12761                }
12762            }
12763        }
12764        // Delete the updated package
12765        outInfo.isRemovedPackageSystemUpdate = true;
12766        if (disabledPs.versionCode < newPs.versionCode) {
12767            // Delete data for downgrades
12768            flags &= ~PackageManager.DELETE_KEEP_DATA;
12769        } else {
12770            // Preserve data by setting flag
12771            flags |= PackageManager.DELETE_KEEP_DATA;
12772        }
12773        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
12774                allUserHandles, perUserInstalled, outInfo, writeSettings);
12775        if (!ret) {
12776            return false;
12777        }
12778        // writer
12779        synchronized (mPackages) {
12780            // Reinstate the old system package
12781            mSettings.enableSystemPackageLPw(newPs.name);
12782            // Remove any native libraries from the upgraded package.
12783            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
12784        }
12785        // Install the system package
12786        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
12787        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
12788        if (locationIsPrivileged(disabledPs.codePath)) {
12789            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12790        }
12791
12792        final PackageParser.Package newPkg;
12793        try {
12794            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
12795        } catch (PackageManagerException e) {
12796            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
12797            return false;
12798        }
12799
12800        // writer
12801        synchronized (mPackages) {
12802            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
12803            updatePermissionsLPw(newPkg.packageName, newPkg,
12804                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
12805            if (applyUserRestrictions) {
12806                if (DEBUG_REMOVE) {
12807                    Slog.d(TAG, "Propagating install state across reinstall");
12808                }
12809                for (int i = 0; i < allUserHandles.length; i++) {
12810                    if (DEBUG_REMOVE) {
12811                        Slog.d(TAG, "    user " + allUserHandles[i]
12812                                + " => " + perUserInstalled[i]);
12813                    }
12814                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12815                }
12816                // Regardless of writeSettings we need to ensure that this restriction
12817                // state propagation is persisted
12818                mSettings.writeAllUsersPackageRestrictionsLPr();
12819            }
12820            // can downgrade to reader here
12821            if (writeSettings) {
12822                mSettings.writeLPr();
12823            }
12824        }
12825        return true;
12826    }
12827
12828    private boolean deleteInstalledPackageLI(PackageSetting ps,
12829            boolean deleteCodeAndResources, int flags,
12830            int[] allUserHandles, boolean[] perUserInstalled,
12831            PackageRemovedInfo outInfo, boolean writeSettings) {
12832        if (outInfo != null) {
12833            outInfo.uid = ps.appId;
12834        }
12835
12836        // Delete package data from internal structures and also remove data if flag is set
12837        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
12838
12839        // Delete application code and resources
12840        if (deleteCodeAndResources && (outInfo != null)) {
12841            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
12842                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
12843            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
12844        }
12845        return true;
12846    }
12847
12848    @Override
12849    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
12850            int userId) {
12851        mContext.enforceCallingOrSelfPermission(
12852                android.Manifest.permission.DELETE_PACKAGES, null);
12853        synchronized (mPackages) {
12854            PackageSetting ps = mSettings.mPackages.get(packageName);
12855            if (ps == null) {
12856                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
12857                return false;
12858            }
12859            if (!ps.getInstalled(userId)) {
12860                // Can't block uninstall for an app that is not installed or enabled.
12861                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
12862                return false;
12863            }
12864            ps.setBlockUninstall(blockUninstall, userId);
12865            mSettings.writePackageRestrictionsLPr(userId);
12866        }
12867        return true;
12868    }
12869
12870    @Override
12871    public boolean getBlockUninstallForUser(String packageName, int userId) {
12872        synchronized (mPackages) {
12873            PackageSetting ps = mSettings.mPackages.get(packageName);
12874            if (ps == null) {
12875                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
12876                return false;
12877            }
12878            return ps.getBlockUninstall(userId);
12879        }
12880    }
12881
12882    /*
12883     * This method handles package deletion in general
12884     */
12885    private boolean deletePackageLI(String packageName, UserHandle user,
12886            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
12887            int flags, PackageRemovedInfo outInfo,
12888            boolean writeSettings) {
12889        if (packageName == null) {
12890            Slog.w(TAG, "Attempt to delete null packageName.");
12891            return false;
12892        }
12893        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
12894        PackageSetting ps;
12895        boolean dataOnly = false;
12896        int removeUser = -1;
12897        int appId = -1;
12898        synchronized (mPackages) {
12899            ps = mSettings.mPackages.get(packageName);
12900            if (ps == null) {
12901                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12902                return false;
12903            }
12904            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
12905                    && user.getIdentifier() != UserHandle.USER_ALL) {
12906                // The caller is asking that the package only be deleted for a single
12907                // user.  To do this, we just mark its uninstalled state and delete
12908                // its data.  If this is a system app, we only allow this to happen if
12909                // they have set the special DELETE_SYSTEM_APP which requests different
12910                // semantics than normal for uninstalling system apps.
12911                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
12912                ps.setUserState(user.getIdentifier(),
12913                        COMPONENT_ENABLED_STATE_DEFAULT,
12914                        false, //installed
12915                        true,  //stopped
12916                        true,  //notLaunched
12917                        false, //hidden
12918                        null, null, null,
12919                        false, // blockUninstall
12920                        INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
12921                if (!isSystemApp(ps)) {
12922                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
12923                        // Other user still have this package installed, so all
12924                        // we need to do is clear this user's data and save that
12925                        // it is uninstalled.
12926                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
12927                        removeUser = user.getIdentifier();
12928                        appId = ps.appId;
12929                        scheduleWritePackageRestrictionsLocked(removeUser);
12930                    } else {
12931                        // We need to set it back to 'installed' so the uninstall
12932                        // broadcasts will be sent correctly.
12933                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
12934                        ps.setInstalled(true, user.getIdentifier());
12935                    }
12936                } else {
12937                    // This is a system app, so we assume that the
12938                    // other users still have this package installed, so all
12939                    // we need to do is clear this user's data and save that
12940                    // it is uninstalled.
12941                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
12942                    removeUser = user.getIdentifier();
12943                    appId = ps.appId;
12944                    scheduleWritePackageRestrictionsLocked(removeUser);
12945                }
12946            }
12947        }
12948
12949        if (removeUser >= 0) {
12950            // From above, we determined that we are deleting this only
12951            // for a single user.  Continue the work here.
12952            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
12953            if (outInfo != null) {
12954                outInfo.removedPackage = packageName;
12955                outInfo.removedAppId = appId;
12956                outInfo.removedUsers = new int[] {removeUser};
12957            }
12958            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
12959            removeKeystoreDataIfNeeded(removeUser, appId);
12960            schedulePackageCleaning(packageName, removeUser, false);
12961            synchronized (mPackages) {
12962                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
12963                    scheduleWritePackageRestrictionsLocked(removeUser);
12964                }
12965                revokeRuntimePermissionsAndClearAllFlagsLocked(ps.getPermissionsState(),
12966                        removeUser);
12967            }
12968            return true;
12969        }
12970
12971        if (dataOnly) {
12972            // Delete application data first
12973            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
12974            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
12975            return true;
12976        }
12977
12978        boolean ret = false;
12979        if (isSystemApp(ps)) {
12980            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
12981            // When an updated system application is deleted we delete the existing resources as well and
12982            // fall back to existing code in system partition
12983            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
12984                    flags, outInfo, writeSettings);
12985        } else {
12986            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
12987            // Kill application pre-emptively especially for apps on sd.
12988            killApplication(packageName, ps.appId, "uninstall pkg");
12989            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
12990                    allUserHandles, perUserInstalled,
12991                    outInfo, writeSettings);
12992        }
12993
12994        return ret;
12995    }
12996
12997    private final class ClearStorageConnection implements ServiceConnection {
12998        IMediaContainerService mContainerService;
12999
13000        @Override
13001        public void onServiceConnected(ComponentName name, IBinder service) {
13002            synchronized (this) {
13003                mContainerService = IMediaContainerService.Stub.asInterface(service);
13004                notifyAll();
13005            }
13006        }
13007
13008        @Override
13009        public void onServiceDisconnected(ComponentName name) {
13010        }
13011    }
13012
13013    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
13014        final boolean mounted;
13015        if (Environment.isExternalStorageEmulated()) {
13016            mounted = true;
13017        } else {
13018            final String status = Environment.getExternalStorageState();
13019
13020            mounted = status.equals(Environment.MEDIA_MOUNTED)
13021                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13022        }
13023
13024        if (!mounted) {
13025            return;
13026        }
13027
13028        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13029        int[] users;
13030        if (userId == UserHandle.USER_ALL) {
13031            users = sUserManager.getUserIds();
13032        } else {
13033            users = new int[] { userId };
13034        }
13035        final ClearStorageConnection conn = new ClearStorageConnection();
13036        if (mContext.bindServiceAsUser(
13037                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
13038            try {
13039                for (int curUser : users) {
13040                    long timeout = SystemClock.uptimeMillis() + 5000;
13041                    synchronized (conn) {
13042                        long now = SystemClock.uptimeMillis();
13043                        while (conn.mContainerService == null && now < timeout) {
13044                            try {
13045                                conn.wait(timeout - now);
13046                            } catch (InterruptedException e) {
13047                            }
13048                        }
13049                    }
13050                    if (conn.mContainerService == null) {
13051                        return;
13052                    }
13053
13054                    final UserEnvironment userEnv = new UserEnvironment(curUser);
13055                    clearDirectory(conn.mContainerService,
13056                            userEnv.buildExternalStorageAppCacheDirs(packageName));
13057                    if (allData) {
13058                        clearDirectory(conn.mContainerService,
13059                                userEnv.buildExternalStorageAppDataDirs(packageName));
13060                        clearDirectory(conn.mContainerService,
13061                                userEnv.buildExternalStorageAppMediaDirs(packageName));
13062                    }
13063                }
13064            } finally {
13065                mContext.unbindService(conn);
13066            }
13067        }
13068    }
13069
13070    @Override
13071    public void clearApplicationUserData(final String packageName,
13072            final IPackageDataObserver observer, final int userId) {
13073        mContext.enforceCallingOrSelfPermission(
13074                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
13075        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
13076        // Queue up an async operation since the package deletion may take a little while.
13077        mHandler.post(new Runnable() {
13078            public void run() {
13079                mHandler.removeCallbacks(this);
13080                final boolean succeeded;
13081                synchronized (mInstallLock) {
13082                    succeeded = clearApplicationUserDataLI(packageName, userId);
13083                }
13084                clearExternalStorageDataSync(packageName, userId, true);
13085                if (succeeded) {
13086                    // invoke DeviceStorageMonitor's update method to clear any notifications
13087                    DeviceStorageMonitorInternal
13088                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13089                    if (dsm != null) {
13090                        dsm.checkMemory();
13091                    }
13092                }
13093                if(observer != null) {
13094                    try {
13095                        observer.onRemoveCompleted(packageName, succeeded);
13096                    } catch (RemoteException e) {
13097                        Log.i(TAG, "Observer no longer exists.");
13098                    }
13099                } //end if observer
13100            } //end run
13101        });
13102    }
13103
13104    private boolean clearApplicationUserDataLI(String packageName, int userId) {
13105        if (packageName == null) {
13106            Slog.w(TAG, "Attempt to delete null packageName.");
13107            return false;
13108        }
13109
13110        // Try finding details about the requested package
13111        PackageParser.Package pkg;
13112        synchronized (mPackages) {
13113            pkg = mPackages.get(packageName);
13114            if (pkg == null) {
13115                final PackageSetting ps = mSettings.mPackages.get(packageName);
13116                if (ps != null) {
13117                    pkg = ps.pkg;
13118                }
13119            }
13120
13121            if (pkg == null) {
13122                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13123                return false;
13124            }
13125
13126            PackageSetting ps = (PackageSetting) pkg.mExtras;
13127            PermissionsState permissionsState = ps.getPermissionsState();
13128            revokeRuntimePermissionsAndClearUserSetFlagsLocked(permissionsState, userId);
13129        }
13130
13131        // Always delete data directories for package, even if we found no other
13132        // record of app. This helps users recover from UID mismatches without
13133        // resorting to a full data wipe.
13134        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
13135        if (retCode < 0) {
13136            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
13137            return false;
13138        }
13139
13140        final int appId = pkg.applicationInfo.uid;
13141        removeKeystoreDataIfNeeded(userId, appId);
13142
13143        // Create a native library symlink only if we have native libraries
13144        // and if the native libraries are 32 bit libraries. We do not provide
13145        // this symlink for 64 bit libraries.
13146        if (pkg.applicationInfo.primaryCpuAbi != null &&
13147                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
13148            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
13149            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
13150                    nativeLibPath, userId) < 0) {
13151                Slog.w(TAG, "Failed linking native library dir");
13152                return false;
13153            }
13154        }
13155
13156        return true;
13157    }
13158
13159
13160    /**
13161     * Revokes granted runtime permissions and clears resettable flags
13162     * which are flags that can be set by a user interaction.
13163     *
13164     * @param permissionsState The permission state to reset.
13165     * @param userId The device user for which to do a reset.
13166     */
13167    private void revokeRuntimePermissionsAndClearUserSetFlagsLocked(
13168            PermissionsState permissionsState, int userId) {
13169        final int userSetFlags = PackageManager.FLAG_PERMISSION_USER_SET
13170                | PackageManager.FLAG_PERMISSION_USER_FIXED
13171                | PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13172
13173        revokeRuntimePermissionsAndClearFlagsLocked(permissionsState, userId, userSetFlags);
13174    }
13175
13176    /**
13177     * Revokes granted runtime permissions and clears all flags.
13178     *
13179     * @param permissionsState The permission state to reset.
13180     * @param userId The device user for which to do a reset.
13181     */
13182    private void revokeRuntimePermissionsAndClearAllFlagsLocked(
13183            PermissionsState permissionsState, int userId) {
13184        revokeRuntimePermissionsAndClearFlagsLocked(permissionsState, userId,
13185                PackageManager.MASK_PERMISSION_FLAGS);
13186    }
13187
13188    /**
13189     * Revokes granted runtime permissions and clears certain flags.
13190     *
13191     * @param permissionsState The permission state to reset.
13192     * @param userId The device user for which to do a reset.
13193     * @param flags The flags that is going to be reset.
13194     */
13195    private void revokeRuntimePermissionsAndClearFlagsLocked(
13196            PermissionsState permissionsState, final int userId, int flags) {
13197        boolean needsWrite = false;
13198
13199        for (PermissionState state : permissionsState.getRuntimePermissionStates(userId)) {
13200            BasePermission bp = mSettings.mPermissions.get(state.getName());
13201            if (bp != null) {
13202                permissionsState.revokeRuntimePermission(bp, userId);
13203                permissionsState.updatePermissionFlags(bp, userId, flags, 0);
13204                needsWrite = true;
13205            }
13206        }
13207
13208        // Ensure default permissions are never cleared.
13209        mHandler.post(new Runnable() {
13210            @Override
13211            public void run() {
13212                mDefaultPermissionPolicy.grantDefaultPermissions(userId);
13213            }
13214        });
13215
13216        if (needsWrite) {
13217            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
13218        }
13219    }
13220
13221    /**
13222     * Remove entries from the keystore daemon. Will only remove it if the
13223     * {@code appId} is valid.
13224     */
13225    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
13226        if (appId < 0) {
13227            return;
13228        }
13229
13230        final KeyStore keyStore = KeyStore.getInstance();
13231        if (keyStore != null) {
13232            if (userId == UserHandle.USER_ALL) {
13233                for (final int individual : sUserManager.getUserIds()) {
13234                    keyStore.clearUid(UserHandle.getUid(individual, appId));
13235                }
13236            } else {
13237                keyStore.clearUid(UserHandle.getUid(userId, appId));
13238            }
13239        } else {
13240            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
13241        }
13242    }
13243
13244    @Override
13245    public void deleteApplicationCacheFiles(final String packageName,
13246            final IPackageDataObserver observer) {
13247        mContext.enforceCallingOrSelfPermission(
13248                android.Manifest.permission.DELETE_CACHE_FILES, null);
13249        // Queue up an async operation since the package deletion may take a little while.
13250        final int userId = UserHandle.getCallingUserId();
13251        mHandler.post(new Runnable() {
13252            public void run() {
13253                mHandler.removeCallbacks(this);
13254                final boolean succeded;
13255                synchronized (mInstallLock) {
13256                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
13257                }
13258                clearExternalStorageDataSync(packageName, userId, false);
13259                if (observer != null) {
13260                    try {
13261                        observer.onRemoveCompleted(packageName, succeded);
13262                    } catch (RemoteException e) {
13263                        Log.i(TAG, "Observer no longer exists.");
13264                    }
13265                } //end if observer
13266            } //end run
13267        });
13268    }
13269
13270    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
13271        if (packageName == null) {
13272            Slog.w(TAG, "Attempt to delete null packageName.");
13273            return false;
13274        }
13275        PackageParser.Package p;
13276        synchronized (mPackages) {
13277            p = mPackages.get(packageName);
13278        }
13279        if (p == null) {
13280            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13281            return false;
13282        }
13283        final ApplicationInfo applicationInfo = p.applicationInfo;
13284        if (applicationInfo == null) {
13285            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13286            return false;
13287        }
13288        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
13289        if (retCode < 0) {
13290            Slog.w(TAG, "Couldn't remove cache files for package: "
13291                       + packageName + " u" + userId);
13292            return false;
13293        }
13294        return true;
13295    }
13296
13297    @Override
13298    public void getPackageSizeInfo(final String packageName, int userHandle,
13299            final IPackageStatsObserver observer) {
13300        mContext.enforceCallingOrSelfPermission(
13301                android.Manifest.permission.GET_PACKAGE_SIZE, null);
13302        if (packageName == null) {
13303            throw new IllegalArgumentException("Attempt to get size of null packageName");
13304        }
13305
13306        PackageStats stats = new PackageStats(packageName, userHandle);
13307
13308        /*
13309         * Queue up an async operation since the package measurement may take a
13310         * little while.
13311         */
13312        Message msg = mHandler.obtainMessage(INIT_COPY);
13313        msg.obj = new MeasureParams(stats, observer);
13314        mHandler.sendMessage(msg);
13315    }
13316
13317    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
13318            PackageStats pStats) {
13319        if (packageName == null) {
13320            Slog.w(TAG, "Attempt to get size of null packageName.");
13321            return false;
13322        }
13323        PackageParser.Package p;
13324        boolean dataOnly = false;
13325        String libDirRoot = null;
13326        String asecPath = null;
13327        PackageSetting ps = null;
13328        synchronized (mPackages) {
13329            p = mPackages.get(packageName);
13330            ps = mSettings.mPackages.get(packageName);
13331            if(p == null) {
13332                dataOnly = true;
13333                if((ps == null) || (ps.pkg == null)) {
13334                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13335                    return false;
13336                }
13337                p = ps.pkg;
13338            }
13339            if (ps != null) {
13340                libDirRoot = ps.legacyNativeLibraryPathString;
13341            }
13342            if (p != null && (isExternal(p) || p.isForwardLocked())) {
13343                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
13344                if (secureContainerId != null) {
13345                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
13346                }
13347            }
13348        }
13349        String publicSrcDir = null;
13350        if(!dataOnly) {
13351            final ApplicationInfo applicationInfo = p.applicationInfo;
13352            if (applicationInfo == null) {
13353                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13354                return false;
13355            }
13356            if (p.isForwardLocked()) {
13357                publicSrcDir = applicationInfo.getBaseResourcePath();
13358            }
13359        }
13360        // TODO: extend to measure size of split APKs
13361        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
13362        // not just the first level.
13363        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
13364        // just the primary.
13365        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
13366        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath,
13367                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
13368        if (res < 0) {
13369            return false;
13370        }
13371
13372        // Fix-up for forward-locked applications in ASEC containers.
13373        if (!isExternal(p)) {
13374            pStats.codeSize += pStats.externalCodeSize;
13375            pStats.externalCodeSize = 0L;
13376        }
13377
13378        return true;
13379    }
13380
13381
13382    @Override
13383    public void addPackageToPreferred(String packageName) {
13384        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
13385    }
13386
13387    @Override
13388    public void removePackageFromPreferred(String packageName) {
13389        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
13390    }
13391
13392    @Override
13393    public List<PackageInfo> getPreferredPackages(int flags) {
13394        return new ArrayList<PackageInfo>();
13395    }
13396
13397    private int getUidTargetSdkVersionLockedLPr(int uid) {
13398        Object obj = mSettings.getUserIdLPr(uid);
13399        if (obj instanceof SharedUserSetting) {
13400            final SharedUserSetting sus = (SharedUserSetting) obj;
13401            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
13402            final Iterator<PackageSetting> it = sus.packages.iterator();
13403            while (it.hasNext()) {
13404                final PackageSetting ps = it.next();
13405                if (ps.pkg != null) {
13406                    int v = ps.pkg.applicationInfo.targetSdkVersion;
13407                    if (v < vers) vers = v;
13408                }
13409            }
13410            return vers;
13411        } else if (obj instanceof PackageSetting) {
13412            final PackageSetting ps = (PackageSetting) obj;
13413            if (ps.pkg != null) {
13414                return ps.pkg.applicationInfo.targetSdkVersion;
13415            }
13416        }
13417        return Build.VERSION_CODES.CUR_DEVELOPMENT;
13418    }
13419
13420    @Override
13421    public void addPreferredActivity(IntentFilter filter, int match,
13422            ComponentName[] set, ComponentName activity, int userId) {
13423        addPreferredActivityInternal(filter, match, set, activity, true, userId,
13424                "Adding preferred");
13425    }
13426
13427    private void addPreferredActivityInternal(IntentFilter filter, int match,
13428            ComponentName[] set, ComponentName activity, boolean always, int userId,
13429            String opname) {
13430        // writer
13431        int callingUid = Binder.getCallingUid();
13432        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
13433        if (filter.countActions() == 0) {
13434            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13435            return;
13436        }
13437        synchronized (mPackages) {
13438            if (mContext.checkCallingOrSelfPermission(
13439                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13440                    != PackageManager.PERMISSION_GRANTED) {
13441                if (getUidTargetSdkVersionLockedLPr(callingUid)
13442                        < Build.VERSION_CODES.FROYO) {
13443                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
13444                            + callingUid);
13445                    return;
13446                }
13447                mContext.enforceCallingOrSelfPermission(
13448                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13449            }
13450
13451            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
13452            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
13453                    + userId + ":");
13454            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13455            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
13456            scheduleWritePackageRestrictionsLocked(userId);
13457        }
13458    }
13459
13460    @Override
13461    public void replacePreferredActivity(IntentFilter filter, int match,
13462            ComponentName[] set, ComponentName activity, int userId) {
13463        if (filter.countActions() != 1) {
13464            throw new IllegalArgumentException(
13465                    "replacePreferredActivity expects filter to have only 1 action.");
13466        }
13467        if (filter.countDataAuthorities() != 0
13468                || filter.countDataPaths() != 0
13469                || filter.countDataSchemes() > 1
13470                || filter.countDataTypes() != 0) {
13471            throw new IllegalArgumentException(
13472                    "replacePreferredActivity expects filter to have no data authorities, " +
13473                    "paths, or types; and at most one scheme.");
13474        }
13475
13476        final int callingUid = Binder.getCallingUid();
13477        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
13478        synchronized (mPackages) {
13479            if (mContext.checkCallingOrSelfPermission(
13480                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13481                    != PackageManager.PERMISSION_GRANTED) {
13482                if (getUidTargetSdkVersionLockedLPr(callingUid)
13483                        < Build.VERSION_CODES.FROYO) {
13484                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
13485                            + Binder.getCallingUid());
13486                    return;
13487                }
13488                mContext.enforceCallingOrSelfPermission(
13489                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13490            }
13491
13492            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13493            if (pir != null) {
13494                // Get all of the existing entries that exactly match this filter.
13495                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
13496                if (existing != null && existing.size() == 1) {
13497                    PreferredActivity cur = existing.get(0);
13498                    if (DEBUG_PREFERRED) {
13499                        Slog.i(TAG, "Checking replace of preferred:");
13500                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13501                        if (!cur.mPref.mAlways) {
13502                            Slog.i(TAG, "  -- CUR; not mAlways!");
13503                        } else {
13504                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
13505                            Slog.i(TAG, "  -- CUR: mSet="
13506                                    + Arrays.toString(cur.mPref.mSetComponents));
13507                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
13508                            Slog.i(TAG, "  -- NEW: mMatch="
13509                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
13510                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
13511                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
13512                        }
13513                    }
13514                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
13515                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
13516                            && cur.mPref.sameSet(set)) {
13517                        // Setting the preferred activity to what it happens to be already
13518                        if (DEBUG_PREFERRED) {
13519                            Slog.i(TAG, "Replacing with same preferred activity "
13520                                    + cur.mPref.mShortComponent + " for user "
13521                                    + userId + ":");
13522                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13523                        }
13524                        return;
13525                    }
13526                }
13527
13528                if (existing != null) {
13529                    if (DEBUG_PREFERRED) {
13530                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
13531                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13532                    }
13533                    for (int i = 0; i < existing.size(); i++) {
13534                        PreferredActivity pa = existing.get(i);
13535                        if (DEBUG_PREFERRED) {
13536                            Slog.i(TAG, "Removing existing preferred activity "
13537                                    + pa.mPref.mComponent + ":");
13538                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
13539                        }
13540                        pir.removeFilter(pa);
13541                    }
13542                }
13543            }
13544            addPreferredActivityInternal(filter, match, set, activity, true, userId,
13545                    "Replacing preferred");
13546        }
13547    }
13548
13549    @Override
13550    public void clearPackagePreferredActivities(String packageName) {
13551        final int uid = Binder.getCallingUid();
13552        // writer
13553        synchronized (mPackages) {
13554            PackageParser.Package pkg = mPackages.get(packageName);
13555            if (pkg == null || pkg.applicationInfo.uid != uid) {
13556                if (mContext.checkCallingOrSelfPermission(
13557                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13558                        != PackageManager.PERMISSION_GRANTED) {
13559                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
13560                            < Build.VERSION_CODES.FROYO) {
13561                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
13562                                + Binder.getCallingUid());
13563                        return;
13564                    }
13565                    mContext.enforceCallingOrSelfPermission(
13566                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13567                }
13568            }
13569
13570            int user = UserHandle.getCallingUserId();
13571            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
13572                scheduleWritePackageRestrictionsLocked(user);
13573            }
13574        }
13575    }
13576
13577    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13578    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
13579        ArrayList<PreferredActivity> removed = null;
13580        boolean changed = false;
13581        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13582            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
13583            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13584            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
13585                continue;
13586            }
13587            Iterator<PreferredActivity> it = pir.filterIterator();
13588            while (it.hasNext()) {
13589                PreferredActivity pa = it.next();
13590                // Mark entry for removal only if it matches the package name
13591                // and the entry is of type "always".
13592                if (packageName == null ||
13593                        (pa.mPref.mComponent.getPackageName().equals(packageName)
13594                                && pa.mPref.mAlways)) {
13595                    if (removed == null) {
13596                        removed = new ArrayList<PreferredActivity>();
13597                    }
13598                    removed.add(pa);
13599                }
13600            }
13601            if (removed != null) {
13602                for (int j=0; j<removed.size(); j++) {
13603                    PreferredActivity pa = removed.get(j);
13604                    pir.removeFilter(pa);
13605                }
13606                changed = true;
13607            }
13608        }
13609        return changed;
13610    }
13611
13612    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13613    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
13614        if (userId == UserHandle.USER_ALL) {
13615            if (mSettings.removeIntentFilterVerificationLPw(packageName,
13616                    sUserManager.getUserIds())) {
13617                for (int oneUserId : sUserManager.getUserIds()) {
13618                    scheduleWritePackageRestrictionsLocked(oneUserId);
13619                }
13620            }
13621        } else {
13622            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
13623                scheduleWritePackageRestrictionsLocked(userId);
13624            }
13625        }
13626    }
13627
13628
13629    void clearDefaultBrowserIfNeeded(String packageName) {
13630        for (int oneUserId : sUserManager.getUserIds()) {
13631            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
13632            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
13633            if (packageName.equals(defaultBrowserPackageName)) {
13634                setDefaultBrowserPackageName(null, oneUserId);
13635            }
13636        }
13637    }
13638
13639    @Override
13640    public void resetPreferredActivities(int userId) {
13641        mContext.enforceCallingOrSelfPermission(
13642                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13643        // writer
13644        synchronized (mPackages) {
13645            clearPackagePreferredActivitiesLPw(null, userId);
13646            mSettings.applyDefaultPreferredAppsLPw(this, userId);
13647            applyFactoryDefaultBrowserLPw(userId);
13648
13649            scheduleWritePackageRestrictionsLocked(userId);
13650        }
13651    }
13652
13653    @Override
13654    public int getPreferredActivities(List<IntentFilter> outFilters,
13655            List<ComponentName> outActivities, String packageName) {
13656
13657        int num = 0;
13658        final int userId = UserHandle.getCallingUserId();
13659        // reader
13660        synchronized (mPackages) {
13661            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13662            if (pir != null) {
13663                final Iterator<PreferredActivity> it = pir.filterIterator();
13664                while (it.hasNext()) {
13665                    final PreferredActivity pa = it.next();
13666                    if (packageName == null
13667                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
13668                                    && pa.mPref.mAlways)) {
13669                        if (outFilters != null) {
13670                            outFilters.add(new IntentFilter(pa));
13671                        }
13672                        if (outActivities != null) {
13673                            outActivities.add(pa.mPref.mComponent);
13674                        }
13675                    }
13676                }
13677            }
13678        }
13679
13680        return num;
13681    }
13682
13683    @Override
13684    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
13685            int userId) {
13686        int callingUid = Binder.getCallingUid();
13687        if (callingUid != Process.SYSTEM_UID) {
13688            throw new SecurityException(
13689                    "addPersistentPreferredActivity can only be run by the system");
13690        }
13691        if (filter.countActions() == 0) {
13692            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13693            return;
13694        }
13695        synchronized (mPackages) {
13696            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
13697                    " :");
13698            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13699            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
13700                    new PersistentPreferredActivity(filter, activity));
13701            scheduleWritePackageRestrictionsLocked(userId);
13702        }
13703    }
13704
13705    @Override
13706    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
13707        int callingUid = Binder.getCallingUid();
13708        if (callingUid != Process.SYSTEM_UID) {
13709            throw new SecurityException(
13710                    "clearPackagePersistentPreferredActivities can only be run by the system");
13711        }
13712        ArrayList<PersistentPreferredActivity> removed = null;
13713        boolean changed = false;
13714        synchronized (mPackages) {
13715            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
13716                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
13717                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
13718                        .valueAt(i);
13719                if (userId != thisUserId) {
13720                    continue;
13721                }
13722                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
13723                while (it.hasNext()) {
13724                    PersistentPreferredActivity ppa = it.next();
13725                    // Mark entry for removal only if it matches the package name.
13726                    if (ppa.mComponent.getPackageName().equals(packageName)) {
13727                        if (removed == null) {
13728                            removed = new ArrayList<PersistentPreferredActivity>();
13729                        }
13730                        removed.add(ppa);
13731                    }
13732                }
13733                if (removed != null) {
13734                    for (int j=0; j<removed.size(); j++) {
13735                        PersistentPreferredActivity ppa = removed.get(j);
13736                        ppir.removeFilter(ppa);
13737                    }
13738                    changed = true;
13739                }
13740            }
13741
13742            if (changed) {
13743                scheduleWritePackageRestrictionsLocked(userId);
13744            }
13745        }
13746    }
13747
13748    /**
13749     * Common machinery for picking apart a restored XML blob and passing
13750     * it to a caller-supplied functor to be applied to the running system.
13751     */
13752    private void restoreFromXml(XmlPullParser parser, int userId,
13753            String expectedStartTag, BlobXmlRestorer functor)
13754            throws IOException, XmlPullParserException {
13755        int type;
13756        while ((type = parser.next()) != XmlPullParser.START_TAG
13757                && type != XmlPullParser.END_DOCUMENT) {
13758        }
13759        if (type != XmlPullParser.START_TAG) {
13760            // oops didn't find a start tag?!
13761            if (DEBUG_BACKUP) {
13762                Slog.e(TAG, "Didn't find start tag during restore");
13763            }
13764            return;
13765        }
13766
13767        // this is supposed to be TAG_PREFERRED_BACKUP
13768        if (!expectedStartTag.equals(parser.getName())) {
13769            if (DEBUG_BACKUP) {
13770                Slog.e(TAG, "Found unexpected tag " + parser.getName());
13771            }
13772            return;
13773        }
13774
13775        // skip interfering stuff, then we're aligned with the backing implementation
13776        while ((type = parser.next()) == XmlPullParser.TEXT) { }
13777        functor.apply(parser, userId);
13778    }
13779
13780    private interface BlobXmlRestorer {
13781        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
13782    }
13783
13784    /**
13785     * Non-Binder method, support for the backup/restore mechanism: write the
13786     * full set of preferred activities in its canonical XML format.  Returns the
13787     * XML output as a byte array, or null if there is none.
13788     */
13789    @Override
13790    public byte[] getPreferredActivityBackup(int userId) {
13791        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13792            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
13793        }
13794
13795        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13796        try {
13797            final XmlSerializer serializer = new FastXmlSerializer();
13798            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13799            serializer.startDocument(null, true);
13800            serializer.startTag(null, TAG_PREFERRED_BACKUP);
13801
13802            synchronized (mPackages) {
13803                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
13804            }
13805
13806            serializer.endTag(null, TAG_PREFERRED_BACKUP);
13807            serializer.endDocument();
13808            serializer.flush();
13809        } catch (Exception e) {
13810            if (DEBUG_BACKUP) {
13811                Slog.e(TAG, "Unable to write preferred activities for backup", e);
13812            }
13813            return null;
13814        }
13815
13816        return dataStream.toByteArray();
13817    }
13818
13819    @Override
13820    public void restorePreferredActivities(byte[] backup, int userId) {
13821        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13822            throw new SecurityException("Only the system may call restorePreferredActivities()");
13823        }
13824
13825        try {
13826            final XmlPullParser parser = Xml.newPullParser();
13827            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13828            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
13829                    new BlobXmlRestorer() {
13830                        @Override
13831                        public void apply(XmlPullParser parser, int userId)
13832                                throws XmlPullParserException, IOException {
13833                            synchronized (mPackages) {
13834                                mSettings.readPreferredActivitiesLPw(parser, userId);
13835                            }
13836                        }
13837                    } );
13838        } catch (Exception e) {
13839            if (DEBUG_BACKUP) {
13840                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
13841            }
13842        }
13843    }
13844
13845    /**
13846     * Non-Binder method, support for the backup/restore mechanism: write the
13847     * default browser (etc) settings in its canonical XML format.  Returns the default
13848     * browser XML representation as a byte array, or null if there is none.
13849     */
13850    @Override
13851    public byte[] getDefaultAppsBackup(int userId) {
13852        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13853            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
13854        }
13855
13856        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13857        try {
13858            final XmlSerializer serializer = new FastXmlSerializer();
13859            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13860            serializer.startDocument(null, true);
13861            serializer.startTag(null, TAG_DEFAULT_APPS);
13862
13863            synchronized (mPackages) {
13864                mSettings.writeDefaultAppsLPr(serializer, userId);
13865            }
13866
13867            serializer.endTag(null, TAG_DEFAULT_APPS);
13868            serializer.endDocument();
13869            serializer.flush();
13870        } catch (Exception e) {
13871            if (DEBUG_BACKUP) {
13872                Slog.e(TAG, "Unable to write default apps for backup", e);
13873            }
13874            return null;
13875        }
13876
13877        return dataStream.toByteArray();
13878    }
13879
13880    @Override
13881    public void restoreDefaultApps(byte[] backup, int userId) {
13882        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13883            throw new SecurityException("Only the system may call restoreDefaultApps()");
13884        }
13885
13886        try {
13887            final XmlPullParser parser = Xml.newPullParser();
13888            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13889            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
13890                    new BlobXmlRestorer() {
13891                        @Override
13892                        public void apply(XmlPullParser parser, int userId)
13893                                throws XmlPullParserException, IOException {
13894                            synchronized (mPackages) {
13895                                mSettings.readDefaultAppsLPw(parser, userId);
13896                            }
13897                        }
13898                    } );
13899        } catch (Exception e) {
13900            if (DEBUG_BACKUP) {
13901                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
13902            }
13903        }
13904    }
13905
13906    @Override
13907    public byte[] getIntentFilterVerificationBackup(int userId) {
13908        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13909            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
13910        }
13911
13912        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13913        try {
13914            final XmlSerializer serializer = new FastXmlSerializer();
13915            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13916            serializer.startDocument(null, true);
13917            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
13918
13919            synchronized (mPackages) {
13920                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
13921            }
13922
13923            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
13924            serializer.endDocument();
13925            serializer.flush();
13926        } catch (Exception e) {
13927            if (DEBUG_BACKUP) {
13928                Slog.e(TAG, "Unable to write default apps for backup", e);
13929            }
13930            return null;
13931        }
13932
13933        return dataStream.toByteArray();
13934    }
13935
13936    @Override
13937    public void restoreIntentFilterVerification(byte[] backup, int userId) {
13938        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13939            throw new SecurityException("Only the system may call restorePreferredActivities()");
13940        }
13941
13942        try {
13943            final XmlPullParser parser = Xml.newPullParser();
13944            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13945            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
13946                    new BlobXmlRestorer() {
13947                        @Override
13948                        public void apply(XmlPullParser parser, int userId)
13949                                throws XmlPullParserException, IOException {
13950                            synchronized (mPackages) {
13951                                mSettings.readAllDomainVerificationsLPr(parser, userId);
13952                                mSettings.writeLPr();
13953                            }
13954                        }
13955                    } );
13956        } catch (Exception e) {
13957            if (DEBUG_BACKUP) {
13958                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
13959            }
13960        }
13961    }
13962
13963    @Override
13964    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
13965            int sourceUserId, int targetUserId, int flags) {
13966        mContext.enforceCallingOrSelfPermission(
13967                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
13968        int callingUid = Binder.getCallingUid();
13969        enforceOwnerRights(ownerPackage, callingUid);
13970        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
13971        if (intentFilter.countActions() == 0) {
13972            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
13973            return;
13974        }
13975        synchronized (mPackages) {
13976            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
13977                    ownerPackage, targetUserId, flags);
13978            CrossProfileIntentResolver resolver =
13979                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
13980            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
13981            // We have all those whose filter is equal. Now checking if the rest is equal as well.
13982            if (existing != null) {
13983                int size = existing.size();
13984                for (int i = 0; i < size; i++) {
13985                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
13986                        return;
13987                    }
13988                }
13989            }
13990            resolver.addFilter(newFilter);
13991            scheduleWritePackageRestrictionsLocked(sourceUserId);
13992        }
13993    }
13994
13995    @Override
13996    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
13997        mContext.enforceCallingOrSelfPermission(
13998                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
13999        int callingUid = Binder.getCallingUid();
14000        enforceOwnerRights(ownerPackage, callingUid);
14001        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14002        synchronized (mPackages) {
14003            CrossProfileIntentResolver resolver =
14004                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14005            ArraySet<CrossProfileIntentFilter> set =
14006                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
14007            for (CrossProfileIntentFilter filter : set) {
14008                if (filter.getOwnerPackage().equals(ownerPackage)) {
14009                    resolver.removeFilter(filter);
14010                }
14011            }
14012            scheduleWritePackageRestrictionsLocked(sourceUserId);
14013        }
14014    }
14015
14016    // Enforcing that callingUid is owning pkg on userId
14017    private void enforceOwnerRights(String pkg, int callingUid) {
14018        // The system owns everything.
14019        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
14020            return;
14021        }
14022        int callingUserId = UserHandle.getUserId(callingUid);
14023        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
14024        if (pi == null) {
14025            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
14026                    + callingUserId);
14027        }
14028        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
14029            throw new SecurityException("Calling uid " + callingUid
14030                    + " does not own package " + pkg);
14031        }
14032    }
14033
14034    @Override
14035    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
14036        Intent intent = new Intent(Intent.ACTION_MAIN);
14037        intent.addCategory(Intent.CATEGORY_HOME);
14038
14039        final int callingUserId = UserHandle.getCallingUserId();
14040        List<ResolveInfo> list = queryIntentActivities(intent, null,
14041                PackageManager.GET_META_DATA, callingUserId);
14042        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
14043                true, false, false, callingUserId);
14044
14045        allHomeCandidates.clear();
14046        if (list != null) {
14047            for (ResolveInfo ri : list) {
14048                allHomeCandidates.add(ri);
14049            }
14050        }
14051        return (preferred == null || preferred.activityInfo == null)
14052                ? null
14053                : new ComponentName(preferred.activityInfo.packageName,
14054                        preferred.activityInfo.name);
14055    }
14056
14057    @Override
14058    public void setApplicationEnabledSetting(String appPackageName,
14059            int newState, int flags, int userId, String callingPackage) {
14060        if (!sUserManager.exists(userId)) return;
14061        if (callingPackage == null) {
14062            callingPackage = Integer.toString(Binder.getCallingUid());
14063        }
14064        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
14065    }
14066
14067    @Override
14068    public void setComponentEnabledSetting(ComponentName componentName,
14069            int newState, int flags, int userId) {
14070        if (!sUserManager.exists(userId)) return;
14071        setEnabledSetting(componentName.getPackageName(),
14072                componentName.getClassName(), newState, flags, userId, null);
14073    }
14074
14075    private void setEnabledSetting(final String packageName, String className, int newState,
14076            final int flags, int userId, String callingPackage) {
14077        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
14078              || newState == COMPONENT_ENABLED_STATE_ENABLED
14079              || newState == COMPONENT_ENABLED_STATE_DISABLED
14080              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
14081              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
14082            throw new IllegalArgumentException("Invalid new component state: "
14083                    + newState);
14084        }
14085        PackageSetting pkgSetting;
14086        final int uid = Binder.getCallingUid();
14087        final int permission = mContext.checkCallingOrSelfPermission(
14088                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14089        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
14090        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14091        boolean sendNow = false;
14092        boolean isApp = (className == null);
14093        String componentName = isApp ? packageName : className;
14094        int packageUid = -1;
14095        ArrayList<String> components;
14096
14097        // writer
14098        synchronized (mPackages) {
14099            pkgSetting = mSettings.mPackages.get(packageName);
14100            if (pkgSetting == null) {
14101                if (className == null) {
14102                    throw new IllegalArgumentException(
14103                            "Unknown package: " + packageName);
14104                }
14105                throw new IllegalArgumentException(
14106                        "Unknown component: " + packageName
14107                        + "/" + className);
14108            }
14109            // Allow root and verify that userId is not being specified by a different user
14110            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
14111                throw new SecurityException(
14112                        "Permission Denial: attempt to change component state from pid="
14113                        + Binder.getCallingPid()
14114                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
14115            }
14116            if (className == null) {
14117                // We're dealing with an application/package level state change
14118                if (pkgSetting.getEnabled(userId) == newState) {
14119                    // Nothing to do
14120                    return;
14121                }
14122                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
14123                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
14124                    // Don't care about who enables an app.
14125                    callingPackage = null;
14126                }
14127                pkgSetting.setEnabled(newState, userId, callingPackage);
14128                // pkgSetting.pkg.mSetEnabled = newState;
14129            } else {
14130                // We're dealing with a component level state change
14131                // First, verify that this is a valid class name.
14132                PackageParser.Package pkg = pkgSetting.pkg;
14133                if (pkg == null || !pkg.hasComponentClassName(className)) {
14134                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
14135                        throw new IllegalArgumentException("Component class " + className
14136                                + " does not exist in " + packageName);
14137                    } else {
14138                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
14139                                + className + " does not exist in " + packageName);
14140                    }
14141                }
14142                switch (newState) {
14143                case COMPONENT_ENABLED_STATE_ENABLED:
14144                    if (!pkgSetting.enableComponentLPw(className, userId)) {
14145                        return;
14146                    }
14147                    break;
14148                case COMPONENT_ENABLED_STATE_DISABLED:
14149                    if (!pkgSetting.disableComponentLPw(className, userId)) {
14150                        return;
14151                    }
14152                    break;
14153                case COMPONENT_ENABLED_STATE_DEFAULT:
14154                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
14155                        return;
14156                    }
14157                    break;
14158                default:
14159                    Slog.e(TAG, "Invalid new component state: " + newState);
14160                    return;
14161                }
14162            }
14163            scheduleWritePackageRestrictionsLocked(userId);
14164            components = mPendingBroadcasts.get(userId, packageName);
14165            final boolean newPackage = components == null;
14166            if (newPackage) {
14167                components = new ArrayList<String>();
14168            }
14169            if (!components.contains(componentName)) {
14170                components.add(componentName);
14171            }
14172            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
14173                sendNow = true;
14174                // Purge entry from pending broadcast list if another one exists already
14175                // since we are sending one right away.
14176                mPendingBroadcasts.remove(userId, packageName);
14177            } else {
14178                if (newPackage) {
14179                    mPendingBroadcasts.put(userId, packageName, components);
14180                }
14181                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
14182                    // Schedule a message
14183                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
14184                }
14185            }
14186        }
14187
14188        long callingId = Binder.clearCallingIdentity();
14189        try {
14190            if (sendNow) {
14191                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
14192                sendPackageChangedBroadcast(packageName,
14193                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
14194            }
14195        } finally {
14196            Binder.restoreCallingIdentity(callingId);
14197        }
14198    }
14199
14200    private void sendPackageChangedBroadcast(String packageName,
14201            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
14202        if (DEBUG_INSTALL)
14203            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
14204                    + componentNames);
14205        Bundle extras = new Bundle(4);
14206        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
14207        String nameList[] = new String[componentNames.size()];
14208        componentNames.toArray(nameList);
14209        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
14210        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
14211        extras.putInt(Intent.EXTRA_UID, packageUid);
14212        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
14213                new int[] {UserHandle.getUserId(packageUid)});
14214    }
14215
14216    @Override
14217    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
14218        if (!sUserManager.exists(userId)) return;
14219        final int uid = Binder.getCallingUid();
14220        final int permission = mContext.checkCallingOrSelfPermission(
14221                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14222        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14223        enforceCrossUserPermission(uid, userId, true, true, "stop package");
14224        // writer
14225        synchronized (mPackages) {
14226            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
14227                    allowedByPermission, uid, userId)) {
14228                scheduleWritePackageRestrictionsLocked(userId);
14229            }
14230        }
14231    }
14232
14233    @Override
14234    public String getInstallerPackageName(String packageName) {
14235        // reader
14236        synchronized (mPackages) {
14237            return mSettings.getInstallerPackageNameLPr(packageName);
14238        }
14239    }
14240
14241    @Override
14242    public int getApplicationEnabledSetting(String packageName, int userId) {
14243        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14244        int uid = Binder.getCallingUid();
14245        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
14246        // reader
14247        synchronized (mPackages) {
14248            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
14249        }
14250    }
14251
14252    @Override
14253    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
14254        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14255        int uid = Binder.getCallingUid();
14256        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
14257        // reader
14258        synchronized (mPackages) {
14259            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
14260        }
14261    }
14262
14263    @Override
14264    public void enterSafeMode() {
14265        enforceSystemOrRoot("Only the system can request entering safe mode");
14266
14267        if (!mSystemReady) {
14268            mSafeMode = true;
14269        }
14270    }
14271
14272    @Override
14273    public void systemReady() {
14274        mSystemReady = true;
14275
14276        // Read the compatibilty setting when the system is ready.
14277        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
14278                mContext.getContentResolver(),
14279                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
14280        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
14281        if (DEBUG_SETTINGS) {
14282            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
14283        }
14284
14285        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
14286
14287        synchronized (mPackages) {
14288            // Verify that all of the preferred activity components actually
14289            // exist.  It is possible for applications to be updated and at
14290            // that point remove a previously declared activity component that
14291            // had been set as a preferred activity.  We try to clean this up
14292            // the next time we encounter that preferred activity, but it is
14293            // possible for the user flow to never be able to return to that
14294            // situation so here we do a sanity check to make sure we haven't
14295            // left any junk around.
14296            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
14297            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14298                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14299                removed.clear();
14300                for (PreferredActivity pa : pir.filterSet()) {
14301                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
14302                        removed.add(pa);
14303                    }
14304                }
14305                if (removed.size() > 0) {
14306                    for (int r=0; r<removed.size(); r++) {
14307                        PreferredActivity pa = removed.get(r);
14308                        Slog.w(TAG, "Removing dangling preferred activity: "
14309                                + pa.mPref.mComponent);
14310                        pir.removeFilter(pa);
14311                    }
14312                    mSettings.writePackageRestrictionsLPr(
14313                            mSettings.mPreferredActivities.keyAt(i));
14314                }
14315            }
14316
14317            for (int userId : UserManagerService.getInstance().getUserIds()) {
14318                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
14319                    grantPermissionsUserIds = ArrayUtils.appendInt(
14320                            grantPermissionsUserIds, userId);
14321                }
14322            }
14323        }
14324        sUserManager.systemReady();
14325
14326        // If we upgraded grant all default permissions before kicking off.
14327        for (int userId : grantPermissionsUserIds) {
14328            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
14329        }
14330
14331        // Kick off any messages waiting for system ready
14332        if (mPostSystemReadyMessages != null) {
14333            for (Message msg : mPostSystemReadyMessages) {
14334                msg.sendToTarget();
14335            }
14336            mPostSystemReadyMessages = null;
14337        }
14338
14339        // Watch for external volumes that come and go over time
14340        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14341        storage.registerListener(mStorageListener);
14342
14343        mInstallerService.systemReady();
14344        mPackageDexOptimizer.systemReady();
14345    }
14346
14347    @Override
14348    public boolean isSafeMode() {
14349        return mSafeMode;
14350    }
14351
14352    @Override
14353    public boolean hasSystemUidErrors() {
14354        return mHasSystemUidErrors;
14355    }
14356
14357    static String arrayToString(int[] array) {
14358        StringBuffer buf = new StringBuffer(128);
14359        buf.append('[');
14360        if (array != null) {
14361            for (int i=0; i<array.length; i++) {
14362                if (i > 0) buf.append(", ");
14363                buf.append(array[i]);
14364            }
14365        }
14366        buf.append(']');
14367        return buf.toString();
14368    }
14369
14370    static class DumpState {
14371        public static final int DUMP_LIBS = 1 << 0;
14372        public static final int DUMP_FEATURES = 1 << 1;
14373        public static final int DUMP_RESOLVERS = 1 << 2;
14374        public static final int DUMP_PERMISSIONS = 1 << 3;
14375        public static final int DUMP_PACKAGES = 1 << 4;
14376        public static final int DUMP_SHARED_USERS = 1 << 5;
14377        public static final int DUMP_MESSAGES = 1 << 6;
14378        public static final int DUMP_PROVIDERS = 1 << 7;
14379        public static final int DUMP_VERIFIERS = 1 << 8;
14380        public static final int DUMP_PREFERRED = 1 << 9;
14381        public static final int DUMP_PREFERRED_XML = 1 << 10;
14382        public static final int DUMP_KEYSETS = 1 << 11;
14383        public static final int DUMP_VERSION = 1 << 12;
14384        public static final int DUMP_INSTALLS = 1 << 13;
14385        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
14386        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
14387
14388        public static final int OPTION_SHOW_FILTERS = 1 << 0;
14389
14390        private int mTypes;
14391
14392        private int mOptions;
14393
14394        private boolean mTitlePrinted;
14395
14396        private SharedUserSetting mSharedUser;
14397
14398        public boolean isDumping(int type) {
14399            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
14400                return true;
14401            }
14402
14403            return (mTypes & type) != 0;
14404        }
14405
14406        public void setDump(int type) {
14407            mTypes |= type;
14408        }
14409
14410        public boolean isOptionEnabled(int option) {
14411            return (mOptions & option) != 0;
14412        }
14413
14414        public void setOptionEnabled(int option) {
14415            mOptions |= option;
14416        }
14417
14418        public boolean onTitlePrinted() {
14419            final boolean printed = mTitlePrinted;
14420            mTitlePrinted = true;
14421            return printed;
14422        }
14423
14424        public boolean getTitlePrinted() {
14425            return mTitlePrinted;
14426        }
14427
14428        public void setTitlePrinted(boolean enabled) {
14429            mTitlePrinted = enabled;
14430        }
14431
14432        public SharedUserSetting getSharedUser() {
14433            return mSharedUser;
14434        }
14435
14436        public void setSharedUser(SharedUserSetting user) {
14437            mSharedUser = user;
14438        }
14439    }
14440
14441    @Override
14442    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
14443        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
14444                != PackageManager.PERMISSION_GRANTED) {
14445            pw.println("Permission Denial: can't dump ActivityManager from from pid="
14446                    + Binder.getCallingPid()
14447                    + ", uid=" + Binder.getCallingUid()
14448                    + " without permission "
14449                    + android.Manifest.permission.DUMP);
14450            return;
14451        }
14452
14453        DumpState dumpState = new DumpState();
14454        boolean fullPreferred = false;
14455        boolean checkin = false;
14456
14457        String packageName = null;
14458        ArraySet<String> permissionNames = null;
14459
14460        int opti = 0;
14461        while (opti < args.length) {
14462            String opt = args[opti];
14463            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
14464                break;
14465            }
14466            opti++;
14467
14468            if ("-a".equals(opt)) {
14469                // Right now we only know how to print all.
14470            } else if ("-h".equals(opt)) {
14471                pw.println("Package manager dump options:");
14472                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
14473                pw.println("    --checkin: dump for a checkin");
14474                pw.println("    -f: print details of intent filters");
14475                pw.println("    -h: print this help");
14476                pw.println("  cmd may be one of:");
14477                pw.println("    l[ibraries]: list known shared libraries");
14478                pw.println("    f[ibraries]: list device features");
14479                pw.println("    k[eysets]: print known keysets");
14480                pw.println("    r[esolvers]: dump intent resolvers");
14481                pw.println("    perm[issions]: dump permissions");
14482                pw.println("    permission [name ...]: dump declaration and use of given permission");
14483                pw.println("    pref[erred]: print preferred package settings");
14484                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
14485                pw.println("    prov[iders]: dump content providers");
14486                pw.println("    p[ackages]: dump installed packages");
14487                pw.println("    s[hared-users]: dump shared user IDs");
14488                pw.println("    m[essages]: print collected runtime messages");
14489                pw.println("    v[erifiers]: print package verifier info");
14490                pw.println("    version: print database version info");
14491                pw.println("    write: write current settings now");
14492                pw.println("    <package.name>: info about given package");
14493                pw.println("    installs: details about install sessions");
14494                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
14495                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
14496                return;
14497            } else if ("--checkin".equals(opt)) {
14498                checkin = true;
14499            } else if ("-f".equals(opt)) {
14500                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14501            } else {
14502                pw.println("Unknown argument: " + opt + "; use -h for help");
14503            }
14504        }
14505
14506        // Is the caller requesting to dump a particular piece of data?
14507        if (opti < args.length) {
14508            String cmd = args[opti];
14509            opti++;
14510            // Is this a package name?
14511            if ("android".equals(cmd) || cmd.contains(".")) {
14512                packageName = cmd;
14513                // When dumping a single package, we always dump all of its
14514                // filter information since the amount of data will be reasonable.
14515                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14516            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
14517                dumpState.setDump(DumpState.DUMP_LIBS);
14518            } else if ("f".equals(cmd) || "features".equals(cmd)) {
14519                dumpState.setDump(DumpState.DUMP_FEATURES);
14520            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
14521                dumpState.setDump(DumpState.DUMP_RESOLVERS);
14522            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
14523                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
14524            } else if ("permission".equals(cmd)) {
14525                if (opti >= args.length) {
14526                    pw.println("Error: permission requires permission name");
14527                    return;
14528                }
14529                permissionNames = new ArraySet<>();
14530                while (opti < args.length) {
14531                    permissionNames.add(args[opti]);
14532                    opti++;
14533                }
14534                dumpState.setDump(DumpState.DUMP_PERMISSIONS
14535                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
14536            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
14537                dumpState.setDump(DumpState.DUMP_PREFERRED);
14538            } else if ("preferred-xml".equals(cmd)) {
14539                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
14540                if (opti < args.length && "--full".equals(args[opti])) {
14541                    fullPreferred = true;
14542                    opti++;
14543                }
14544            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
14545                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
14546            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
14547                dumpState.setDump(DumpState.DUMP_PACKAGES);
14548            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
14549                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
14550            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
14551                dumpState.setDump(DumpState.DUMP_PROVIDERS);
14552            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
14553                dumpState.setDump(DumpState.DUMP_MESSAGES);
14554            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
14555                dumpState.setDump(DumpState.DUMP_VERIFIERS);
14556            } else if ("i".equals(cmd) || "ifv".equals(cmd)
14557                    || "intent-filter-verifiers".equals(cmd)) {
14558                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
14559            } else if ("version".equals(cmd)) {
14560                dumpState.setDump(DumpState.DUMP_VERSION);
14561            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
14562                dumpState.setDump(DumpState.DUMP_KEYSETS);
14563            } else if ("installs".equals(cmd)) {
14564                dumpState.setDump(DumpState.DUMP_INSTALLS);
14565            } else if ("write".equals(cmd)) {
14566                synchronized (mPackages) {
14567                    mSettings.writeLPr();
14568                    pw.println("Settings written.");
14569                    return;
14570                }
14571            }
14572        }
14573
14574        if (checkin) {
14575            pw.println("vers,1");
14576        }
14577
14578        // reader
14579        synchronized (mPackages) {
14580            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
14581                if (!checkin) {
14582                    if (dumpState.onTitlePrinted())
14583                        pw.println();
14584                    pw.println("Database versions:");
14585                    pw.print("  SDK Version:");
14586                    pw.print(" internal=");
14587                    pw.print(mSettings.mInternalSdkPlatform);
14588                    pw.print(" external=");
14589                    pw.println(mSettings.mExternalSdkPlatform);
14590                    pw.print("  DB Version:");
14591                    pw.print(" internal=");
14592                    pw.print(mSettings.mInternalDatabaseVersion);
14593                    pw.print(" external=");
14594                    pw.println(mSettings.mExternalDatabaseVersion);
14595                }
14596            }
14597
14598            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
14599                if (!checkin) {
14600                    if (dumpState.onTitlePrinted())
14601                        pw.println();
14602                    pw.println("Verifiers:");
14603                    pw.print("  Required: ");
14604                    pw.print(mRequiredVerifierPackage);
14605                    pw.print(" (uid=");
14606                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
14607                    pw.println(")");
14608                } else if (mRequiredVerifierPackage != null) {
14609                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
14610                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
14611                }
14612            }
14613
14614            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
14615                    packageName == null) {
14616                if (mIntentFilterVerifierComponent != null) {
14617                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
14618                    if (!checkin) {
14619                        if (dumpState.onTitlePrinted())
14620                            pw.println();
14621                        pw.println("Intent Filter Verifier:");
14622                        pw.print("  Using: ");
14623                        pw.print(verifierPackageName);
14624                        pw.print(" (uid=");
14625                        pw.print(getPackageUid(verifierPackageName, 0));
14626                        pw.println(")");
14627                    } else if (verifierPackageName != null) {
14628                        pw.print("ifv,"); pw.print(verifierPackageName);
14629                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
14630                    }
14631                } else {
14632                    pw.println();
14633                    pw.println("No Intent Filter Verifier available!");
14634                }
14635            }
14636
14637            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
14638                boolean printedHeader = false;
14639                final Iterator<String> it = mSharedLibraries.keySet().iterator();
14640                while (it.hasNext()) {
14641                    String name = it.next();
14642                    SharedLibraryEntry ent = mSharedLibraries.get(name);
14643                    if (!checkin) {
14644                        if (!printedHeader) {
14645                            if (dumpState.onTitlePrinted())
14646                                pw.println();
14647                            pw.println("Libraries:");
14648                            printedHeader = true;
14649                        }
14650                        pw.print("  ");
14651                    } else {
14652                        pw.print("lib,");
14653                    }
14654                    pw.print(name);
14655                    if (!checkin) {
14656                        pw.print(" -> ");
14657                    }
14658                    if (ent.path != null) {
14659                        if (!checkin) {
14660                            pw.print("(jar) ");
14661                            pw.print(ent.path);
14662                        } else {
14663                            pw.print(",jar,");
14664                            pw.print(ent.path);
14665                        }
14666                    } else {
14667                        if (!checkin) {
14668                            pw.print("(apk) ");
14669                            pw.print(ent.apk);
14670                        } else {
14671                            pw.print(",apk,");
14672                            pw.print(ent.apk);
14673                        }
14674                    }
14675                    pw.println();
14676                }
14677            }
14678
14679            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
14680                if (dumpState.onTitlePrinted())
14681                    pw.println();
14682                if (!checkin) {
14683                    pw.println("Features:");
14684                }
14685                Iterator<String> it = mAvailableFeatures.keySet().iterator();
14686                while (it.hasNext()) {
14687                    String name = it.next();
14688                    if (!checkin) {
14689                        pw.print("  ");
14690                    } else {
14691                        pw.print("feat,");
14692                    }
14693                    pw.println(name);
14694                }
14695            }
14696
14697            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
14698                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
14699                        : "Activity Resolver Table:", "  ", packageName,
14700                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14701                    dumpState.setTitlePrinted(true);
14702                }
14703                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
14704                        : "Receiver Resolver Table:", "  ", packageName,
14705                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14706                    dumpState.setTitlePrinted(true);
14707                }
14708                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
14709                        : "Service Resolver Table:", "  ", packageName,
14710                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14711                    dumpState.setTitlePrinted(true);
14712                }
14713                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
14714                        : "Provider Resolver Table:", "  ", packageName,
14715                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14716                    dumpState.setTitlePrinted(true);
14717                }
14718            }
14719
14720            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
14721                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14722                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14723                    int user = mSettings.mPreferredActivities.keyAt(i);
14724                    if (pir.dump(pw,
14725                            dumpState.getTitlePrinted()
14726                                ? "\nPreferred Activities User " + user + ":"
14727                                : "Preferred Activities User " + user + ":", "  ",
14728                            packageName, true, false)) {
14729                        dumpState.setTitlePrinted(true);
14730                    }
14731                }
14732            }
14733
14734            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
14735                pw.flush();
14736                FileOutputStream fout = new FileOutputStream(fd);
14737                BufferedOutputStream str = new BufferedOutputStream(fout);
14738                XmlSerializer serializer = new FastXmlSerializer();
14739                try {
14740                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
14741                    serializer.startDocument(null, true);
14742                    serializer.setFeature(
14743                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
14744                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
14745                    serializer.endDocument();
14746                    serializer.flush();
14747                } catch (IllegalArgumentException e) {
14748                    pw.println("Failed writing: " + e);
14749                } catch (IllegalStateException e) {
14750                    pw.println("Failed writing: " + e);
14751                } catch (IOException e) {
14752                    pw.println("Failed writing: " + e);
14753                }
14754            }
14755
14756            if (!checkin
14757                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
14758                    && packageName == null) {
14759                pw.println();
14760                int count = mSettings.mPackages.size();
14761                if (count == 0) {
14762                    pw.println("No domain preferred apps!");
14763                    pw.println();
14764                } else {
14765                    final String prefix = "  ";
14766                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
14767                    if (allPackageSettings.size() == 0) {
14768                        pw.println("No domain preferred apps!");
14769                        pw.println();
14770                    } else {
14771                        pw.println("Domain preferred apps status:");
14772                        pw.println();
14773                        count = 0;
14774                        for (PackageSetting ps : allPackageSettings) {
14775                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
14776                            if (ivi == null || ivi.getPackageName() == null) continue;
14777                            pw.println(prefix + "Package Name: " + ivi.getPackageName());
14778                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
14779                            pw.println(prefix + "Status: " + ivi.getStatusString());
14780                            pw.println();
14781                            count++;
14782                        }
14783                        if (count == 0) {
14784                            pw.println(prefix + "No domain preferred app status!");
14785                            pw.println();
14786                        }
14787                        for (int userId : sUserManager.getUserIds()) {
14788                            pw.println("Domain preferred apps for User " + userId + ":");
14789                            pw.println();
14790                            count = 0;
14791                            for (PackageSetting ps : allPackageSettings) {
14792                                IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
14793                                if (ivi == null || ivi.getPackageName() == null) {
14794                                    continue;
14795                                }
14796                                final int status = ps.getDomainVerificationStatusForUser(userId);
14797                                if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
14798                                    continue;
14799                                }
14800                                pw.println(prefix + "Package Name: " + ivi.getPackageName());
14801                                pw.println(prefix + "Domains: " + ivi.getDomainsString());
14802                                String statusStr = IntentFilterVerificationInfo.
14803                                        getStatusStringFromValue(status);
14804                                pw.println(prefix + "Status: " + statusStr);
14805                                pw.println();
14806                                count++;
14807                            }
14808                            if (count == 0) {
14809                                pw.println(prefix + "No domain preferred apps!");
14810                                pw.println();
14811                            }
14812                        }
14813                    }
14814                }
14815            }
14816
14817            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
14818                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
14819                if (packageName == null && permissionNames == null) {
14820                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
14821                        if (iperm == 0) {
14822                            if (dumpState.onTitlePrinted())
14823                                pw.println();
14824                            pw.println("AppOp Permissions:");
14825                        }
14826                        pw.print("  AppOp Permission ");
14827                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
14828                        pw.println(":");
14829                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
14830                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
14831                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
14832                        }
14833                    }
14834                }
14835            }
14836
14837            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
14838                boolean printedSomething = false;
14839                for (PackageParser.Provider p : mProviders.mProviders.values()) {
14840                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14841                        continue;
14842                    }
14843                    if (!printedSomething) {
14844                        if (dumpState.onTitlePrinted())
14845                            pw.println();
14846                        pw.println("Registered ContentProviders:");
14847                        printedSomething = true;
14848                    }
14849                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
14850                    pw.print("    "); pw.println(p.toString());
14851                }
14852                printedSomething = false;
14853                for (Map.Entry<String, PackageParser.Provider> entry :
14854                        mProvidersByAuthority.entrySet()) {
14855                    PackageParser.Provider p = entry.getValue();
14856                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14857                        continue;
14858                    }
14859                    if (!printedSomething) {
14860                        if (dumpState.onTitlePrinted())
14861                            pw.println();
14862                        pw.println("ContentProvider Authorities:");
14863                        printedSomething = true;
14864                    }
14865                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
14866                    pw.print("    "); pw.println(p.toString());
14867                    if (p.info != null && p.info.applicationInfo != null) {
14868                        final String appInfo = p.info.applicationInfo.toString();
14869                        pw.print("      applicationInfo="); pw.println(appInfo);
14870                    }
14871                }
14872            }
14873
14874            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
14875                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
14876            }
14877
14878            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
14879                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
14880            }
14881
14882            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
14883                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
14884            }
14885
14886            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
14887                // XXX should handle packageName != null by dumping only install data that
14888                // the given package is involved with.
14889                if (dumpState.onTitlePrinted()) pw.println();
14890                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
14891            }
14892
14893            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
14894                if (dumpState.onTitlePrinted()) pw.println();
14895                mSettings.dumpReadMessagesLPr(pw, dumpState);
14896
14897                pw.println();
14898                pw.println("Package warning messages:");
14899                BufferedReader in = null;
14900                String line = null;
14901                try {
14902                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
14903                    while ((line = in.readLine()) != null) {
14904                        if (line.contains("ignored: updated version")) continue;
14905                        pw.println(line);
14906                    }
14907                } catch (IOException ignored) {
14908                } finally {
14909                    IoUtils.closeQuietly(in);
14910                }
14911            }
14912
14913            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
14914                BufferedReader in = null;
14915                String line = null;
14916                try {
14917                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
14918                    while ((line = in.readLine()) != null) {
14919                        if (line.contains("ignored: updated version")) continue;
14920                        pw.print("msg,");
14921                        pw.println(line);
14922                    }
14923                } catch (IOException ignored) {
14924                } finally {
14925                    IoUtils.closeQuietly(in);
14926                }
14927            }
14928        }
14929    }
14930
14931    // ------- apps on sdcard specific code -------
14932    static final boolean DEBUG_SD_INSTALL = false;
14933
14934    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
14935
14936    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
14937
14938    private boolean mMediaMounted = false;
14939
14940    static String getEncryptKey() {
14941        try {
14942            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
14943                    SD_ENCRYPTION_KEYSTORE_NAME);
14944            if (sdEncKey == null) {
14945                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
14946                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
14947                if (sdEncKey == null) {
14948                    Slog.e(TAG, "Failed to create encryption keys");
14949                    return null;
14950                }
14951            }
14952            return sdEncKey;
14953        } catch (NoSuchAlgorithmException nsae) {
14954            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
14955            return null;
14956        } catch (IOException ioe) {
14957            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
14958            return null;
14959        }
14960    }
14961
14962    /*
14963     * Update media status on PackageManager.
14964     */
14965    @Override
14966    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
14967        int callingUid = Binder.getCallingUid();
14968        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
14969            throw new SecurityException("Media status can only be updated by the system");
14970        }
14971        // reader; this apparently protects mMediaMounted, but should probably
14972        // be a different lock in that case.
14973        synchronized (mPackages) {
14974            Log.i(TAG, "Updating external media status from "
14975                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
14976                    + (mediaStatus ? "mounted" : "unmounted"));
14977            if (DEBUG_SD_INSTALL)
14978                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
14979                        + ", mMediaMounted=" + mMediaMounted);
14980            if (mediaStatus == mMediaMounted) {
14981                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
14982                        : 0, -1);
14983                mHandler.sendMessage(msg);
14984                return;
14985            }
14986            mMediaMounted = mediaStatus;
14987        }
14988        // Queue up an async operation since the package installation may take a
14989        // little while.
14990        mHandler.post(new Runnable() {
14991            public void run() {
14992                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
14993            }
14994        });
14995    }
14996
14997    /**
14998     * Called by MountService when the initial ASECs to scan are available.
14999     * Should block until all the ASEC containers are finished being scanned.
15000     */
15001    public void scanAvailableAsecs() {
15002        updateExternalMediaStatusInner(true, false, false);
15003        if (mShouldRestoreconData) {
15004            SELinuxMMAC.setRestoreconDone();
15005            mShouldRestoreconData = false;
15006        }
15007    }
15008
15009    /*
15010     * Collect information of applications on external media, map them against
15011     * existing containers and update information based on current mount status.
15012     * Please note that we always have to report status if reportStatus has been
15013     * set to true especially when unloading packages.
15014     */
15015    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
15016            boolean externalStorage) {
15017        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
15018        int[] uidArr = EmptyArray.INT;
15019
15020        final String[] list = PackageHelper.getSecureContainerList();
15021        if (ArrayUtils.isEmpty(list)) {
15022            Log.i(TAG, "No secure containers found");
15023        } else {
15024            // Process list of secure containers and categorize them
15025            // as active or stale based on their package internal state.
15026
15027            // reader
15028            synchronized (mPackages) {
15029                for (String cid : list) {
15030                    // Leave stages untouched for now; installer service owns them
15031                    if (PackageInstallerService.isStageName(cid)) continue;
15032
15033                    if (DEBUG_SD_INSTALL)
15034                        Log.i(TAG, "Processing container " + cid);
15035                    String pkgName = getAsecPackageName(cid);
15036                    if (pkgName == null) {
15037                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
15038                        continue;
15039                    }
15040                    if (DEBUG_SD_INSTALL)
15041                        Log.i(TAG, "Looking for pkg : " + pkgName);
15042
15043                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
15044                    if (ps == null) {
15045                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
15046                        continue;
15047                    }
15048
15049                    /*
15050                     * Skip packages that are not external if we're unmounting
15051                     * external storage.
15052                     */
15053                    if (externalStorage && !isMounted && !isExternal(ps)) {
15054                        continue;
15055                    }
15056
15057                    final AsecInstallArgs args = new AsecInstallArgs(cid,
15058                            getAppDexInstructionSets(ps), ps.isForwardLocked());
15059                    // The package status is changed only if the code path
15060                    // matches between settings and the container id.
15061                    if (ps.codePathString != null
15062                            && ps.codePathString.startsWith(args.getCodePath())) {
15063                        if (DEBUG_SD_INSTALL) {
15064                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
15065                                    + " at code path: " + ps.codePathString);
15066                        }
15067
15068                        // We do have a valid package installed on sdcard
15069                        processCids.put(args, ps.codePathString);
15070                        final int uid = ps.appId;
15071                        if (uid != -1) {
15072                            uidArr = ArrayUtils.appendInt(uidArr, uid);
15073                        }
15074                    } else {
15075                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
15076                                + ps.codePathString);
15077                    }
15078                }
15079            }
15080
15081            Arrays.sort(uidArr);
15082        }
15083
15084        // Process packages with valid entries.
15085        if (isMounted) {
15086            if (DEBUG_SD_INSTALL)
15087                Log.i(TAG, "Loading packages");
15088            loadMediaPackages(processCids, uidArr);
15089            startCleaningPackages();
15090            mInstallerService.onSecureContainersAvailable();
15091        } else {
15092            if (DEBUG_SD_INSTALL)
15093                Log.i(TAG, "Unloading packages");
15094            unloadMediaPackages(processCids, uidArr, reportStatus);
15095        }
15096    }
15097
15098    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15099            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
15100        final int size = infos.size();
15101        final String[] packageNames = new String[size];
15102        final int[] packageUids = new int[size];
15103        for (int i = 0; i < size; i++) {
15104            final ApplicationInfo info = infos.get(i);
15105            packageNames[i] = info.packageName;
15106            packageUids[i] = info.uid;
15107        }
15108        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
15109                finishedReceiver);
15110    }
15111
15112    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15113            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15114        sendResourcesChangedBroadcast(mediaStatus, replacing,
15115                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
15116    }
15117
15118    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15119            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15120        int size = pkgList.length;
15121        if (size > 0) {
15122            // Send broadcasts here
15123            Bundle extras = new Bundle();
15124            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
15125            if (uidArr != null) {
15126                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
15127            }
15128            if (replacing) {
15129                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
15130            }
15131            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
15132                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
15133            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
15134        }
15135    }
15136
15137   /*
15138     * Look at potentially valid container ids from processCids If package
15139     * information doesn't match the one on record or package scanning fails,
15140     * the cid is added to list of removeCids. We currently don't delete stale
15141     * containers.
15142     */
15143    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
15144        ArrayList<String> pkgList = new ArrayList<String>();
15145        Set<AsecInstallArgs> keys = processCids.keySet();
15146
15147        for (AsecInstallArgs args : keys) {
15148            String codePath = processCids.get(args);
15149            if (DEBUG_SD_INSTALL)
15150                Log.i(TAG, "Loading container : " + args.cid);
15151            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15152            try {
15153                // Make sure there are no container errors first.
15154                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
15155                    Slog.e(TAG, "Failed to mount cid : " + args.cid
15156                            + " when installing from sdcard");
15157                    continue;
15158                }
15159                // Check code path here.
15160                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
15161                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
15162                            + " does not match one in settings " + codePath);
15163                    continue;
15164                }
15165                // Parse package
15166                int parseFlags = mDefParseFlags;
15167                if (args.isExternalAsec()) {
15168                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
15169                }
15170                if (args.isFwdLocked()) {
15171                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
15172                }
15173
15174                synchronized (mInstallLock) {
15175                    PackageParser.Package pkg = null;
15176                    try {
15177                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
15178                    } catch (PackageManagerException e) {
15179                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
15180                    }
15181                    // Scan the package
15182                    if (pkg != null) {
15183                        /*
15184                         * TODO why is the lock being held? doPostInstall is
15185                         * called in other places without the lock. This needs
15186                         * to be straightened out.
15187                         */
15188                        // writer
15189                        synchronized (mPackages) {
15190                            retCode = PackageManager.INSTALL_SUCCEEDED;
15191                            pkgList.add(pkg.packageName);
15192                            // Post process args
15193                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
15194                                    pkg.applicationInfo.uid);
15195                        }
15196                    } else {
15197                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
15198                    }
15199                }
15200
15201            } finally {
15202                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
15203                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
15204                }
15205            }
15206        }
15207        // writer
15208        synchronized (mPackages) {
15209            // If the platform SDK has changed since the last time we booted,
15210            // we need to re-grant app permission to catch any new ones that
15211            // appear. This is really a hack, and means that apps can in some
15212            // cases get permissions that the user didn't initially explicitly
15213            // allow... it would be nice to have some better way to handle
15214            // this situation.
15215            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
15216            if (regrantPermissions)
15217                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
15218                        + mSdkVersion + "; regranting permissions for external storage");
15219            mSettings.mExternalSdkPlatform = mSdkVersion;
15220
15221            // Make sure group IDs have been assigned, and any permission
15222            // changes in other apps are accounted for
15223            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
15224                    | (regrantPermissions
15225                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
15226                            : 0));
15227
15228            mSettings.updateExternalDatabaseVersion();
15229
15230            // can downgrade to reader
15231            // Persist settings
15232            mSettings.writeLPr();
15233        }
15234        // Send a broadcast to let everyone know we are done processing
15235        if (pkgList.size() > 0) {
15236            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
15237        }
15238    }
15239
15240   /*
15241     * Utility method to unload a list of specified containers
15242     */
15243    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
15244        // Just unmount all valid containers.
15245        for (AsecInstallArgs arg : cidArgs) {
15246            synchronized (mInstallLock) {
15247                arg.doPostDeleteLI(false);
15248           }
15249       }
15250   }
15251
15252    /*
15253     * Unload packages mounted on external media. This involves deleting package
15254     * data from internal structures, sending broadcasts about diabled packages,
15255     * gc'ing to free up references, unmounting all secure containers
15256     * corresponding to packages on external media, and posting a
15257     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
15258     * that we always have to post this message if status has been requested no
15259     * matter what.
15260     */
15261    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
15262            final boolean reportStatus) {
15263        if (DEBUG_SD_INSTALL)
15264            Log.i(TAG, "unloading media packages");
15265        ArrayList<String> pkgList = new ArrayList<String>();
15266        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
15267        final Set<AsecInstallArgs> keys = processCids.keySet();
15268        for (AsecInstallArgs args : keys) {
15269            String pkgName = args.getPackageName();
15270            if (DEBUG_SD_INSTALL)
15271                Log.i(TAG, "Trying to unload pkg : " + pkgName);
15272            // Delete package internally
15273            PackageRemovedInfo outInfo = new PackageRemovedInfo();
15274            synchronized (mInstallLock) {
15275                boolean res = deletePackageLI(pkgName, null, false, null, null,
15276                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
15277                if (res) {
15278                    pkgList.add(pkgName);
15279                } else {
15280                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
15281                    failedList.add(args);
15282                }
15283            }
15284        }
15285
15286        // reader
15287        synchronized (mPackages) {
15288            // We didn't update the settings after removing each package;
15289            // write them now for all packages.
15290            mSettings.writeLPr();
15291        }
15292
15293        // We have to absolutely send UPDATED_MEDIA_STATUS only
15294        // after confirming that all the receivers processed the ordered
15295        // broadcast when packages get disabled, force a gc to clean things up.
15296        // and unload all the containers.
15297        if (pkgList.size() > 0) {
15298            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
15299                    new IIntentReceiver.Stub() {
15300                public void performReceive(Intent intent, int resultCode, String data,
15301                        Bundle extras, boolean ordered, boolean sticky,
15302                        int sendingUser) throws RemoteException {
15303                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
15304                            reportStatus ? 1 : 0, 1, keys);
15305                    mHandler.sendMessage(msg);
15306                }
15307            });
15308        } else {
15309            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
15310                    keys);
15311            mHandler.sendMessage(msg);
15312        }
15313    }
15314
15315    private void loadPrivatePackages(VolumeInfo vol) {
15316        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
15317        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
15318        synchronized (mInstallLock) {
15319        synchronized (mPackages) {
15320            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15321            for (PackageSetting ps : packages) {
15322                final PackageParser.Package pkg;
15323                try {
15324                    pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null);
15325                    loaded.add(pkg.applicationInfo);
15326                } catch (PackageManagerException e) {
15327                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
15328                }
15329            }
15330
15331            // TODO: regrant any permissions that changed based since original install
15332
15333            mSettings.writeLPr();
15334        }
15335        }
15336
15337        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
15338        sendResourcesChangedBroadcast(true, false, loaded, null);
15339    }
15340
15341    private void unloadPrivatePackages(VolumeInfo vol) {
15342        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
15343        synchronized (mInstallLock) {
15344        synchronized (mPackages) {
15345            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15346            for (PackageSetting ps : packages) {
15347                if (ps.pkg == null) continue;
15348
15349                final ApplicationInfo info = ps.pkg.applicationInfo;
15350                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
15351                if (deletePackageLI(ps.name, null, false, null, null,
15352                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
15353                    unloaded.add(info);
15354                } else {
15355                    Slog.w(TAG, "Failed to unload " + ps.codePath);
15356                }
15357            }
15358
15359            mSettings.writeLPr();
15360        }
15361        }
15362
15363        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
15364        sendResourcesChangedBroadcast(false, false, unloaded, null);
15365    }
15366
15367    /**
15368     * Examine all users present on given mounted volume, and destroy data
15369     * belonging to users that are no longer valid, or whose user ID has been
15370     * recycled.
15371     */
15372    private void reconcileUsers(String volumeUuid) {
15373        final File[] files = Environment.getDataUserDirectory(volumeUuid).listFiles();
15374        if (ArrayUtils.isEmpty(files)) {
15375            Slog.d(TAG, "No users found on " + volumeUuid);
15376            return;
15377        }
15378
15379        for (File file : files) {
15380            if (!file.isDirectory()) continue;
15381
15382            final int userId;
15383            final UserInfo info;
15384            try {
15385                userId = Integer.parseInt(file.getName());
15386                info = sUserManager.getUserInfo(userId);
15387            } catch (NumberFormatException e) {
15388                Slog.w(TAG, "Invalid user directory " + file);
15389                continue;
15390            }
15391
15392            boolean destroyUser = false;
15393            if (info == null) {
15394                logCriticalInfo(Log.WARN, "Destroying user directory " + file
15395                        + " because no matching user was found");
15396                destroyUser = true;
15397            } else {
15398                try {
15399                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
15400                } catch (IOException e) {
15401                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
15402                            + " because we failed to enforce serial number: " + e);
15403                    destroyUser = true;
15404                }
15405            }
15406
15407            if (destroyUser) {
15408                synchronized (mInstallLock) {
15409                    mInstaller.removeUserDataDirs(volumeUuid, userId);
15410                }
15411            }
15412        }
15413
15414        final UserManager um = mContext.getSystemService(UserManager.class);
15415        for (UserInfo user : um.getUsers()) {
15416            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
15417            if (userDir.exists()) continue;
15418
15419            try {
15420                UserManagerService.prepareUserDirectory(userDir);
15421                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
15422            } catch (IOException e) {
15423                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
15424            }
15425        }
15426    }
15427
15428    /**
15429     * Examine all apps present on given mounted volume, and destroy apps that
15430     * aren't expected, either due to uninstallation or reinstallation on
15431     * another volume.
15432     */
15433    private void reconcileApps(String volumeUuid) {
15434        final File[] files = Environment.getDataAppDirectory(volumeUuid).listFiles();
15435        if (ArrayUtils.isEmpty(files)) {
15436            Slog.d(TAG, "No apps found on " + volumeUuid);
15437            return;
15438        }
15439
15440        for (File file : files) {
15441            final boolean isPackage = (isApkFile(file) || file.isDirectory())
15442                    && !PackageInstallerService.isStageName(file.getName());
15443            if (!isPackage) {
15444                // Ignore entries which are not packages
15445                continue;
15446            }
15447
15448            boolean destroyApp = false;
15449            String packageName = null;
15450            try {
15451                final PackageLite pkg = PackageParser.parsePackageLite(file,
15452                        PackageParser.PARSE_MUST_BE_APK);
15453                packageName = pkg.packageName;
15454
15455                synchronized (mPackages) {
15456                    final PackageSetting ps = mSettings.mPackages.get(packageName);
15457                    if (ps == null) {
15458                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
15459                                + volumeUuid + " because we found no install record");
15460                        destroyApp = true;
15461                    } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
15462                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
15463                                + volumeUuid + " because we expected it on " + ps.volumeUuid);
15464                        destroyApp = true;
15465                    }
15466                }
15467
15468            } catch (PackageParserException e) {
15469                logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
15470                destroyApp = true;
15471            }
15472
15473            if (destroyApp) {
15474                synchronized (mInstallLock) {
15475                    if (packageName != null) {
15476                        removeDataDirsLI(volumeUuid, packageName);
15477                    }
15478                    if (file.isDirectory()) {
15479                        mInstaller.rmPackageDir(file.getAbsolutePath());
15480                    } else {
15481                        file.delete();
15482                    }
15483                }
15484            }
15485        }
15486    }
15487
15488    private void unfreezePackage(String packageName) {
15489        synchronized (mPackages) {
15490            final PackageSetting ps = mSettings.mPackages.get(packageName);
15491            if (ps != null) {
15492                ps.frozen = false;
15493            }
15494        }
15495    }
15496
15497    @Override
15498    public int movePackage(final String packageName, final String volumeUuid) {
15499        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15500
15501        final int moveId = mNextMoveId.getAndIncrement();
15502        try {
15503            movePackageInternal(packageName, volumeUuid, moveId);
15504        } catch (PackageManagerException e) {
15505            Slog.w(TAG, "Failed to move " + packageName, e);
15506            mMoveCallbacks.notifyStatusChanged(moveId,
15507                    PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15508        }
15509        return moveId;
15510    }
15511
15512    private void movePackageInternal(final String packageName, final String volumeUuid,
15513            final int moveId) throws PackageManagerException {
15514        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
15515        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15516        final PackageManager pm = mContext.getPackageManager();
15517
15518        final boolean currentAsec;
15519        final String currentVolumeUuid;
15520        final File codeFile;
15521        final String installerPackageName;
15522        final String packageAbiOverride;
15523        final int appId;
15524        final String seinfo;
15525        final String label;
15526
15527        // reader
15528        synchronized (mPackages) {
15529            final PackageParser.Package pkg = mPackages.get(packageName);
15530            final PackageSetting ps = mSettings.mPackages.get(packageName);
15531            if (pkg == null || ps == null) {
15532                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
15533            }
15534
15535            if (pkg.applicationInfo.isSystemApp()) {
15536                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
15537                        "Cannot move system application");
15538            }
15539
15540            if (Objects.equals(ps.volumeUuid, volumeUuid)) {
15541                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15542                        "Package already moved to " + volumeUuid);
15543            }
15544
15545            final File probe = new File(pkg.codePath);
15546            final File probeOat = new File(probe, "oat");
15547            if (!probe.isDirectory() || !probeOat.isDirectory()) {
15548                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15549                        "Move only supported for modern cluster style installs");
15550            }
15551
15552            if (ps.frozen) {
15553                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
15554                        "Failed to move already frozen package");
15555            }
15556            ps.frozen = true;
15557
15558            currentAsec = pkg.applicationInfo.isForwardLocked()
15559                    || pkg.applicationInfo.isExternalAsec();
15560            currentVolumeUuid = ps.volumeUuid;
15561            codeFile = new File(pkg.codePath);
15562            installerPackageName = ps.installerPackageName;
15563            packageAbiOverride = ps.cpuAbiOverrideString;
15564            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
15565            seinfo = pkg.applicationInfo.seinfo;
15566            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
15567        }
15568
15569        // Now that we're guarded by frozen state, kill app during move
15570        killApplication(packageName, appId, "move pkg");
15571
15572        final Bundle extras = new Bundle();
15573        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
15574        extras.putString(Intent.EXTRA_TITLE, label);
15575        mMoveCallbacks.notifyCreated(moveId, extras);
15576
15577        int installFlags;
15578        final boolean moveCompleteApp;
15579        final File measurePath;
15580
15581        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
15582            installFlags = INSTALL_INTERNAL;
15583            moveCompleteApp = !currentAsec;
15584            measurePath = Environment.getDataAppDirectory(volumeUuid);
15585        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
15586            installFlags = INSTALL_EXTERNAL;
15587            moveCompleteApp = false;
15588            measurePath = storage.getPrimaryPhysicalVolume().getPath();
15589        } else {
15590            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
15591            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
15592                    || !volume.isMountedWritable()) {
15593                unfreezePackage(packageName);
15594                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15595                        "Move location not mounted private volume");
15596            }
15597
15598            Preconditions.checkState(!currentAsec);
15599
15600            installFlags = INSTALL_INTERNAL;
15601            moveCompleteApp = true;
15602            measurePath = Environment.getDataAppDirectory(volumeUuid);
15603        }
15604
15605        final PackageStats stats = new PackageStats(null, -1);
15606        synchronized (mInstaller) {
15607            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
15608                unfreezePackage(packageName);
15609                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15610                        "Failed to measure package size");
15611            }
15612        }
15613
15614        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
15615                + stats.dataSize);
15616
15617        final long startFreeBytes = measurePath.getFreeSpace();
15618        final long sizeBytes;
15619        if (moveCompleteApp) {
15620            sizeBytes = stats.codeSize + stats.dataSize;
15621        } else {
15622            sizeBytes = stats.codeSize;
15623        }
15624
15625        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
15626            unfreezePackage(packageName);
15627            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15628                    "Not enough free space to move");
15629        }
15630
15631        mMoveCallbacks.notifyStatusChanged(moveId, 10);
15632
15633        final CountDownLatch installedLatch = new CountDownLatch(1);
15634        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
15635            @Override
15636            public void onUserActionRequired(Intent intent) throws RemoteException {
15637                throw new IllegalStateException();
15638            }
15639
15640            @Override
15641            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
15642                    Bundle extras) throws RemoteException {
15643                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
15644                        + PackageManager.installStatusToString(returnCode, msg));
15645
15646                installedLatch.countDown();
15647
15648                // Regardless of success or failure of the move operation,
15649                // always unfreeze the package
15650                unfreezePackage(packageName);
15651
15652                final int status = PackageManager.installStatusToPublicStatus(returnCode);
15653                switch (status) {
15654                    case PackageInstaller.STATUS_SUCCESS:
15655                        mMoveCallbacks.notifyStatusChanged(moveId,
15656                                PackageManager.MOVE_SUCCEEDED);
15657                        break;
15658                    case PackageInstaller.STATUS_FAILURE_STORAGE:
15659                        mMoveCallbacks.notifyStatusChanged(moveId,
15660                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
15661                        break;
15662                    default:
15663                        mMoveCallbacks.notifyStatusChanged(moveId,
15664                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15665                        break;
15666                }
15667            }
15668        };
15669
15670        final MoveInfo move;
15671        if (moveCompleteApp) {
15672            // Kick off a thread to report progress estimates
15673            new Thread() {
15674                @Override
15675                public void run() {
15676                    while (true) {
15677                        try {
15678                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
15679                                break;
15680                            }
15681                        } catch (InterruptedException ignored) {
15682                        }
15683
15684                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
15685                        final int progress = 10 + (int) MathUtils.constrain(
15686                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
15687                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
15688                    }
15689                }
15690            }.start();
15691
15692            final String dataAppName = codeFile.getName();
15693            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
15694                    dataAppName, appId, seinfo);
15695        } else {
15696            move = null;
15697        }
15698
15699        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
15700
15701        final Message msg = mHandler.obtainMessage(INIT_COPY);
15702        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
15703        msg.obj = new InstallParams(origin, move, installObserver, installFlags,
15704                installerPackageName, volumeUuid, null, user, packageAbiOverride);
15705        mHandler.sendMessage(msg);
15706    }
15707
15708    @Override
15709    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
15710        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15711
15712        final int realMoveId = mNextMoveId.getAndIncrement();
15713        final Bundle extras = new Bundle();
15714        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
15715        mMoveCallbacks.notifyCreated(realMoveId, extras);
15716
15717        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
15718            @Override
15719            public void onCreated(int moveId, Bundle extras) {
15720                // Ignored
15721            }
15722
15723            @Override
15724            public void onStatusChanged(int moveId, int status, long estMillis) {
15725                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
15726            }
15727        };
15728
15729        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15730        storage.setPrimaryStorageUuid(volumeUuid, callback);
15731        return realMoveId;
15732    }
15733
15734    @Override
15735    public int getMoveStatus(int moveId) {
15736        mContext.enforceCallingOrSelfPermission(
15737                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15738        return mMoveCallbacks.mLastStatus.get(moveId);
15739    }
15740
15741    @Override
15742    public void registerMoveCallback(IPackageMoveObserver callback) {
15743        mContext.enforceCallingOrSelfPermission(
15744                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15745        mMoveCallbacks.register(callback);
15746    }
15747
15748    @Override
15749    public void unregisterMoveCallback(IPackageMoveObserver callback) {
15750        mContext.enforceCallingOrSelfPermission(
15751                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15752        mMoveCallbacks.unregister(callback);
15753    }
15754
15755    @Override
15756    public boolean setInstallLocation(int loc) {
15757        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
15758                null);
15759        if (getInstallLocation() == loc) {
15760            return true;
15761        }
15762        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
15763                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
15764            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
15765                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
15766            return true;
15767        }
15768        return false;
15769   }
15770
15771    @Override
15772    public int getInstallLocation() {
15773        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15774                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
15775                PackageHelper.APP_INSTALL_AUTO);
15776    }
15777
15778    /** Called by UserManagerService */
15779    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
15780        mDirtyUsers.remove(userHandle);
15781        mSettings.removeUserLPw(userHandle);
15782        mPendingBroadcasts.remove(userHandle);
15783        if (mInstaller != null) {
15784            // Technically, we shouldn't be doing this with the package lock
15785            // held.  However, this is very rare, and there is already so much
15786            // other disk I/O going on, that we'll let it slide for now.
15787            final StorageManager storage = mContext.getSystemService(StorageManager.class);
15788            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
15789                final String volumeUuid = vol.getFsUuid();
15790                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
15791                mInstaller.removeUserDataDirs(volumeUuid, userHandle);
15792            }
15793        }
15794        mUserNeedsBadging.delete(userHandle);
15795        removeUnusedPackagesLILPw(userManager, userHandle);
15796    }
15797
15798    /**
15799     * We're removing userHandle and would like to remove any downloaded packages
15800     * that are no longer in use by any other user.
15801     * @param userHandle the user being removed
15802     */
15803    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
15804        final boolean DEBUG_CLEAN_APKS = false;
15805        int [] users = userManager.getUserIdsLPr();
15806        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
15807        while (psit.hasNext()) {
15808            PackageSetting ps = psit.next();
15809            if (ps.pkg == null) {
15810                continue;
15811            }
15812            final String packageName = ps.pkg.packageName;
15813            // Skip over if system app
15814            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15815                continue;
15816            }
15817            if (DEBUG_CLEAN_APKS) {
15818                Slog.i(TAG, "Checking package " + packageName);
15819            }
15820            boolean keep = false;
15821            for (int i = 0; i < users.length; i++) {
15822                if (users[i] != userHandle && ps.getInstalled(users[i])) {
15823                    keep = true;
15824                    if (DEBUG_CLEAN_APKS) {
15825                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
15826                                + users[i]);
15827                    }
15828                    break;
15829                }
15830            }
15831            if (!keep) {
15832                if (DEBUG_CLEAN_APKS) {
15833                    Slog.i(TAG, "  Removing package " + packageName);
15834                }
15835                mHandler.post(new Runnable() {
15836                    public void run() {
15837                        deletePackageX(packageName, userHandle, 0);
15838                    } //end run
15839                });
15840            }
15841        }
15842    }
15843
15844    /** Called by UserManagerService */
15845    void createNewUserLILPw(int userHandle) {
15846        if (mInstaller != null) {
15847            mInstaller.createUserConfig(userHandle);
15848            mSettings.createNewUserLILPw(this, mInstaller, userHandle);
15849            applyFactoryDefaultBrowserLPw(userHandle);
15850        }
15851    }
15852
15853    void newUserCreatedLILPw(final int userHandle) {
15854        // We cannot grant the default permissions with a lock held as
15855        // we query providers from other components for default handlers
15856        // such as enabled IMEs, etc.
15857        mHandler.post(new Runnable() {
15858            @Override
15859            public void run() {
15860                mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
15861            }
15862        });
15863    }
15864
15865    @Override
15866    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
15867        mContext.enforceCallingOrSelfPermission(
15868                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15869                "Only package verification agents can read the verifier device identity");
15870
15871        synchronized (mPackages) {
15872            return mSettings.getVerifierDeviceIdentityLPw();
15873        }
15874    }
15875
15876    @Override
15877    public void setPermissionEnforced(String permission, boolean enforced) {
15878        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
15879        if (READ_EXTERNAL_STORAGE.equals(permission)) {
15880            synchronized (mPackages) {
15881                if (mSettings.mReadExternalStorageEnforced == null
15882                        || mSettings.mReadExternalStorageEnforced != enforced) {
15883                    mSettings.mReadExternalStorageEnforced = enforced;
15884                    mSettings.writeLPr();
15885                }
15886            }
15887            // kill any non-foreground processes so we restart them and
15888            // grant/revoke the GID.
15889            final IActivityManager am = ActivityManagerNative.getDefault();
15890            if (am != null) {
15891                final long token = Binder.clearCallingIdentity();
15892                try {
15893                    am.killProcessesBelowForeground("setPermissionEnforcement");
15894                } catch (RemoteException e) {
15895                } finally {
15896                    Binder.restoreCallingIdentity(token);
15897                }
15898            }
15899        } else {
15900            throw new IllegalArgumentException("No selective enforcement for " + permission);
15901        }
15902    }
15903
15904    @Override
15905    @Deprecated
15906    public boolean isPermissionEnforced(String permission) {
15907        return true;
15908    }
15909
15910    @Override
15911    public boolean isStorageLow() {
15912        final long token = Binder.clearCallingIdentity();
15913        try {
15914            final DeviceStorageMonitorInternal
15915                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
15916            if (dsm != null) {
15917                return dsm.isMemoryLow();
15918            } else {
15919                return false;
15920            }
15921        } finally {
15922            Binder.restoreCallingIdentity(token);
15923        }
15924    }
15925
15926    @Override
15927    public IPackageInstaller getPackageInstaller() {
15928        return mInstallerService;
15929    }
15930
15931    private boolean userNeedsBadging(int userId) {
15932        int index = mUserNeedsBadging.indexOfKey(userId);
15933        if (index < 0) {
15934            final UserInfo userInfo;
15935            final long token = Binder.clearCallingIdentity();
15936            try {
15937                userInfo = sUserManager.getUserInfo(userId);
15938            } finally {
15939                Binder.restoreCallingIdentity(token);
15940            }
15941            final boolean b;
15942            if (userInfo != null && userInfo.isManagedProfile()) {
15943                b = true;
15944            } else {
15945                b = false;
15946            }
15947            mUserNeedsBadging.put(userId, b);
15948            return b;
15949        }
15950        return mUserNeedsBadging.valueAt(index);
15951    }
15952
15953    @Override
15954    public KeySet getKeySetByAlias(String packageName, String alias) {
15955        if (packageName == null || alias == null) {
15956            return null;
15957        }
15958        synchronized(mPackages) {
15959            final PackageParser.Package pkg = mPackages.get(packageName);
15960            if (pkg == null) {
15961                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15962                throw new IllegalArgumentException("Unknown package: " + packageName);
15963            }
15964            KeySetManagerService ksms = mSettings.mKeySetManagerService;
15965            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
15966        }
15967    }
15968
15969    @Override
15970    public KeySet getSigningKeySet(String packageName) {
15971        if (packageName == null) {
15972            return null;
15973        }
15974        synchronized(mPackages) {
15975            final PackageParser.Package pkg = mPackages.get(packageName);
15976            if (pkg == null) {
15977                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15978                throw new IllegalArgumentException("Unknown package: " + packageName);
15979            }
15980            if (pkg.applicationInfo.uid != Binder.getCallingUid()
15981                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
15982                throw new SecurityException("May not access signing KeySet of other apps.");
15983            }
15984            KeySetManagerService ksms = mSettings.mKeySetManagerService;
15985            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
15986        }
15987    }
15988
15989    @Override
15990    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
15991        if (packageName == null || ks == null) {
15992            return false;
15993        }
15994        synchronized(mPackages) {
15995            final PackageParser.Package pkg = mPackages.get(packageName);
15996            if (pkg == null) {
15997                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15998                throw new IllegalArgumentException("Unknown package: " + packageName);
15999            }
16000            IBinder ksh = ks.getToken();
16001            if (ksh instanceof KeySetHandle) {
16002                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16003                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
16004            }
16005            return false;
16006        }
16007    }
16008
16009    @Override
16010    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
16011        if (packageName == null || ks == null) {
16012            return false;
16013        }
16014        synchronized(mPackages) {
16015            final PackageParser.Package pkg = mPackages.get(packageName);
16016            if (pkg == null) {
16017                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16018                throw new IllegalArgumentException("Unknown package: " + packageName);
16019            }
16020            IBinder ksh = ks.getToken();
16021            if (ksh instanceof KeySetHandle) {
16022                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16023                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
16024            }
16025            return false;
16026        }
16027    }
16028
16029    public void getUsageStatsIfNoPackageUsageInfo() {
16030        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
16031            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
16032            if (usm == null) {
16033                throw new IllegalStateException("UsageStatsManager must be initialized");
16034            }
16035            long now = System.currentTimeMillis();
16036            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
16037            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
16038                String packageName = entry.getKey();
16039                PackageParser.Package pkg = mPackages.get(packageName);
16040                if (pkg == null) {
16041                    continue;
16042                }
16043                UsageStats usage = entry.getValue();
16044                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
16045                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
16046            }
16047        }
16048    }
16049
16050    /**
16051     * Check and throw if the given before/after packages would be considered a
16052     * downgrade.
16053     */
16054    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
16055            throws PackageManagerException {
16056        if (after.versionCode < before.mVersionCode) {
16057            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16058                    "Update version code " + after.versionCode + " is older than current "
16059                    + before.mVersionCode);
16060        } else if (after.versionCode == before.mVersionCode) {
16061            if (after.baseRevisionCode < before.baseRevisionCode) {
16062                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16063                        "Update base revision code " + after.baseRevisionCode
16064                        + " is older than current " + before.baseRevisionCode);
16065            }
16066
16067            if (!ArrayUtils.isEmpty(after.splitNames)) {
16068                for (int i = 0; i < after.splitNames.length; i++) {
16069                    final String splitName = after.splitNames[i];
16070                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
16071                    if (j != -1) {
16072                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
16073                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16074                                    "Update split " + splitName + " revision code "
16075                                    + after.splitRevisionCodes[i] + " is older than current "
16076                                    + before.splitRevisionCodes[j]);
16077                        }
16078                    }
16079                }
16080            }
16081        }
16082    }
16083
16084    private static class MoveCallbacks extends Handler {
16085        private static final int MSG_CREATED = 1;
16086        private static final int MSG_STATUS_CHANGED = 2;
16087
16088        private final RemoteCallbackList<IPackageMoveObserver>
16089                mCallbacks = new RemoteCallbackList<>();
16090
16091        private final SparseIntArray mLastStatus = new SparseIntArray();
16092
16093        public MoveCallbacks(Looper looper) {
16094            super(looper);
16095        }
16096
16097        public void register(IPackageMoveObserver callback) {
16098            mCallbacks.register(callback);
16099        }
16100
16101        public void unregister(IPackageMoveObserver callback) {
16102            mCallbacks.unregister(callback);
16103        }
16104
16105        @Override
16106        public void handleMessage(Message msg) {
16107            final SomeArgs args = (SomeArgs) msg.obj;
16108            final int n = mCallbacks.beginBroadcast();
16109            for (int i = 0; i < n; i++) {
16110                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
16111                try {
16112                    invokeCallback(callback, msg.what, args);
16113                } catch (RemoteException ignored) {
16114                }
16115            }
16116            mCallbacks.finishBroadcast();
16117            args.recycle();
16118        }
16119
16120        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
16121                throws RemoteException {
16122            switch (what) {
16123                case MSG_CREATED: {
16124                    callback.onCreated(args.argi1, (Bundle) args.arg2);
16125                    break;
16126                }
16127                case MSG_STATUS_CHANGED: {
16128                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
16129                    break;
16130                }
16131            }
16132        }
16133
16134        private void notifyCreated(int moveId, Bundle extras) {
16135            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
16136
16137            final SomeArgs args = SomeArgs.obtain();
16138            args.argi1 = moveId;
16139            args.arg2 = extras;
16140            obtainMessage(MSG_CREATED, args).sendToTarget();
16141        }
16142
16143        private void notifyStatusChanged(int moveId, int status) {
16144            notifyStatusChanged(moveId, status, -1);
16145        }
16146
16147        private void notifyStatusChanged(int moveId, int status, long estMillis) {
16148            Slog.v(TAG, "Move " + moveId + " status " + status);
16149
16150            final SomeArgs args = SomeArgs.obtain();
16151            args.argi1 = moveId;
16152            args.argi2 = status;
16153            args.arg3 = estMillis;
16154            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
16155
16156            synchronized (mLastStatus) {
16157                mLastStatus.put(moveId, status);
16158            }
16159        }
16160    }
16161
16162    private final class OnPermissionChangeListeners extends Handler {
16163        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
16164
16165        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
16166                new RemoteCallbackList<>();
16167
16168        public OnPermissionChangeListeners(Looper looper) {
16169            super(looper);
16170        }
16171
16172        @Override
16173        public void handleMessage(Message msg) {
16174            switch (msg.what) {
16175                case MSG_ON_PERMISSIONS_CHANGED: {
16176                    final int uid = msg.arg1;
16177                    handleOnPermissionsChanged(uid);
16178                } break;
16179            }
16180        }
16181
16182        public void addListenerLocked(IOnPermissionsChangeListener listener) {
16183            mPermissionListeners.register(listener);
16184
16185        }
16186
16187        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
16188            mPermissionListeners.unregister(listener);
16189        }
16190
16191        public void onPermissionsChanged(int uid) {
16192            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
16193                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
16194            }
16195        }
16196
16197        private void handleOnPermissionsChanged(int uid) {
16198            final int count = mPermissionListeners.beginBroadcast();
16199            try {
16200                for (int i = 0; i < count; i++) {
16201                    IOnPermissionsChangeListener callback = mPermissionListeners
16202                            .getBroadcastItem(i);
16203                    try {
16204                        callback.onPermissionsChanged(uid);
16205                    } catch (RemoteException e) {
16206                        Log.e(TAG, "Permission listener is dead", e);
16207                    }
16208                }
16209            } finally {
16210                mPermissionListeners.finishBroadcast();
16211            }
16212        }
16213    }
16214
16215    private class PackageManagerInternalImpl extends PackageManagerInternal {
16216        @Override
16217        public void setLocationPackagesProvider(PackagesProvider provider) {
16218            synchronized (mPackages) {
16219                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
16220            }
16221        }
16222
16223        @Override
16224        public void setImePackagesProvider(PackagesProvider provider) {
16225            synchronized (mPackages) {
16226                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
16227            }
16228        }
16229
16230        @Override
16231        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
16232            synchronized (mPackages) {
16233                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
16234            }
16235        }
16236
16237        @Override
16238        public void setSmsAppPackagesProvider(PackagesProvider provider) {
16239            synchronized (mPackages) {
16240                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
16241            }
16242        }
16243
16244        @Override
16245        public void setDialerAppPackagesProvider(PackagesProvider provider) {
16246            synchronized (mPackages) {
16247                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
16248            }
16249        }
16250
16251        @Override
16252        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
16253            synchronized (mPackages) {
16254                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderrLPw(provider);
16255            }
16256        }
16257
16258        @Override
16259        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
16260            synchronized (mPackages) {
16261                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
16262                        packageName, userId);
16263            }
16264        }
16265
16266        @Override
16267        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
16268            synchronized (mPackages) {
16269                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
16270                        packageName, userId);
16271            }
16272        }
16273    }
16274
16275    @Override
16276    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
16277        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
16278        synchronized (mPackages) {
16279            final long identity = Binder.clearCallingIdentity();
16280            try {
16281                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
16282                        packageNames, userId);
16283            } finally {
16284                Binder.restoreCallingIdentity(identity);
16285            }
16286        }
16287    }
16288
16289    private static void enforceSystemOrPhoneCaller(String tag) {
16290        int callingUid = Binder.getCallingUid();
16291        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
16292            throw new SecurityException(
16293                    "Cannot call " + tag + " from UID " + callingUid);
16294        }
16295    }
16296}
16297