PackageManagerService.java revision bcf48ed2262d655ebf59153dea645ca761b73db5
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    final Settings mSettings;
472    boolean mRestoredSettings;
473
474    // System configuration read by SystemConfig.
475    final int[] mGlobalGids;
476    final SparseArray<ArraySet<String>> mSystemPermissions;
477    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
478
479    // If mac_permissions.xml was found for seinfo labeling.
480    boolean mFoundPolicyFile;
481
482    // If a recursive restorecon of /data/data/<pkg> is needed.
483    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
484
485    public static final class SharedLibraryEntry {
486        public final String path;
487        public final String apk;
488
489        SharedLibraryEntry(String _path, String _apk) {
490            path = _path;
491            apk = _apk;
492        }
493    }
494
495    // Currently known shared libraries.
496    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
497            new ArrayMap<String, SharedLibraryEntry>();
498
499    // All available activities, for your resolving pleasure.
500    final ActivityIntentResolver mActivities =
501            new ActivityIntentResolver();
502
503    // All available receivers, for your resolving pleasure.
504    final ActivityIntentResolver mReceivers =
505            new ActivityIntentResolver();
506
507    // All available services, for your resolving pleasure.
508    final ServiceIntentResolver mServices = new ServiceIntentResolver();
509
510    // All available providers, for your resolving pleasure.
511    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
512
513    // Mapping from provider base names (first directory in content URI codePath)
514    // to the provider information.
515    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
516            new ArrayMap<String, PackageParser.Provider>();
517
518    // Mapping from instrumentation class names to info about them.
519    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
520            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
521
522    // Mapping from permission names to info about them.
523    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
524            new ArrayMap<String, PackageParser.PermissionGroup>();
525
526    // Packages whose data we have transfered into another package, thus
527    // should no longer exist.
528    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
529
530    // Broadcast actions that are only available to the system.
531    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
532
533    /** List of packages waiting for verification. */
534    final SparseArray<PackageVerificationState> mPendingVerification
535            = new SparseArray<PackageVerificationState>();
536
537    /** Set of packages associated with each app op permission. */
538    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
539
540    final PackageInstallerService mInstallerService;
541
542    private final PackageDexOptimizer mPackageDexOptimizer;
543
544    private AtomicInteger mNextMoveId = new AtomicInteger();
545    private final MoveCallbacks mMoveCallbacks;
546
547    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
548
549    // Cache of users who need badging.
550    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
551
552    /** Token for keys in mPendingVerification. */
553    private int mPendingVerificationToken = 0;
554
555    volatile boolean mSystemReady;
556    volatile boolean mSafeMode;
557    volatile boolean mHasSystemUidErrors;
558
559    ApplicationInfo mAndroidApplication;
560    final ActivityInfo mResolveActivity = new ActivityInfo();
561    final ResolveInfo mResolveInfo = new ResolveInfo();
562    ComponentName mResolveComponentName;
563    PackageParser.Package mPlatformPackage;
564    ComponentName mCustomResolverComponentName;
565
566    boolean mResolverReplaced = false;
567
568    private final ComponentName mIntentFilterVerifierComponent;
569    private int mIntentFilterVerificationToken = 0;
570
571    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
572            = new SparseArray<IntentFilterVerificationState>();
573
574    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
575            new DefaultPermissionGrantPolicy(this);
576
577    private static class IFVerificationParams {
578        PackageParser.Package pkg;
579        boolean replacing;
580        int userId;
581        int verifierUid;
582
583        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
584                int _userId, int _verifierUid) {
585            pkg = _pkg;
586            replacing = _replacing;
587            userId = _userId;
588            replacing = _replacing;
589            verifierUid = _verifierUid;
590        }
591    }
592
593    private interface IntentFilterVerifier<T extends IntentFilter> {
594        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
595                                               T filter, String packageName);
596        void startVerifications(int userId);
597        void receiveVerificationResponse(int verificationId);
598    }
599
600    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
601        private Context mContext;
602        private ComponentName mIntentFilterVerifierComponent;
603        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
604
605        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
606            mContext = context;
607            mIntentFilterVerifierComponent = verifierComponent;
608        }
609
610        private String getDefaultScheme() {
611            return IntentFilter.SCHEME_HTTPS;
612        }
613
614        @Override
615        public void startVerifications(int userId) {
616            // Launch verifications requests
617            int count = mCurrentIntentFilterVerifications.size();
618            for (int n=0; n<count; n++) {
619                int verificationId = mCurrentIntentFilterVerifications.get(n);
620                final IntentFilterVerificationState ivs =
621                        mIntentFilterVerificationStates.get(verificationId);
622
623                String packageName = ivs.getPackageName();
624
625                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
626                final int filterCount = filters.size();
627                ArraySet<String> domainsSet = new ArraySet<>();
628                for (int m=0; m<filterCount; m++) {
629                    PackageParser.ActivityIntentInfo filter = filters.get(m);
630                    domainsSet.addAll(filter.getHostsList());
631                }
632                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
633                synchronized (mPackages) {
634                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
635                            packageName, domainsList) != null) {
636                        scheduleWriteSettingsLocked();
637                    }
638                }
639                sendVerificationRequest(userId, verificationId, ivs);
640            }
641            mCurrentIntentFilterVerifications.clear();
642        }
643
644        private void sendVerificationRequest(int userId, int verificationId,
645                IntentFilterVerificationState ivs) {
646
647            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
648            verificationIntent.putExtra(
649                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
650                    verificationId);
651            verificationIntent.putExtra(
652                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
653                    getDefaultScheme());
654            verificationIntent.putExtra(
655                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
656                    ivs.getHostsString());
657            verificationIntent.putExtra(
658                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
659                    ivs.getPackageName());
660            verificationIntent.setComponent(mIntentFilterVerifierComponent);
661            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
662
663            UserHandle user = new UserHandle(userId);
664            mContext.sendBroadcastAsUser(verificationIntent, user);
665            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
666                    "Sending IntentFilter verification broadcast");
667        }
668
669        public void receiveVerificationResponse(int verificationId) {
670            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
671
672            final boolean verified = ivs.isVerified();
673
674            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
675            final int count = filters.size();
676            if (DEBUG_DOMAIN_VERIFICATION) {
677                Slog.i(TAG, "Received verification response " + verificationId
678                        + " for " + count + " filters, verified=" + verified);
679            }
680            for (int n=0; n<count; n++) {
681                PackageParser.ActivityIntentInfo filter = filters.get(n);
682                filter.setVerified(verified);
683
684                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
685                        + " verified with result:" + verified + " and hosts:"
686                        + ivs.getHostsString());
687            }
688
689            mIntentFilterVerificationStates.remove(verificationId);
690
691            final String packageName = ivs.getPackageName();
692            IntentFilterVerificationInfo ivi = null;
693
694            synchronized (mPackages) {
695                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
696            }
697            if (ivi == null) {
698                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
699                        + verificationId + " packageName:" + packageName);
700                return;
701            }
702            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
703                    "Updating IntentFilterVerificationInfo for verificationId:" + verificationId);
704
705            synchronized (mPackages) {
706                if (verified) {
707                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
708                } else {
709                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
710                }
711                scheduleWriteSettingsLocked();
712
713                final int userId = ivs.getUserId();
714                if (userId != UserHandle.USER_ALL) {
715                    final int userStatus =
716                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
717
718                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
719                    boolean needUpdate = false;
720
721                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
722                    // already been set by the User thru the Disambiguation dialog
723                    switch (userStatus) {
724                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
725                            if (verified) {
726                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
727                            } else {
728                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
729                            }
730                            needUpdate = true;
731                            break;
732
733                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
734                            if (verified) {
735                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
736                                needUpdate = true;
737                            }
738                            break;
739
740                        default:
741                            // Nothing to do
742                    }
743
744                    if (needUpdate) {
745                        mSettings.updateIntentFilterVerificationStatusLPw(
746                                packageName, updatedStatus, userId);
747                        scheduleWritePackageRestrictionsLocked(userId);
748                    }
749                }
750            }
751        }
752
753        @Override
754        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
755                    ActivityIntentInfo filter, String packageName) {
756            if (!hasValidDomains(filter)) {
757                return false;
758            }
759            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
760            if (ivs == null) {
761                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
762                        packageName);
763            }
764            if (DEBUG_DOMAIN_VERIFICATION) {
765                Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter);
766            }
767            ivs.addFilter(filter);
768            return true;
769        }
770
771        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
772                int userId, int verificationId, String packageName) {
773            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
774                    verifierUid, userId, packageName);
775            ivs.setPendingState();
776            synchronized (mPackages) {
777                mIntentFilterVerificationStates.append(verificationId, ivs);
778                mCurrentIntentFilterVerifications.add(verificationId);
779            }
780            return ivs;
781        }
782    }
783
784    private static boolean hasValidDomains(ActivityIntentInfo filter) {
785        boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
786                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS);
787        if (!hasHTTPorHTTPS) {
788            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
789                    "IntentFilter does not contain any HTTP or HTTPS data scheme");
790            return false;
791        }
792        return true;
793    }
794
795    private IntentFilterVerifier mIntentFilterVerifier;
796
797    // Set of pending broadcasts for aggregating enable/disable of components.
798    static class PendingPackageBroadcasts {
799        // for each user id, a map of <package name -> components within that package>
800        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
801
802        public PendingPackageBroadcasts() {
803            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
804        }
805
806        public ArrayList<String> get(int userId, String packageName) {
807            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
808            return packages.get(packageName);
809        }
810
811        public void put(int userId, String packageName, ArrayList<String> components) {
812            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
813            packages.put(packageName, components);
814        }
815
816        public void remove(int userId, String packageName) {
817            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
818            if (packages != null) {
819                packages.remove(packageName);
820            }
821        }
822
823        public void remove(int userId) {
824            mUidMap.remove(userId);
825        }
826
827        public int userIdCount() {
828            return mUidMap.size();
829        }
830
831        public int userIdAt(int n) {
832            return mUidMap.keyAt(n);
833        }
834
835        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
836            return mUidMap.get(userId);
837        }
838
839        public int size() {
840            // total number of pending broadcast entries across all userIds
841            int num = 0;
842            for (int i = 0; i< mUidMap.size(); i++) {
843                num += mUidMap.valueAt(i).size();
844            }
845            return num;
846        }
847
848        public void clear() {
849            mUidMap.clear();
850        }
851
852        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
853            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
854            if (map == null) {
855                map = new ArrayMap<String, ArrayList<String>>();
856                mUidMap.put(userId, map);
857            }
858            return map;
859        }
860    }
861    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
862
863    // Service Connection to remote media container service to copy
864    // package uri's from external media onto secure containers
865    // or internal storage.
866    private IMediaContainerService mContainerService = null;
867
868    static final int SEND_PENDING_BROADCAST = 1;
869    static final int MCS_BOUND = 3;
870    static final int END_COPY = 4;
871    static final int INIT_COPY = 5;
872    static final int MCS_UNBIND = 6;
873    static final int START_CLEANING_PACKAGE = 7;
874    static final int FIND_INSTALL_LOC = 8;
875    static final int POST_INSTALL = 9;
876    static final int MCS_RECONNECT = 10;
877    static final int MCS_GIVE_UP = 11;
878    static final int UPDATED_MEDIA_STATUS = 12;
879    static final int WRITE_SETTINGS = 13;
880    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
881    static final int PACKAGE_VERIFIED = 15;
882    static final int CHECK_PENDING_VERIFICATION = 16;
883    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
884    static final int INTENT_FILTER_VERIFIED = 18;
885
886    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
887
888    // Delay time in millisecs
889    static final int BROADCAST_DELAY = 10 * 1000;
890
891    static UserManagerService sUserManager;
892
893    // Stores a list of users whose package restrictions file needs to be updated
894    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
895
896    final private DefaultContainerConnection mDefContainerConn =
897            new DefaultContainerConnection();
898    class DefaultContainerConnection implements ServiceConnection {
899        public void onServiceConnected(ComponentName name, IBinder service) {
900            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
901            IMediaContainerService imcs =
902                IMediaContainerService.Stub.asInterface(service);
903            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
904        }
905
906        public void onServiceDisconnected(ComponentName name) {
907            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
908        }
909    }
910
911    // Recordkeeping of restore-after-install operations that are currently in flight
912    // between the Package Manager and the Backup Manager
913    class PostInstallData {
914        public InstallArgs args;
915        public PackageInstalledInfo res;
916
917        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
918            args = _a;
919            res = _r;
920        }
921    }
922
923    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
924    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
925
926    // XML tags for backup/restore of various bits of state
927    private static final String TAG_PREFERRED_BACKUP = "pa";
928    private static final String TAG_DEFAULT_APPS = "da";
929    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
930
931    final String mRequiredVerifierPackage;
932    final String mRequiredInstallerPackage;
933
934    private final PackageUsage mPackageUsage = new PackageUsage();
935
936    private class PackageUsage {
937        private static final int WRITE_INTERVAL
938            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
939
940        private final Object mFileLock = new Object();
941        private final AtomicLong mLastWritten = new AtomicLong(0);
942        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
943
944        private boolean mIsHistoricalPackageUsageAvailable = true;
945
946        boolean isHistoricalPackageUsageAvailable() {
947            return mIsHistoricalPackageUsageAvailable;
948        }
949
950        void write(boolean force) {
951            if (force) {
952                writeInternal();
953                return;
954            }
955            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
956                && !DEBUG_DEXOPT) {
957                return;
958            }
959            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
960                new Thread("PackageUsage_DiskWriter") {
961                    @Override
962                    public void run() {
963                        try {
964                            writeInternal();
965                        } finally {
966                            mBackgroundWriteRunning.set(false);
967                        }
968                    }
969                }.start();
970            }
971        }
972
973        private void writeInternal() {
974            synchronized (mPackages) {
975                synchronized (mFileLock) {
976                    AtomicFile file = getFile();
977                    FileOutputStream f = null;
978                    try {
979                        f = file.startWrite();
980                        BufferedOutputStream out = new BufferedOutputStream(f);
981                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
982                        StringBuilder sb = new StringBuilder();
983                        for (PackageParser.Package pkg : mPackages.values()) {
984                            if (pkg.mLastPackageUsageTimeInMills == 0) {
985                                continue;
986                            }
987                            sb.setLength(0);
988                            sb.append(pkg.packageName);
989                            sb.append(' ');
990                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
991                            sb.append('\n');
992                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
993                        }
994                        out.flush();
995                        file.finishWrite(f);
996                    } catch (IOException e) {
997                        if (f != null) {
998                            file.failWrite(f);
999                        }
1000                        Log.e(TAG, "Failed to write package usage times", e);
1001                    }
1002                }
1003            }
1004            mLastWritten.set(SystemClock.elapsedRealtime());
1005        }
1006
1007        void readLP() {
1008            synchronized (mFileLock) {
1009                AtomicFile file = getFile();
1010                BufferedInputStream in = null;
1011                try {
1012                    in = new BufferedInputStream(file.openRead());
1013                    StringBuffer sb = new StringBuffer();
1014                    while (true) {
1015                        String packageName = readToken(in, sb, ' ');
1016                        if (packageName == null) {
1017                            break;
1018                        }
1019                        String timeInMillisString = readToken(in, sb, '\n');
1020                        if (timeInMillisString == null) {
1021                            throw new IOException("Failed to find last usage time for package "
1022                                                  + packageName);
1023                        }
1024                        PackageParser.Package pkg = mPackages.get(packageName);
1025                        if (pkg == null) {
1026                            continue;
1027                        }
1028                        long timeInMillis;
1029                        try {
1030                            timeInMillis = Long.parseLong(timeInMillisString.toString());
1031                        } catch (NumberFormatException e) {
1032                            throw new IOException("Failed to parse " + timeInMillisString
1033                                                  + " as a long.", e);
1034                        }
1035                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1036                    }
1037                } catch (FileNotFoundException expected) {
1038                    mIsHistoricalPackageUsageAvailable = false;
1039                } catch (IOException e) {
1040                    Log.w(TAG, "Failed to read package usage times", e);
1041                } finally {
1042                    IoUtils.closeQuietly(in);
1043                }
1044            }
1045            mLastWritten.set(SystemClock.elapsedRealtime());
1046        }
1047
1048        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1049                throws IOException {
1050            sb.setLength(0);
1051            while (true) {
1052                int ch = in.read();
1053                if (ch == -1) {
1054                    if (sb.length() == 0) {
1055                        return null;
1056                    }
1057                    throw new IOException("Unexpected EOF");
1058                }
1059                if (ch == endOfToken) {
1060                    return sb.toString();
1061                }
1062                sb.append((char)ch);
1063            }
1064        }
1065
1066        private AtomicFile getFile() {
1067            File dataDir = Environment.getDataDirectory();
1068            File systemDir = new File(dataDir, "system");
1069            File fname = new File(systemDir, "package-usage.list");
1070            return new AtomicFile(fname);
1071        }
1072    }
1073
1074    class PackageHandler extends Handler {
1075        private boolean mBound = false;
1076        final ArrayList<HandlerParams> mPendingInstalls =
1077            new ArrayList<HandlerParams>();
1078
1079        private boolean connectToService() {
1080            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1081                    " DefaultContainerService");
1082            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1083            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1084            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1085                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
1086                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1087                mBound = true;
1088                return true;
1089            }
1090            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1091            return false;
1092        }
1093
1094        private void disconnectService() {
1095            mContainerService = null;
1096            mBound = false;
1097            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1098            mContext.unbindService(mDefContainerConn);
1099            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1100        }
1101
1102        PackageHandler(Looper looper) {
1103            super(looper);
1104        }
1105
1106        public void handleMessage(Message msg) {
1107            try {
1108                doHandleMessage(msg);
1109            } finally {
1110                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1111            }
1112        }
1113
1114        void doHandleMessage(Message msg) {
1115            switch (msg.what) {
1116                case INIT_COPY: {
1117                    HandlerParams params = (HandlerParams) msg.obj;
1118                    int idx = mPendingInstalls.size();
1119                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1120                    // If a bind was already initiated we dont really
1121                    // need to do anything. The pending install
1122                    // will be processed later on.
1123                    if (!mBound) {
1124                        // If this is the only one pending we might
1125                        // have to bind to the service again.
1126                        if (!connectToService()) {
1127                            Slog.e(TAG, "Failed to bind to media container service");
1128                            params.serviceError();
1129                            return;
1130                        } else {
1131                            // Once we bind to the service, the first
1132                            // pending request will be processed.
1133                            mPendingInstalls.add(idx, params);
1134                        }
1135                    } else {
1136                        mPendingInstalls.add(idx, params);
1137                        // Already bound to the service. Just make
1138                        // sure we trigger off processing the first request.
1139                        if (idx == 0) {
1140                            mHandler.sendEmptyMessage(MCS_BOUND);
1141                        }
1142                    }
1143                    break;
1144                }
1145                case MCS_BOUND: {
1146                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1147                    if (msg.obj != null) {
1148                        mContainerService = (IMediaContainerService) msg.obj;
1149                    }
1150                    if (mContainerService == null) {
1151                        if (!mBound) {
1152                            // Something seriously wrong since we are not bound and we are not
1153                            // waiting for connection. Bail out.
1154                            Slog.e(TAG, "Cannot bind to media container service");
1155                            for (HandlerParams params : mPendingInstalls) {
1156                                // Indicate service bind error
1157                                params.serviceError();
1158                            }
1159                            mPendingInstalls.clear();
1160                        } else {
1161                            Slog.w(TAG, "Waiting to connect to media container service");
1162                        }
1163                    } else if (mPendingInstalls.size() > 0) {
1164                        HandlerParams params = mPendingInstalls.get(0);
1165                        if (params != null) {
1166                            if (params.startCopy()) {
1167                                // We are done...  look for more work or to
1168                                // go idle.
1169                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1170                                        "Checking for more work or unbind...");
1171                                // Delete pending install
1172                                if (mPendingInstalls.size() > 0) {
1173                                    mPendingInstalls.remove(0);
1174                                }
1175                                if (mPendingInstalls.size() == 0) {
1176                                    if (mBound) {
1177                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1178                                                "Posting delayed MCS_UNBIND");
1179                                        removeMessages(MCS_UNBIND);
1180                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1181                                        // Unbind after a little delay, to avoid
1182                                        // continual thrashing.
1183                                        sendMessageDelayed(ubmsg, 10000);
1184                                    }
1185                                } else {
1186                                    // There are more pending requests in queue.
1187                                    // Just post MCS_BOUND message to trigger processing
1188                                    // of next pending install.
1189                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1190                                            "Posting MCS_BOUND for next work");
1191                                    mHandler.sendEmptyMessage(MCS_BOUND);
1192                                }
1193                            }
1194                        }
1195                    } else {
1196                        // Should never happen ideally.
1197                        Slog.w(TAG, "Empty queue");
1198                    }
1199                    break;
1200                }
1201                case MCS_RECONNECT: {
1202                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1203                    if (mPendingInstalls.size() > 0) {
1204                        if (mBound) {
1205                            disconnectService();
1206                        }
1207                        if (!connectToService()) {
1208                            Slog.e(TAG, "Failed to bind to media container service");
1209                            for (HandlerParams params : mPendingInstalls) {
1210                                // Indicate service bind error
1211                                params.serviceError();
1212                            }
1213                            mPendingInstalls.clear();
1214                        }
1215                    }
1216                    break;
1217                }
1218                case MCS_UNBIND: {
1219                    // If there is no actual work left, then time to unbind.
1220                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1221
1222                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1223                        if (mBound) {
1224                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1225
1226                            disconnectService();
1227                        }
1228                    } else if (mPendingInstalls.size() > 0) {
1229                        // There are more pending requests in queue.
1230                        // Just post MCS_BOUND message to trigger processing
1231                        // of next pending install.
1232                        mHandler.sendEmptyMessage(MCS_BOUND);
1233                    }
1234
1235                    break;
1236                }
1237                case MCS_GIVE_UP: {
1238                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1239                    mPendingInstalls.remove(0);
1240                    break;
1241                }
1242                case SEND_PENDING_BROADCAST: {
1243                    String packages[];
1244                    ArrayList<String> components[];
1245                    int size = 0;
1246                    int uids[];
1247                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1248                    synchronized (mPackages) {
1249                        if (mPendingBroadcasts == null) {
1250                            return;
1251                        }
1252                        size = mPendingBroadcasts.size();
1253                        if (size <= 0) {
1254                            // Nothing to be done. Just return
1255                            return;
1256                        }
1257                        packages = new String[size];
1258                        components = new ArrayList[size];
1259                        uids = new int[size];
1260                        int i = 0;  // filling out the above arrays
1261
1262                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1263                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1264                            Iterator<Map.Entry<String, ArrayList<String>>> it
1265                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1266                                            .entrySet().iterator();
1267                            while (it.hasNext() && i < size) {
1268                                Map.Entry<String, ArrayList<String>> ent = it.next();
1269                                packages[i] = ent.getKey();
1270                                components[i] = ent.getValue();
1271                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1272                                uids[i] = (ps != null)
1273                                        ? UserHandle.getUid(packageUserId, ps.appId)
1274                                        : -1;
1275                                i++;
1276                            }
1277                        }
1278                        size = i;
1279                        mPendingBroadcasts.clear();
1280                    }
1281                    // Send broadcasts
1282                    for (int i = 0; i < size; i++) {
1283                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1284                    }
1285                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1286                    break;
1287                }
1288                case START_CLEANING_PACKAGE: {
1289                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1290                    final String packageName = (String)msg.obj;
1291                    final int userId = msg.arg1;
1292                    final boolean andCode = msg.arg2 != 0;
1293                    synchronized (mPackages) {
1294                        if (userId == UserHandle.USER_ALL) {
1295                            int[] users = sUserManager.getUserIds();
1296                            for (int user : users) {
1297                                mSettings.addPackageToCleanLPw(
1298                                        new PackageCleanItem(user, packageName, andCode));
1299                            }
1300                        } else {
1301                            mSettings.addPackageToCleanLPw(
1302                                    new PackageCleanItem(userId, packageName, andCode));
1303                        }
1304                    }
1305                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1306                    startCleaningPackages();
1307                } break;
1308                case POST_INSTALL: {
1309                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1310                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1311                    mRunningInstalls.delete(msg.arg1);
1312                    boolean deleteOld = false;
1313
1314                    if (data != null) {
1315                        InstallArgs args = data.args;
1316                        PackageInstalledInfo res = data.res;
1317
1318                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1319                            final String packageName = res.pkg.applicationInfo.packageName;
1320                            res.removedInfo.sendBroadcast(false, true, false);
1321                            Bundle extras = new Bundle(1);
1322                            extras.putInt(Intent.EXTRA_UID, res.uid);
1323
1324                            // Now that we successfully installed the package, grant runtime
1325                            // permissions if requested before broadcasting the install.
1326                            if ((args.installFlags
1327                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) {
1328                                grantRequestedRuntimePermissions(res.pkg,
1329                                        args.user.getIdentifier());
1330                            }
1331
1332                            // Determine the set of users who are adding this
1333                            // package for the first time vs. those who are seeing
1334                            // an update.
1335                            int[] firstUsers;
1336                            int[] updateUsers = new int[0];
1337                            if (res.origUsers == null || res.origUsers.length == 0) {
1338                                firstUsers = res.newUsers;
1339                            } else {
1340                                firstUsers = new int[0];
1341                                for (int i=0; i<res.newUsers.length; i++) {
1342                                    int user = res.newUsers[i];
1343                                    boolean isNew = true;
1344                                    for (int j=0; j<res.origUsers.length; j++) {
1345                                        if (res.origUsers[j] == user) {
1346                                            isNew = false;
1347                                            break;
1348                                        }
1349                                    }
1350                                    if (isNew) {
1351                                        int[] newFirst = new int[firstUsers.length+1];
1352                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1353                                                firstUsers.length);
1354                                        newFirst[firstUsers.length] = user;
1355                                        firstUsers = newFirst;
1356                                    } else {
1357                                        int[] newUpdate = new int[updateUsers.length+1];
1358                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1359                                                updateUsers.length);
1360                                        newUpdate[updateUsers.length] = user;
1361                                        updateUsers = newUpdate;
1362                                    }
1363                                }
1364                            }
1365                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1366                                    packageName, extras, null, null, firstUsers);
1367                            final boolean update = res.removedInfo.removedPackage != null;
1368                            if (update) {
1369                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1370                            }
1371                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1372                                    packageName, extras, null, null, updateUsers);
1373                            if (update) {
1374                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1375                                        packageName, extras, null, null, updateUsers);
1376                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1377                                        null, null, packageName, null, updateUsers);
1378
1379                                // treat asec-hosted packages like removable media on upgrade
1380                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1381                                    if (DEBUG_INSTALL) {
1382                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1383                                                + " is ASEC-hosted -> AVAILABLE");
1384                                    }
1385                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1386                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1387                                    pkgList.add(packageName);
1388                                    sendResourcesChangedBroadcast(true, true,
1389                                            pkgList,uidArray, null);
1390                                }
1391                            }
1392                            if (res.removedInfo.args != null) {
1393                                // Remove the replaced package's older resources safely now
1394                                deleteOld = true;
1395                            }
1396
1397                            // If this app is a browser and it's newly-installed for some
1398                            // users, clear any default-browser state in those users
1399                            if (firstUsers.length > 0) {
1400                                // the app's nature doesn't depend on the user, so we can just
1401                                // check its browser nature in any user and generalize.
1402                                if (packageIsBrowser(packageName, firstUsers[0])) {
1403                                    synchronized (mPackages) {
1404                                        for (int userId : firstUsers) {
1405                                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1406                                        }
1407                                    }
1408                                }
1409                            }
1410                            // Log current value of "unknown sources" setting
1411                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1412                                getUnknownSourcesSettings());
1413                        }
1414                        // Force a gc to clear up things
1415                        Runtime.getRuntime().gc();
1416                        // We delete after a gc for applications  on sdcard.
1417                        if (deleteOld) {
1418                            synchronized (mInstallLock) {
1419                                res.removedInfo.args.doPostDeleteLI(true);
1420                            }
1421                        }
1422                        if (args.observer != null) {
1423                            try {
1424                                Bundle extras = extrasForInstallResult(res);
1425                                args.observer.onPackageInstalled(res.name, res.returnCode,
1426                                        res.returnMsg, extras);
1427                            } catch (RemoteException e) {
1428                                Slog.i(TAG, "Observer no longer exists.");
1429                            }
1430                        }
1431                    } else {
1432                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1433                    }
1434                } break;
1435                case UPDATED_MEDIA_STATUS: {
1436                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1437                    boolean reportStatus = msg.arg1 == 1;
1438                    boolean doGc = msg.arg2 == 1;
1439                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1440                    if (doGc) {
1441                        // Force a gc to clear up stale containers.
1442                        Runtime.getRuntime().gc();
1443                    }
1444                    if (msg.obj != null) {
1445                        @SuppressWarnings("unchecked")
1446                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1447                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1448                        // Unload containers
1449                        unloadAllContainers(args);
1450                    }
1451                    if (reportStatus) {
1452                        try {
1453                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1454                            PackageHelper.getMountService().finishMediaUpdate();
1455                        } catch (RemoteException e) {
1456                            Log.e(TAG, "MountService not running?");
1457                        }
1458                    }
1459                } break;
1460                case WRITE_SETTINGS: {
1461                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1462                    synchronized (mPackages) {
1463                        removeMessages(WRITE_SETTINGS);
1464                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1465                        mSettings.writeLPr();
1466                        mDirtyUsers.clear();
1467                    }
1468                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1469                } break;
1470                case WRITE_PACKAGE_RESTRICTIONS: {
1471                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1472                    synchronized (mPackages) {
1473                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1474                        for (int userId : mDirtyUsers) {
1475                            mSettings.writePackageRestrictionsLPr(userId);
1476                        }
1477                        mDirtyUsers.clear();
1478                    }
1479                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1480                } break;
1481                case CHECK_PENDING_VERIFICATION: {
1482                    final int verificationId = msg.arg1;
1483                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1484
1485                    if ((state != null) && !state.timeoutExtended()) {
1486                        final InstallArgs args = state.getInstallArgs();
1487                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1488
1489                        Slog.i(TAG, "Verification timed out for " + originUri);
1490                        mPendingVerification.remove(verificationId);
1491
1492                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1493
1494                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1495                            Slog.i(TAG, "Continuing with installation of " + originUri);
1496                            state.setVerifierResponse(Binder.getCallingUid(),
1497                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1498                            broadcastPackageVerified(verificationId, originUri,
1499                                    PackageManager.VERIFICATION_ALLOW,
1500                                    state.getInstallArgs().getUser());
1501                            try {
1502                                ret = args.copyApk(mContainerService, true);
1503                            } catch (RemoteException e) {
1504                                Slog.e(TAG, "Could not contact the ContainerService");
1505                            }
1506                        } else {
1507                            broadcastPackageVerified(verificationId, originUri,
1508                                    PackageManager.VERIFICATION_REJECT,
1509                                    state.getInstallArgs().getUser());
1510                        }
1511
1512                        processPendingInstall(args, ret);
1513                        mHandler.sendEmptyMessage(MCS_UNBIND);
1514                    }
1515                    break;
1516                }
1517                case PACKAGE_VERIFIED: {
1518                    final int verificationId = msg.arg1;
1519
1520                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1521                    if (state == null) {
1522                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1523                        break;
1524                    }
1525
1526                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1527
1528                    state.setVerifierResponse(response.callerUid, response.code);
1529
1530                    if (state.isVerificationComplete()) {
1531                        mPendingVerification.remove(verificationId);
1532
1533                        final InstallArgs args = state.getInstallArgs();
1534                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1535
1536                        int ret;
1537                        if (state.isInstallAllowed()) {
1538                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1539                            broadcastPackageVerified(verificationId, originUri,
1540                                    response.code, state.getInstallArgs().getUser());
1541                            try {
1542                                ret = args.copyApk(mContainerService, true);
1543                            } catch (RemoteException e) {
1544                                Slog.e(TAG, "Could not contact the ContainerService");
1545                            }
1546                        } else {
1547                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1548                        }
1549
1550                        processPendingInstall(args, ret);
1551
1552                        mHandler.sendEmptyMessage(MCS_UNBIND);
1553                    }
1554
1555                    break;
1556                }
1557                case START_INTENT_FILTER_VERIFICATIONS: {
1558                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1559                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1560                            params.replacing, params.pkg);
1561                    break;
1562                }
1563                case INTENT_FILTER_VERIFIED: {
1564                    final int verificationId = msg.arg1;
1565
1566                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1567                            verificationId);
1568                    if (state == null) {
1569                        Slog.w(TAG, "Invalid IntentFilter verification token "
1570                                + verificationId + " received");
1571                        break;
1572                    }
1573
1574                    final int userId = state.getUserId();
1575
1576                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1577                            "Processing IntentFilter verification with token:"
1578                            + verificationId + " and userId:" + userId);
1579
1580                    final IntentFilterVerificationResponse response =
1581                            (IntentFilterVerificationResponse) msg.obj;
1582
1583                    state.setVerifierResponse(response.callerUid, response.code);
1584
1585                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1586                            "IntentFilter verification with token:" + verificationId
1587                            + " and userId:" + userId
1588                            + " is settings verifier response with response code:"
1589                            + response.code);
1590
1591                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1592                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1593                                + response.getFailedDomainsString());
1594                    }
1595
1596                    if (state.isVerificationComplete()) {
1597                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1598                    } else {
1599                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1600                                "IntentFilter verification with token:" + verificationId
1601                                + " was not said to be complete");
1602                    }
1603
1604                    break;
1605                }
1606            }
1607        }
1608    }
1609
1610    private StorageEventListener mStorageListener = new StorageEventListener() {
1611        @Override
1612        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1613            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1614                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1615                    final String volumeUuid = vol.getFsUuid();
1616
1617                    // Clean up any users or apps that were removed or recreated
1618                    // while this volume was missing
1619                    reconcileUsers(volumeUuid);
1620                    reconcileApps(volumeUuid);
1621
1622                    // Clean up any install sessions that expired or were
1623                    // cancelled while this volume was missing
1624                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1625
1626                    loadPrivatePackages(vol);
1627
1628                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1629                    unloadPrivatePackages(vol);
1630                }
1631            }
1632
1633            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1634                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1635                    updateExternalMediaStatus(true, false);
1636                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1637                    updateExternalMediaStatus(false, false);
1638                }
1639            }
1640        }
1641
1642        @Override
1643        public void onVolumeForgotten(String fsUuid) {
1644            // Remove any apps installed on the forgotten volume
1645            synchronized (mPackages) {
1646                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1647                for (PackageSetting ps : packages) {
1648                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1649                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1650                            UserHandle.USER_OWNER, PackageManager.DELETE_ALL_USERS);
1651                }
1652
1653                mSettings.writeLPr();
1654            }
1655        }
1656    };
1657
1658    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) {
1659        if (userId >= UserHandle.USER_OWNER) {
1660            grantRequestedRuntimePermissionsForUser(pkg, userId);
1661        } else if (userId == UserHandle.USER_ALL) {
1662            for (int someUserId : UserManagerService.getInstance().getUserIds()) {
1663                grantRequestedRuntimePermissionsForUser(pkg, someUserId);
1664            }
1665        }
1666
1667        // We could have touched GID membership, so flush out packages.list
1668        synchronized (mPackages) {
1669            mSettings.writePackageListLPr();
1670        }
1671    }
1672
1673    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) {
1674        SettingBase sb = (SettingBase) pkg.mExtras;
1675        if (sb == null) {
1676            return;
1677        }
1678
1679        PermissionsState permissionsState = sb.getPermissionsState();
1680
1681        for (String permission : pkg.requestedPermissions) {
1682            BasePermission bp = mSettings.mPermissions.get(permission);
1683            if (bp != null && bp.isRuntime()) {
1684                permissionsState.grantRuntimePermission(bp, userId);
1685            }
1686        }
1687    }
1688
1689    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1690        Bundle extras = null;
1691        switch (res.returnCode) {
1692            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1693                extras = new Bundle();
1694                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1695                        res.origPermission);
1696                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1697                        res.origPackage);
1698                break;
1699            }
1700            case PackageManager.INSTALL_SUCCEEDED: {
1701                extras = new Bundle();
1702                extras.putBoolean(Intent.EXTRA_REPLACING,
1703                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1704                break;
1705            }
1706        }
1707        return extras;
1708    }
1709
1710    void scheduleWriteSettingsLocked() {
1711        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1712            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1713        }
1714    }
1715
1716    void scheduleWritePackageRestrictionsLocked(int userId) {
1717        if (!sUserManager.exists(userId)) return;
1718        mDirtyUsers.add(userId);
1719        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1720            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1721        }
1722    }
1723
1724    public static PackageManagerService main(Context context, Installer installer,
1725            boolean factoryTest, boolean onlyCore) {
1726        PackageManagerService m = new PackageManagerService(context, installer,
1727                factoryTest, onlyCore);
1728        ServiceManager.addService("package", m);
1729        return m;
1730    }
1731
1732    static String[] splitString(String str, char sep) {
1733        int count = 1;
1734        int i = 0;
1735        while ((i=str.indexOf(sep, i)) >= 0) {
1736            count++;
1737            i++;
1738        }
1739
1740        String[] res = new String[count];
1741        i=0;
1742        count = 0;
1743        int lastI=0;
1744        while ((i=str.indexOf(sep, i)) >= 0) {
1745            res[count] = str.substring(lastI, i);
1746            count++;
1747            i++;
1748            lastI = i;
1749        }
1750        res[count] = str.substring(lastI, str.length());
1751        return res;
1752    }
1753
1754    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1755        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1756                Context.DISPLAY_SERVICE);
1757        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1758    }
1759
1760    public PackageManagerService(Context context, Installer installer,
1761            boolean factoryTest, boolean onlyCore) {
1762        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1763                SystemClock.uptimeMillis());
1764
1765        if (mSdkVersion <= 0) {
1766            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1767        }
1768
1769        mContext = context;
1770        mFactoryTest = factoryTest;
1771        mOnlyCore = onlyCore;
1772        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1773        mMetrics = new DisplayMetrics();
1774        mSettings = new Settings(mPackages);
1775        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1776                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1777        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1778                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1779        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1780                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1781        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1782                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1783        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1784                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1785        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1786                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1787
1788        // TODO: add a property to control this?
1789        long dexOptLRUThresholdInMinutes;
1790        if (mLazyDexOpt) {
1791            dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1792        } else {
1793            dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1794        }
1795        mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1796
1797        String separateProcesses = SystemProperties.get("debug.separate_processes");
1798        if (separateProcesses != null && separateProcesses.length() > 0) {
1799            if ("*".equals(separateProcesses)) {
1800                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1801                mSeparateProcesses = null;
1802                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1803            } else {
1804                mDefParseFlags = 0;
1805                mSeparateProcesses = separateProcesses.split(",");
1806                Slog.w(TAG, "Running with debug.separate_processes: "
1807                        + separateProcesses);
1808            }
1809        } else {
1810            mDefParseFlags = 0;
1811            mSeparateProcesses = null;
1812        }
1813
1814        mInstaller = installer;
1815        mPackageDexOptimizer = new PackageDexOptimizer(this);
1816        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1817
1818        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1819                FgThread.get().getLooper());
1820
1821        getDefaultDisplayMetrics(context, mMetrics);
1822
1823        SystemConfig systemConfig = SystemConfig.getInstance();
1824        mGlobalGids = systemConfig.getGlobalGids();
1825        mSystemPermissions = systemConfig.getSystemPermissions();
1826        mAvailableFeatures = systemConfig.getAvailableFeatures();
1827
1828        synchronized (mInstallLock) {
1829        // writer
1830        synchronized (mPackages) {
1831            mHandlerThread = new ServiceThread(TAG,
1832                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1833            mHandlerThread.start();
1834            mHandler = new PackageHandler(mHandlerThread.getLooper());
1835            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1836
1837            File dataDir = Environment.getDataDirectory();
1838            mAppDataDir = new File(dataDir, "data");
1839            mAppInstallDir = new File(dataDir, "app");
1840            mAppLib32InstallDir = new File(dataDir, "app-lib");
1841            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1842            mUserAppDataDir = new File(dataDir, "user");
1843            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1844
1845            sUserManager = new UserManagerService(context, this,
1846                    mInstallLock, mPackages);
1847
1848            // Propagate permission configuration in to package manager.
1849            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1850                    = systemConfig.getPermissions();
1851            for (int i=0; i<permConfig.size(); i++) {
1852                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1853                BasePermission bp = mSettings.mPermissions.get(perm.name);
1854                if (bp == null) {
1855                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1856                    mSettings.mPermissions.put(perm.name, bp);
1857                }
1858                if (perm.gids != null) {
1859                    bp.setGids(perm.gids, perm.perUser);
1860                }
1861            }
1862
1863            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1864            for (int i=0; i<libConfig.size(); i++) {
1865                mSharedLibraries.put(libConfig.keyAt(i),
1866                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1867            }
1868
1869            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1870
1871            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1872                    mSdkVersion, mOnlyCore);
1873
1874            String customResolverActivity = Resources.getSystem().getString(
1875                    R.string.config_customResolverActivity);
1876            if (TextUtils.isEmpty(customResolverActivity)) {
1877                customResolverActivity = null;
1878            } else {
1879                mCustomResolverComponentName = ComponentName.unflattenFromString(
1880                        customResolverActivity);
1881            }
1882
1883            long startTime = SystemClock.uptimeMillis();
1884
1885            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1886                    startTime);
1887
1888            // Set flag to monitor and not change apk file paths when
1889            // scanning install directories.
1890            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
1891
1892            final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1893
1894            /**
1895             * Add everything in the in the boot class path to the
1896             * list of process files because dexopt will have been run
1897             * if necessary during zygote startup.
1898             */
1899            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1900            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1901
1902            if (bootClassPath != null) {
1903                String[] bootClassPathElements = splitString(bootClassPath, ':');
1904                for (String element : bootClassPathElements) {
1905                    alreadyDexOpted.add(element);
1906                }
1907            } else {
1908                Slog.w(TAG, "No BOOTCLASSPATH found!");
1909            }
1910
1911            if (systemServerClassPath != null) {
1912                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1913                for (String element : systemServerClassPathElements) {
1914                    alreadyDexOpted.add(element);
1915                }
1916            } else {
1917                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1918            }
1919
1920            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
1921            final String[] dexCodeInstructionSets =
1922                    getDexCodeInstructionSets(
1923                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
1924
1925            /**
1926             * Ensure all external libraries have had dexopt run on them.
1927             */
1928            if (mSharedLibraries.size() > 0) {
1929                // NOTE: For now, we're compiling these system "shared libraries"
1930                // (and framework jars) into all available architectures. It's possible
1931                // to compile them only when we come across an app that uses them (there's
1932                // already logic for that in scanPackageLI) but that adds some complexity.
1933                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1934                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1935                        final String lib = libEntry.path;
1936                        if (lib == null) {
1937                            continue;
1938                        }
1939
1940                        try {
1941                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
1942                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1943                                alreadyDexOpted.add(lib);
1944                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1945                            }
1946                        } catch (FileNotFoundException e) {
1947                            Slog.w(TAG, "Library not found: " + lib);
1948                        } catch (IOException e) {
1949                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1950                                    + e.getMessage());
1951                        }
1952                    }
1953                }
1954            }
1955
1956            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1957
1958            // Gross hack for now: we know this file doesn't contain any
1959            // code, so don't dexopt it to avoid the resulting log spew.
1960            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1961
1962            // Gross hack for now: we know this file is only part of
1963            // the boot class path for art, so don't dexopt it to
1964            // avoid the resulting log spew.
1965            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1966
1967            /**
1968             * There are a number of commands implemented in Java, which
1969             * we currently need to do the dexopt on so that they can be
1970             * run from a non-root shell.
1971             */
1972            String[] frameworkFiles = frameworkDir.list();
1973            if (frameworkFiles != null) {
1974                // TODO: We could compile these only for the most preferred ABI. We should
1975                // first double check that the dex files for these commands are not referenced
1976                // by other system apps.
1977                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1978                    for (int i=0; i<frameworkFiles.length; i++) {
1979                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1980                        String path = libPath.getPath();
1981                        // Skip the file if we already did it.
1982                        if (alreadyDexOpted.contains(path)) {
1983                            continue;
1984                        }
1985                        // Skip the file if it is not a type we want to dexopt.
1986                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1987                            continue;
1988                        }
1989                        try {
1990                            int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false);
1991                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1992                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1993                            }
1994                        } catch (FileNotFoundException e) {
1995                            Slog.w(TAG, "Jar not found: " + path);
1996                        } catch (IOException e) {
1997                            Slog.w(TAG, "Exception reading jar: " + path, e);
1998                        }
1999                    }
2000                }
2001            }
2002
2003            // Collect vendor overlay packages.
2004            // (Do this before scanning any apps.)
2005            // For security and version matching reason, only consider
2006            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2007            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2008            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2009                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2010
2011            // Find base frameworks (resource packages without code).
2012            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2013                    | PackageParser.PARSE_IS_SYSTEM_DIR
2014                    | PackageParser.PARSE_IS_PRIVILEGED,
2015                    scanFlags | SCAN_NO_DEX, 0);
2016
2017            // Collected privileged system packages.
2018            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2019            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2020                    | PackageParser.PARSE_IS_SYSTEM_DIR
2021                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2022
2023            // Collect ordinary system packages.
2024            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2025            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2026                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2027
2028            // Collect all vendor packages.
2029            File vendorAppDir = new File("/vendor/app");
2030            try {
2031                vendorAppDir = vendorAppDir.getCanonicalFile();
2032            } catch (IOException e) {
2033                // failed to look up canonical path, continue with original one
2034            }
2035            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2036                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2037
2038            // Collect all OEM packages.
2039            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2040            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2041                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2042
2043            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
2044            mInstaller.moveFiles();
2045
2046            // Prune any system packages that no longer exist.
2047            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2048            final ArrayMap<String, File> expectingBetter = new ArrayMap<>();
2049            if (!mOnlyCore) {
2050                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2051                while (psit.hasNext()) {
2052                    PackageSetting ps = psit.next();
2053
2054                    /*
2055                     * If this is not a system app, it can't be a
2056                     * disable system app.
2057                     */
2058                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2059                        continue;
2060                    }
2061
2062                    /*
2063                     * If the package is scanned, it's not erased.
2064                     */
2065                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2066                    if (scannedPkg != null) {
2067                        /*
2068                         * If the system app is both scanned and in the
2069                         * disabled packages list, then it must have been
2070                         * added via OTA. Remove it from the currently
2071                         * scanned package so the previously user-installed
2072                         * application can be scanned.
2073                         */
2074                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2075                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2076                                    + ps.name + "; removing system app.  Last known codePath="
2077                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2078                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2079                                    + scannedPkg.mVersionCode);
2080                            removePackageLI(ps, true);
2081                            expectingBetter.put(ps.name, ps.codePath);
2082                        }
2083
2084                        continue;
2085                    }
2086
2087                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2088                        psit.remove();
2089                        logCriticalInfo(Log.WARN, "System package " + ps.name
2090                                + " no longer exists; wiping its data");
2091                        removeDataDirsLI(null, ps.name);
2092                    } else {
2093                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2094                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2095                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2096                        }
2097                    }
2098                }
2099            }
2100
2101            //look for any incomplete package installations
2102            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2103            //clean up list
2104            for(int i = 0; i < deletePkgsList.size(); i++) {
2105                //clean up here
2106                cleanupInstallFailedPackage(deletePkgsList.get(i));
2107            }
2108            //delete tmp files
2109            deleteTempPackageFiles();
2110
2111            // Remove any shared userIDs that have no associated packages
2112            mSettings.pruneSharedUsersLPw();
2113
2114            if (!mOnlyCore) {
2115                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2116                        SystemClock.uptimeMillis());
2117                scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2118
2119                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2120                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2121
2122                /**
2123                 * Remove disable package settings for any updated system
2124                 * apps that were removed via an OTA. If they're not a
2125                 * previously-updated app, remove them completely.
2126                 * Otherwise, just revoke their system-level permissions.
2127                 */
2128                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2129                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2130                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2131
2132                    String msg;
2133                    if (deletedPkg == null) {
2134                        msg = "Updated system package " + deletedAppName
2135                                + " no longer exists; wiping its data";
2136                        removeDataDirsLI(null, deletedAppName);
2137                    } else {
2138                        msg = "Updated system app + " + deletedAppName
2139                                + " no longer present; removing system privileges for "
2140                                + deletedAppName;
2141
2142                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2143
2144                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2145                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2146                    }
2147                    logCriticalInfo(Log.WARN, msg);
2148                }
2149
2150                /**
2151                 * Make sure all system apps that we expected to appear on
2152                 * the userdata partition actually showed up. If they never
2153                 * appeared, crawl back and revive the system version.
2154                 */
2155                for (int i = 0; i < expectingBetter.size(); i++) {
2156                    final String packageName = expectingBetter.keyAt(i);
2157                    if (!mPackages.containsKey(packageName)) {
2158                        final File scanFile = expectingBetter.valueAt(i);
2159
2160                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2161                                + " but never showed up; reverting to system");
2162
2163                        final int reparseFlags;
2164                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2165                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2166                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2167                                    | PackageParser.PARSE_IS_PRIVILEGED;
2168                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2169                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2170                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2171                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2172                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2173                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2174                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2175                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2176                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2177                        } else {
2178                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2179                            continue;
2180                        }
2181
2182                        mSettings.enableSystemPackageLPw(packageName);
2183
2184                        try {
2185                            scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
2186                        } catch (PackageManagerException e) {
2187                            Slog.e(TAG, "Failed to parse original system package: "
2188                                    + e.getMessage());
2189                        }
2190                    }
2191                }
2192            }
2193
2194            // Now that we know all of the shared libraries, update all clients to have
2195            // the correct library paths.
2196            updateAllSharedLibrariesLPw();
2197
2198            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2199                // NOTE: We ignore potential failures here during a system scan (like
2200                // the rest of the commands above) because there's precious little we
2201                // can do about it. A settings error is reported, though.
2202                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2203                        false /* force dexopt */, false /* defer dexopt */);
2204            }
2205
2206            // Now that we know all the packages we are keeping,
2207            // read and update their last usage times.
2208            mPackageUsage.readLP();
2209
2210            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2211                    SystemClock.uptimeMillis());
2212            Slog.i(TAG, "Time to scan packages: "
2213                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2214                    + " seconds");
2215
2216            // If the platform SDK has changed since the last time we booted,
2217            // we need to re-grant app permission to catch any new ones that
2218            // appear.  This is really a hack, and means that apps can in some
2219            // cases get permissions that the user didn't initially explicitly
2220            // allow...  it would be nice to have some better way to handle
2221            // this situation.
2222            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
2223                    != mSdkVersion;
2224            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
2225                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
2226                    + "; regranting permissions for internal storage");
2227            mSettings.mInternalSdkPlatform = mSdkVersion;
2228
2229            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
2230                    | (regrantPermissions
2231                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
2232                            : 0));
2233
2234            // If this is the first boot, and it is a normal boot, then
2235            // we need to initialize the default preferred apps.
2236            if (!mRestoredSettings && !onlyCore) {
2237                mSettings.applyDefaultPreferredAppsLPw(this, UserHandle.USER_OWNER);
2238                applyFactoryDefaultBrowserLPw(UserHandle.USER_OWNER);
2239            }
2240
2241            // If this is first boot after an OTA, and a normal boot, then
2242            // we need to clear code cache directories.
2243            mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint);
2244            if (mIsUpgrade && !onlyCore) {
2245                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2246                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2247                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2248                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2249                }
2250                mSettings.mFingerprint = Build.FINGERPRINT;
2251            }
2252
2253            primeDomainVerificationsLPw();
2254            checkDefaultBrowser();
2255
2256            // All the changes are done during package scanning.
2257            mSettings.updateInternalDatabaseVersion();
2258
2259            // can downgrade to reader
2260            mSettings.writeLPr();
2261
2262            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2263                    SystemClock.uptimeMillis());
2264
2265            mRequiredVerifierPackage = getRequiredVerifierLPr();
2266            mRequiredInstallerPackage = getRequiredInstallerLPr();
2267
2268            mInstallerService = new PackageInstallerService(context, this);
2269
2270            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2271            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2272                    mIntentFilterVerifierComponent);
2273
2274        } // synchronized (mPackages)
2275        } // synchronized (mInstallLock)
2276
2277        // Now after opening every single application zip, make sure they
2278        // are all flushed.  Not really needed, but keeps things nice and
2279        // tidy.
2280        Runtime.getRuntime().gc();
2281
2282        // Expose private service for system components to use.
2283        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2284    }
2285
2286    @Override
2287    public boolean isFirstBoot() {
2288        return !mRestoredSettings;
2289    }
2290
2291    @Override
2292    public boolean isOnlyCoreApps() {
2293        return mOnlyCore;
2294    }
2295
2296    @Override
2297    public boolean isUpgrade() {
2298        return mIsUpgrade;
2299    }
2300
2301    private String getRequiredVerifierLPr() {
2302        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2303        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2304                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
2305
2306        String requiredVerifier = null;
2307
2308        final int N = receivers.size();
2309        for (int i = 0; i < N; i++) {
2310            final ResolveInfo info = receivers.get(i);
2311
2312            if (info.activityInfo == null) {
2313                continue;
2314            }
2315
2316            final String packageName = info.activityInfo.packageName;
2317
2318            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2319                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2320                continue;
2321            }
2322
2323            if (requiredVerifier != null) {
2324                throw new RuntimeException("There can be only one required verifier");
2325            }
2326
2327            requiredVerifier = packageName;
2328        }
2329
2330        return requiredVerifier;
2331    }
2332
2333    private String getRequiredInstallerLPr() {
2334        Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2335        installerIntent.addCategory(Intent.CATEGORY_DEFAULT);
2336        installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2337
2338        final List<ResolveInfo> installers = queryIntentActivities(installerIntent,
2339                PACKAGE_MIME_TYPE, 0, 0);
2340
2341        String requiredInstaller = null;
2342
2343        final int N = installers.size();
2344        for (int i = 0; i < N; i++) {
2345            final ResolveInfo info = installers.get(i);
2346            final String packageName = info.activityInfo.packageName;
2347
2348            if (!info.activityInfo.applicationInfo.isSystemApp()) {
2349                continue;
2350            }
2351
2352            if (requiredInstaller != null) {
2353                throw new RuntimeException("There must be one required installer");
2354            }
2355
2356            requiredInstaller = packageName;
2357        }
2358
2359        if (requiredInstaller == null) {
2360            throw new RuntimeException("There must be one required installer");
2361        }
2362
2363        return requiredInstaller;
2364    }
2365
2366    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2367        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2368        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2369                PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */);
2370
2371        ComponentName verifierComponentName = null;
2372
2373        int priority = -1000;
2374        final int N = receivers.size();
2375        for (int i = 0; i < N; i++) {
2376            final ResolveInfo info = receivers.get(i);
2377
2378            if (info.activityInfo == null) {
2379                continue;
2380            }
2381
2382            final String packageName = info.activityInfo.packageName;
2383
2384            final PackageSetting ps = mSettings.mPackages.get(packageName);
2385            if (ps == null) {
2386                continue;
2387            }
2388
2389            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2390                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2391                continue;
2392            }
2393
2394            // Select the IntentFilterVerifier with the highest priority
2395            if (priority < info.priority) {
2396                priority = info.priority;
2397                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2398                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2399                        + verifierComponentName + " with priority: " + info.priority);
2400            }
2401        }
2402
2403        return verifierComponentName;
2404    }
2405
2406    private void primeDomainVerificationsLPw() {
2407        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Start priming domain verifications");
2408        boolean updated = false;
2409        ArraySet<String> allHostsSet = new ArraySet<>();
2410        for (PackageParser.Package pkg : mPackages.values()) {
2411            final String packageName = pkg.packageName;
2412            if (!hasDomainURLs(pkg)) {
2413                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "No priming domain verifications for " +
2414                            "package with no domain URLs: " + packageName);
2415                continue;
2416            }
2417            if (!pkg.isSystemApp()) {
2418                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2419                        "No priming domain verifications for a non system package : " +
2420                                packageName);
2421                continue;
2422            }
2423            for (PackageParser.Activity a : pkg.activities) {
2424                for (ActivityIntentInfo filter : a.intents) {
2425                    if (hasValidDomains(filter)) {
2426                        allHostsSet.addAll(filter.getHostsList());
2427                    }
2428                }
2429            }
2430            if (allHostsSet.size() == 0) {
2431                allHostsSet.add("*");
2432            }
2433            ArrayList<String> allHostsList = new ArrayList<>(allHostsSet);
2434            IntentFilterVerificationInfo ivi =
2435                    mSettings.createIntentFilterVerificationIfNeededLPw(packageName, allHostsList);
2436            if (ivi != null) {
2437                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2438                        "Priming domain verifications for package: " + packageName +
2439                        " with hosts:" + ivi.getDomainsString());
2440                ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
2441                updated = true;
2442            }
2443            else {
2444                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2445                        "No priming domain verifications for package: " + packageName);
2446            }
2447            allHostsSet.clear();
2448        }
2449        if (updated) {
2450            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2451                    "Will need to write primed domain verifications");
2452        }
2453        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "End priming domain verifications");
2454    }
2455
2456    private void applyFactoryDefaultBrowserLPw(int userId) {
2457        // The default browser app's package name is stored in a string resource,
2458        // with a product-specific overlay used for vendor customization.
2459        String browserPkg = mContext.getResources().getString(
2460                com.android.internal.R.string.default_browser);
2461        if (browserPkg != null) {
2462            // non-empty string => required to be a known package
2463            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2464            if (ps == null) {
2465                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2466                browserPkg = null;
2467            } else {
2468                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2469            }
2470        }
2471
2472        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2473        // default.  If there's more than one, just leave everything alone.
2474        if (browserPkg == null) {
2475            calculateDefaultBrowserLPw(userId);
2476        }
2477    }
2478
2479    private void calculateDefaultBrowserLPw(int userId) {
2480        List<String> allBrowsers = resolveAllBrowserApps(userId);
2481        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2482        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2483    }
2484
2485    private List<String> resolveAllBrowserApps(int userId) {
2486        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2487        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2488                PackageManager.MATCH_ALL, userId);
2489
2490        final int count = list.size();
2491        List<String> result = new ArrayList<String>(count);
2492        for (int i=0; i<count; i++) {
2493            ResolveInfo info = list.get(i);
2494            if (info.activityInfo == null
2495                    || !info.handleAllWebDataURI
2496                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2497                    || result.contains(info.activityInfo.packageName)) {
2498                continue;
2499            }
2500            result.add(info.activityInfo.packageName);
2501        }
2502
2503        return result;
2504    }
2505
2506    private boolean packageIsBrowser(String packageName, int userId) {
2507        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2508                PackageManager.MATCH_ALL, userId);
2509        final int N = list.size();
2510        for (int i = 0; i < N; i++) {
2511            ResolveInfo info = list.get(i);
2512            if (packageName.equals(info.activityInfo.packageName)) {
2513                return true;
2514            }
2515        }
2516        return false;
2517    }
2518
2519    private void checkDefaultBrowser() {
2520        final int myUserId = UserHandle.myUserId();
2521        final String packageName = getDefaultBrowserPackageName(myUserId);
2522        if (packageName != null) {
2523            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2524            if (info == null) {
2525                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2526                synchronized (mPackages) {
2527                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2528                }
2529            }
2530        }
2531    }
2532
2533    @Override
2534    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2535            throws RemoteException {
2536        try {
2537            return super.onTransact(code, data, reply, flags);
2538        } catch (RuntimeException e) {
2539            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2540                Slog.wtf(TAG, "Package Manager Crash", e);
2541            }
2542            throw e;
2543        }
2544    }
2545
2546    void cleanupInstallFailedPackage(PackageSetting ps) {
2547        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2548
2549        removeDataDirsLI(ps.volumeUuid, ps.name);
2550        if (ps.codePath != null) {
2551            if (ps.codePath.isDirectory()) {
2552                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2553            } else {
2554                ps.codePath.delete();
2555            }
2556        }
2557        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2558            if (ps.resourcePath.isDirectory()) {
2559                FileUtils.deleteContents(ps.resourcePath);
2560            }
2561            ps.resourcePath.delete();
2562        }
2563        mSettings.removePackageLPw(ps.name);
2564    }
2565
2566    static int[] appendInts(int[] cur, int[] add) {
2567        if (add == null) return cur;
2568        if (cur == null) return add;
2569        final int N = add.length;
2570        for (int i=0; i<N; i++) {
2571            cur = appendInt(cur, add[i]);
2572        }
2573        return cur;
2574    }
2575
2576    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2577        if (!sUserManager.exists(userId)) return null;
2578        final PackageSetting ps = (PackageSetting) p.mExtras;
2579        if (ps == null) {
2580            return null;
2581        }
2582
2583        final PermissionsState permissionsState = ps.getPermissionsState();
2584
2585        final int[] gids = permissionsState.computeGids(userId);
2586        final Set<String> permissions = permissionsState.getPermissions(userId);
2587        final PackageUserState state = ps.readUserState(userId);
2588
2589        return PackageParser.generatePackageInfo(p, gids, flags,
2590                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2591    }
2592
2593    @Override
2594    public boolean isPackageFrozen(String packageName) {
2595        synchronized (mPackages) {
2596            final PackageSetting ps = mSettings.mPackages.get(packageName);
2597            if (ps != null) {
2598                return ps.frozen;
2599            }
2600        }
2601        Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen");
2602        return true;
2603    }
2604
2605    @Override
2606    public boolean isPackageAvailable(String packageName, int userId) {
2607        if (!sUserManager.exists(userId)) return false;
2608        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2609        synchronized (mPackages) {
2610            PackageParser.Package p = mPackages.get(packageName);
2611            if (p != null) {
2612                final PackageSetting ps = (PackageSetting) p.mExtras;
2613                if (ps != null) {
2614                    final PackageUserState state = ps.readUserState(userId);
2615                    if (state != null) {
2616                        return PackageParser.isAvailable(state);
2617                    }
2618                }
2619            }
2620        }
2621        return false;
2622    }
2623
2624    @Override
2625    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2626        if (!sUserManager.exists(userId)) return null;
2627        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2628        // reader
2629        synchronized (mPackages) {
2630            PackageParser.Package p = mPackages.get(packageName);
2631            if (DEBUG_PACKAGE_INFO)
2632                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2633            if (p != null) {
2634                return generatePackageInfo(p, flags, userId);
2635            }
2636            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2637                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2638            }
2639        }
2640        return null;
2641    }
2642
2643    @Override
2644    public String[] currentToCanonicalPackageNames(String[] names) {
2645        String[] out = new String[names.length];
2646        // reader
2647        synchronized (mPackages) {
2648            for (int i=names.length-1; i>=0; i--) {
2649                PackageSetting ps = mSettings.mPackages.get(names[i]);
2650                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2651            }
2652        }
2653        return out;
2654    }
2655
2656    @Override
2657    public String[] canonicalToCurrentPackageNames(String[] names) {
2658        String[] out = new String[names.length];
2659        // reader
2660        synchronized (mPackages) {
2661            for (int i=names.length-1; i>=0; i--) {
2662                String cur = mSettings.mRenamedPackages.get(names[i]);
2663                out[i] = cur != null ? cur : names[i];
2664            }
2665        }
2666        return out;
2667    }
2668
2669    @Override
2670    public int getPackageUid(String packageName, int userId) {
2671        if (!sUserManager.exists(userId)) return -1;
2672        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2673
2674        // reader
2675        synchronized (mPackages) {
2676            PackageParser.Package p = mPackages.get(packageName);
2677            if(p != null) {
2678                return UserHandle.getUid(userId, p.applicationInfo.uid);
2679            }
2680            PackageSetting ps = mSettings.mPackages.get(packageName);
2681            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2682                return -1;
2683            }
2684            p = ps.pkg;
2685            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2686        }
2687    }
2688
2689    @Override
2690    public int[] getPackageGids(String packageName, int userId) throws RemoteException {
2691        if (!sUserManager.exists(userId)) {
2692            return null;
2693        }
2694
2695        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2696                "getPackageGids");
2697
2698        // reader
2699        synchronized (mPackages) {
2700            PackageParser.Package p = mPackages.get(packageName);
2701            if (DEBUG_PACKAGE_INFO) {
2702                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2703            }
2704            if (p != null) {
2705                PackageSetting ps = (PackageSetting) p.mExtras;
2706                return ps.getPermissionsState().computeGids(userId);
2707            }
2708        }
2709
2710        return null;
2711    }
2712
2713    @Override
2714    public int getMountExternalMode(int uid) {
2715        if (Process.isIsolated(uid)) {
2716            return Zygote.MOUNT_EXTERNAL_NONE;
2717        } else {
2718            if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
2719                return Zygote.MOUNT_EXTERNAL_DEFAULT;
2720            } else if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_GRANTED) {
2721                return Zygote.MOUNT_EXTERNAL_WRITE;
2722            } else if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_GRANTED) {
2723                return Zygote.MOUNT_EXTERNAL_READ;
2724            } else {
2725                return Zygote.MOUNT_EXTERNAL_DEFAULT;
2726            }
2727        }
2728    }
2729
2730    static PermissionInfo generatePermissionInfo(
2731            BasePermission bp, int flags) {
2732        if (bp.perm != null) {
2733            return PackageParser.generatePermissionInfo(bp.perm, flags);
2734        }
2735        PermissionInfo pi = new PermissionInfo();
2736        pi.name = bp.name;
2737        pi.packageName = bp.sourcePackage;
2738        pi.nonLocalizedLabel = bp.name;
2739        pi.protectionLevel = bp.protectionLevel;
2740        return pi;
2741    }
2742
2743    @Override
2744    public PermissionInfo getPermissionInfo(String name, int flags) {
2745        // reader
2746        synchronized (mPackages) {
2747            final BasePermission p = mSettings.mPermissions.get(name);
2748            if (p != null) {
2749                return generatePermissionInfo(p, flags);
2750            }
2751            return null;
2752        }
2753    }
2754
2755    @Override
2756    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2757        // reader
2758        synchronized (mPackages) {
2759            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2760            for (BasePermission p : mSettings.mPermissions.values()) {
2761                if (group == null) {
2762                    if (p.perm == null || p.perm.info.group == null) {
2763                        out.add(generatePermissionInfo(p, flags));
2764                    }
2765                } else {
2766                    if (p.perm != null && group.equals(p.perm.info.group)) {
2767                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2768                    }
2769                }
2770            }
2771
2772            if (out.size() > 0) {
2773                return out;
2774            }
2775            return mPermissionGroups.containsKey(group) ? out : null;
2776        }
2777    }
2778
2779    @Override
2780    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2781        // reader
2782        synchronized (mPackages) {
2783            return PackageParser.generatePermissionGroupInfo(
2784                    mPermissionGroups.get(name), flags);
2785        }
2786    }
2787
2788    @Override
2789    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2790        // reader
2791        synchronized (mPackages) {
2792            final int N = mPermissionGroups.size();
2793            ArrayList<PermissionGroupInfo> out
2794                    = new ArrayList<PermissionGroupInfo>(N);
2795            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2796                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2797            }
2798            return out;
2799        }
2800    }
2801
2802    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2803            int userId) {
2804        if (!sUserManager.exists(userId)) return null;
2805        PackageSetting ps = mSettings.mPackages.get(packageName);
2806        if (ps != null) {
2807            if (ps.pkg == null) {
2808                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2809                        flags, userId);
2810                if (pInfo != null) {
2811                    return pInfo.applicationInfo;
2812                }
2813                return null;
2814            }
2815            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2816                    ps.readUserState(userId), userId);
2817        }
2818        return null;
2819    }
2820
2821    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2822            int userId) {
2823        if (!sUserManager.exists(userId)) return null;
2824        PackageSetting ps = mSettings.mPackages.get(packageName);
2825        if (ps != null) {
2826            PackageParser.Package pkg = ps.pkg;
2827            if (pkg == null) {
2828                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2829                    return null;
2830                }
2831                // Only data remains, so we aren't worried about code paths
2832                pkg = new PackageParser.Package(packageName);
2833                pkg.applicationInfo.packageName = packageName;
2834                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2835                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2836                pkg.applicationInfo.dataDir = Environment
2837                        .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName)
2838                        .getAbsolutePath();
2839                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2840                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2841            }
2842            return generatePackageInfo(pkg, flags, userId);
2843        }
2844        return null;
2845    }
2846
2847    @Override
2848    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2849        if (!sUserManager.exists(userId)) return null;
2850        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2851        // writer
2852        synchronized (mPackages) {
2853            PackageParser.Package p = mPackages.get(packageName);
2854            if (DEBUG_PACKAGE_INFO) Log.v(
2855                    TAG, "getApplicationInfo " + packageName
2856                    + ": " + p);
2857            if (p != null) {
2858                PackageSetting ps = mSettings.mPackages.get(packageName);
2859                if (ps == null) return null;
2860                // Note: isEnabledLP() does not apply here - always return info
2861                return PackageParser.generateApplicationInfo(
2862                        p, flags, ps.readUserState(userId), userId);
2863            }
2864            if ("android".equals(packageName)||"system".equals(packageName)) {
2865                return mAndroidApplication;
2866            }
2867            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2868                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2869            }
2870        }
2871        return null;
2872    }
2873
2874    @Override
2875    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
2876            final IPackageDataObserver observer) {
2877        mContext.enforceCallingOrSelfPermission(
2878                android.Manifest.permission.CLEAR_APP_CACHE, null);
2879        // Queue up an async operation since clearing cache may take a little while.
2880        mHandler.post(new Runnable() {
2881            public void run() {
2882                mHandler.removeCallbacks(this);
2883                int retCode = -1;
2884                synchronized (mInstallLock) {
2885                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2886                    if (retCode < 0) {
2887                        Slog.w(TAG, "Couldn't clear application caches");
2888                    }
2889                }
2890                if (observer != null) {
2891                    try {
2892                        observer.onRemoveCompleted(null, (retCode >= 0));
2893                    } catch (RemoteException e) {
2894                        Slog.w(TAG, "RemoveException when invoking call back");
2895                    }
2896                }
2897            }
2898        });
2899    }
2900
2901    @Override
2902    public void freeStorage(final String volumeUuid, final long freeStorageSize,
2903            final IntentSender pi) {
2904        mContext.enforceCallingOrSelfPermission(
2905                android.Manifest.permission.CLEAR_APP_CACHE, null);
2906        // Queue up an async operation since clearing cache may take a little while.
2907        mHandler.post(new Runnable() {
2908            public void run() {
2909                mHandler.removeCallbacks(this);
2910                int retCode = -1;
2911                synchronized (mInstallLock) {
2912                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2913                    if (retCode < 0) {
2914                        Slog.w(TAG, "Couldn't clear application caches");
2915                    }
2916                }
2917                if(pi != null) {
2918                    try {
2919                        // Callback via pending intent
2920                        int code = (retCode >= 0) ? 1 : 0;
2921                        pi.sendIntent(null, code, null,
2922                                null, null);
2923                    } catch (SendIntentException e1) {
2924                        Slog.i(TAG, "Failed to send pending intent");
2925                    }
2926                }
2927            }
2928        });
2929    }
2930
2931    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
2932        synchronized (mInstallLock) {
2933            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
2934                throw new IOException("Failed to free enough space");
2935            }
2936        }
2937    }
2938
2939    @Override
2940    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2941        if (!sUserManager.exists(userId)) return null;
2942        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2943        synchronized (mPackages) {
2944            PackageParser.Activity a = mActivities.mActivities.get(component);
2945
2946            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2947            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2948                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2949                if (ps == null) return null;
2950                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2951                        userId);
2952            }
2953            if (mResolveComponentName.equals(component)) {
2954                return PackageParser.generateActivityInfo(mResolveActivity, flags,
2955                        new PackageUserState(), userId);
2956            }
2957        }
2958        return null;
2959    }
2960
2961    @Override
2962    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2963            String resolvedType) {
2964        synchronized (mPackages) {
2965            PackageParser.Activity a = mActivities.mActivities.get(component);
2966            if (a == null) {
2967                return false;
2968            }
2969            for (int i=0; i<a.intents.size(); i++) {
2970                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2971                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2972                    return true;
2973                }
2974            }
2975            return false;
2976        }
2977    }
2978
2979    @Override
2980    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2981        if (!sUserManager.exists(userId)) return null;
2982        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
2983        synchronized (mPackages) {
2984            PackageParser.Activity a = mReceivers.mActivities.get(component);
2985            if (DEBUG_PACKAGE_INFO) Log.v(
2986                TAG, "getReceiverInfo " + component + ": " + a);
2987            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2988                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2989                if (ps == null) return null;
2990                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2991                        userId);
2992            }
2993        }
2994        return null;
2995    }
2996
2997    @Override
2998    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2999        if (!sUserManager.exists(userId)) return null;
3000        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3001        synchronized (mPackages) {
3002            PackageParser.Service s = mServices.mServices.get(component);
3003            if (DEBUG_PACKAGE_INFO) Log.v(
3004                TAG, "getServiceInfo " + component + ": " + s);
3005            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
3006                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3007                if (ps == null) return null;
3008                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3009                        userId);
3010            }
3011        }
3012        return null;
3013    }
3014
3015    @Override
3016    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3017        if (!sUserManager.exists(userId)) return null;
3018        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3019        synchronized (mPackages) {
3020            PackageParser.Provider p = mProviders.mProviders.get(component);
3021            if (DEBUG_PACKAGE_INFO) Log.v(
3022                TAG, "getProviderInfo " + component + ": " + p);
3023            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
3024                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3025                if (ps == null) return null;
3026                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3027                        userId);
3028            }
3029        }
3030        return null;
3031    }
3032
3033    @Override
3034    public String[] getSystemSharedLibraryNames() {
3035        Set<String> libSet;
3036        synchronized (mPackages) {
3037            libSet = mSharedLibraries.keySet();
3038            int size = libSet.size();
3039            if (size > 0) {
3040                String[] libs = new String[size];
3041                libSet.toArray(libs);
3042                return libs;
3043            }
3044        }
3045        return null;
3046    }
3047
3048    /**
3049     * @hide
3050     */
3051    PackageParser.Package findSharedNonSystemLibrary(String libName) {
3052        synchronized (mPackages) {
3053            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
3054            if (lib != null && lib.apk != null) {
3055                return mPackages.get(lib.apk);
3056            }
3057        }
3058        return null;
3059    }
3060
3061    @Override
3062    public FeatureInfo[] getSystemAvailableFeatures() {
3063        Collection<FeatureInfo> featSet;
3064        synchronized (mPackages) {
3065            featSet = mAvailableFeatures.values();
3066            int size = featSet.size();
3067            if (size > 0) {
3068                FeatureInfo[] features = new FeatureInfo[size+1];
3069                featSet.toArray(features);
3070                FeatureInfo fi = new FeatureInfo();
3071                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3072                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3073                features[size] = fi;
3074                return features;
3075            }
3076        }
3077        return null;
3078    }
3079
3080    @Override
3081    public boolean hasSystemFeature(String name) {
3082        synchronized (mPackages) {
3083            return mAvailableFeatures.containsKey(name);
3084        }
3085    }
3086
3087    private void checkValidCaller(int uid, int userId) {
3088        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
3089            return;
3090
3091        throw new SecurityException("Caller uid=" + uid
3092                + " is not privileged to communicate with user=" + userId);
3093    }
3094
3095    @Override
3096    public int checkPermission(String permName, String pkgName, int userId) {
3097        if (!sUserManager.exists(userId)) {
3098            return PackageManager.PERMISSION_DENIED;
3099        }
3100
3101        synchronized (mPackages) {
3102            final PackageParser.Package p = mPackages.get(pkgName);
3103            if (p != null && p.mExtras != null) {
3104                final PackageSetting ps = (PackageSetting) p.mExtras;
3105                if (ps.getPermissionsState().hasPermission(permName, userId)) {
3106                    return PackageManager.PERMISSION_GRANTED;
3107                }
3108            }
3109        }
3110
3111        return PackageManager.PERMISSION_DENIED;
3112    }
3113
3114    @Override
3115    public int checkUidPermission(String permName, int uid) {
3116        final int userId = UserHandle.getUserId(uid);
3117
3118        if (!sUserManager.exists(userId)) {
3119            return PackageManager.PERMISSION_DENIED;
3120        }
3121
3122        synchronized (mPackages) {
3123            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3124            if (obj != null) {
3125                final SettingBase ps = (SettingBase) obj;
3126                if (ps.getPermissionsState().hasPermission(permName, userId)) {
3127                    return PackageManager.PERMISSION_GRANTED;
3128                }
3129            } else {
3130                ArraySet<String> perms = mSystemPermissions.get(uid);
3131                if (perms != null && perms.contains(permName)) {
3132                    return PackageManager.PERMISSION_GRANTED;
3133                }
3134            }
3135        }
3136
3137        return PackageManager.PERMISSION_DENIED;
3138    }
3139
3140    /**
3141     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3142     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3143     * @param checkShell TODO(yamasani):
3144     * @param message the message to log on security exception
3145     */
3146    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3147            boolean checkShell, String message) {
3148        if (userId < 0) {
3149            throw new IllegalArgumentException("Invalid userId " + userId);
3150        }
3151        if (checkShell) {
3152            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3153        }
3154        if (userId == UserHandle.getUserId(callingUid)) return;
3155        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3156            if (requireFullPermission) {
3157                mContext.enforceCallingOrSelfPermission(
3158                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3159            } else {
3160                try {
3161                    mContext.enforceCallingOrSelfPermission(
3162                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3163                } catch (SecurityException se) {
3164                    mContext.enforceCallingOrSelfPermission(
3165                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3166                }
3167            }
3168        }
3169    }
3170
3171    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3172        if (callingUid == Process.SHELL_UID) {
3173            if (userHandle >= 0
3174                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3175                throw new SecurityException("Shell does not have permission to access user "
3176                        + userHandle);
3177            } else if (userHandle < 0) {
3178                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3179                        + Debug.getCallers(3));
3180            }
3181        }
3182    }
3183
3184    private BasePermission findPermissionTreeLP(String permName) {
3185        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3186            if (permName.startsWith(bp.name) &&
3187                    permName.length() > bp.name.length() &&
3188                    permName.charAt(bp.name.length()) == '.') {
3189                return bp;
3190            }
3191        }
3192        return null;
3193    }
3194
3195    private BasePermission checkPermissionTreeLP(String permName) {
3196        if (permName != null) {
3197            BasePermission bp = findPermissionTreeLP(permName);
3198            if (bp != null) {
3199                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3200                    return bp;
3201                }
3202                throw new SecurityException("Calling uid "
3203                        + Binder.getCallingUid()
3204                        + " is not allowed to add to permission tree "
3205                        + bp.name + " owned by uid " + bp.uid);
3206            }
3207        }
3208        throw new SecurityException("No permission tree found for " + permName);
3209    }
3210
3211    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3212        if (s1 == null) {
3213            return s2 == null;
3214        }
3215        if (s2 == null) {
3216            return false;
3217        }
3218        if (s1.getClass() != s2.getClass()) {
3219            return false;
3220        }
3221        return s1.equals(s2);
3222    }
3223
3224    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3225        if (pi1.icon != pi2.icon) return false;
3226        if (pi1.logo != pi2.logo) return false;
3227        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3228        if (!compareStrings(pi1.name, pi2.name)) return false;
3229        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3230        // We'll take care of setting this one.
3231        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3232        // These are not currently stored in settings.
3233        //if (!compareStrings(pi1.group, pi2.group)) return false;
3234        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3235        //if (pi1.labelRes != pi2.labelRes) return false;
3236        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3237        return true;
3238    }
3239
3240    int permissionInfoFootprint(PermissionInfo info) {
3241        int size = info.name.length();
3242        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3243        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3244        return size;
3245    }
3246
3247    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3248        int size = 0;
3249        for (BasePermission perm : mSettings.mPermissions.values()) {
3250            if (perm.uid == tree.uid) {
3251                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3252            }
3253        }
3254        return size;
3255    }
3256
3257    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3258        // We calculate the max size of permissions defined by this uid and throw
3259        // if that plus the size of 'info' would exceed our stated maximum.
3260        if (tree.uid != Process.SYSTEM_UID) {
3261            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3262            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3263                throw new SecurityException("Permission tree size cap exceeded");
3264            }
3265        }
3266    }
3267
3268    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3269        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3270            throw new SecurityException("Label must be specified in permission");
3271        }
3272        BasePermission tree = checkPermissionTreeLP(info.name);
3273        BasePermission bp = mSettings.mPermissions.get(info.name);
3274        boolean added = bp == null;
3275        boolean changed = true;
3276        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3277        if (added) {
3278            enforcePermissionCapLocked(info, tree);
3279            bp = new BasePermission(info.name, tree.sourcePackage,
3280                    BasePermission.TYPE_DYNAMIC);
3281        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3282            throw new SecurityException(
3283                    "Not allowed to modify non-dynamic permission "
3284                    + info.name);
3285        } else {
3286            if (bp.protectionLevel == fixedLevel
3287                    && bp.perm.owner.equals(tree.perm.owner)
3288                    && bp.uid == tree.uid
3289                    && comparePermissionInfos(bp.perm.info, info)) {
3290                changed = false;
3291            }
3292        }
3293        bp.protectionLevel = fixedLevel;
3294        info = new PermissionInfo(info);
3295        info.protectionLevel = fixedLevel;
3296        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3297        bp.perm.info.packageName = tree.perm.info.packageName;
3298        bp.uid = tree.uid;
3299        if (added) {
3300            mSettings.mPermissions.put(info.name, bp);
3301        }
3302        if (changed) {
3303            if (!async) {
3304                mSettings.writeLPr();
3305            } else {
3306                scheduleWriteSettingsLocked();
3307            }
3308        }
3309        return added;
3310    }
3311
3312    @Override
3313    public boolean addPermission(PermissionInfo info) {
3314        synchronized (mPackages) {
3315            return addPermissionLocked(info, false);
3316        }
3317    }
3318
3319    @Override
3320    public boolean addPermissionAsync(PermissionInfo info) {
3321        synchronized (mPackages) {
3322            return addPermissionLocked(info, true);
3323        }
3324    }
3325
3326    @Override
3327    public void removePermission(String name) {
3328        synchronized (mPackages) {
3329            checkPermissionTreeLP(name);
3330            BasePermission bp = mSettings.mPermissions.get(name);
3331            if (bp != null) {
3332                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3333                    throw new SecurityException(
3334                            "Not allowed to modify non-dynamic permission "
3335                            + name);
3336                }
3337                mSettings.mPermissions.remove(name);
3338                mSettings.writeLPr();
3339            }
3340        }
3341    }
3342
3343    private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg,
3344            BasePermission bp) {
3345        int index = pkg.requestedPermissions.indexOf(bp.name);
3346        if (index == -1) {
3347            throw new SecurityException("Package " + pkg.packageName
3348                    + " has not requested permission " + bp.name);
3349        }
3350        if (!bp.isRuntime()) {
3351            throw new SecurityException("Permission " + bp.name
3352                    + " is not a changeable permission type");
3353        }
3354    }
3355
3356    @Override
3357    public void grantRuntimePermission(String packageName, String name, final int userId) {
3358        if (!sUserManager.exists(userId)) {
3359            Log.e(TAG, "No such user:" + userId);
3360            return;
3361        }
3362
3363        mContext.enforceCallingOrSelfPermission(
3364                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3365                "grantRuntimePermission");
3366
3367        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3368                "grantRuntimePermission");
3369
3370        final int uid;
3371        final SettingBase sb;
3372
3373        synchronized (mPackages) {
3374            final PackageParser.Package pkg = mPackages.get(packageName);
3375            if (pkg == null) {
3376                throw new IllegalArgumentException("Unknown package: " + packageName);
3377            }
3378
3379            final BasePermission bp = mSettings.mPermissions.get(name);
3380            if (bp == null) {
3381                throw new IllegalArgumentException("Unknown permission: " + name);
3382            }
3383
3384            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3385
3386            uid = pkg.applicationInfo.uid;
3387            sb = (SettingBase) pkg.mExtras;
3388            if (sb == null) {
3389                throw new IllegalArgumentException("Unknown package: " + packageName);
3390            }
3391
3392            final PermissionsState permissionsState = sb.getPermissionsState();
3393
3394            final int flags = permissionsState.getPermissionFlags(name, userId);
3395            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3396                throw new SecurityException("Cannot grant system fixed permission: "
3397                        + name + " for package: " + packageName);
3398            }
3399
3400            final int result = permissionsState.grantRuntimePermission(bp, userId);
3401            switch (result) {
3402                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3403                    return;
3404                }
3405
3406                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3407                    mHandler.post(new Runnable() {
3408                        @Override
3409                        public void run() {
3410                            killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED);
3411                        }
3412                    });
3413                } break;
3414            }
3415
3416            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3417
3418            // Not critical if that is lost - app has to request again.
3419            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3420        }
3421
3422        if (READ_EXTERNAL_STORAGE.equals(name)
3423                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3424            final long token = Binder.clearCallingIdentity();
3425            try {
3426                final StorageManager storage = mContext.getSystemService(StorageManager.class);
3427                storage.remountUid(uid);
3428            } finally {
3429                Binder.restoreCallingIdentity(token);
3430            }
3431        }
3432    }
3433
3434    @Override
3435    public void revokeRuntimePermission(String packageName, String name, int userId) {
3436        if (!sUserManager.exists(userId)) {
3437            Log.e(TAG, "No such user:" + userId);
3438            return;
3439        }
3440
3441        mContext.enforceCallingOrSelfPermission(
3442                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3443                "revokeRuntimePermission");
3444
3445        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3446                "revokeRuntimePermission");
3447
3448        final SettingBase sb;
3449
3450        synchronized (mPackages) {
3451            final PackageParser.Package pkg = mPackages.get(packageName);
3452            if (pkg == null) {
3453                throw new IllegalArgumentException("Unknown package: " + packageName);
3454            }
3455
3456            final BasePermission bp = mSettings.mPermissions.get(name);
3457            if (bp == null) {
3458                throw new IllegalArgumentException("Unknown permission: " + name);
3459            }
3460
3461            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3462
3463            sb = (SettingBase) pkg.mExtras;
3464            if (sb == null) {
3465                throw new IllegalArgumentException("Unknown package: " + packageName);
3466            }
3467
3468            final PermissionsState permissionsState = sb.getPermissionsState();
3469
3470            final int flags = permissionsState.getPermissionFlags(name, userId);
3471            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3472                throw new SecurityException("Cannot revoke system fixed permission: "
3473                        + name + " for package: " + packageName);
3474            }
3475
3476            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3477                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3478                return;
3479            }
3480
3481            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3482
3483            // Critical, after this call app should never have the permission.
3484            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3485        }
3486
3487        killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3488    }
3489
3490    @Override
3491    public void resetRuntimePermissions() {
3492        mContext.enforceCallingOrSelfPermission(
3493                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3494                "revokeRuntimePermission");
3495
3496        int callingUid = Binder.getCallingUid();
3497        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3498            mContext.enforceCallingOrSelfPermission(
3499                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3500                    "resetRuntimePermissions");
3501        }
3502
3503        final int[] userIds;
3504
3505        synchronized (mPackages) {
3506            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3507            final int userCount = UserManagerService.getInstance().getUserIds().length;
3508            userIds = Arrays.copyOf(UserManagerService.getInstance().getUserIds(), userCount);
3509        }
3510
3511        for (int userId : userIds) {
3512            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
3513        }
3514    }
3515
3516    @Override
3517    public int getPermissionFlags(String name, String packageName, int userId) {
3518        if (!sUserManager.exists(userId)) {
3519            return 0;
3520        }
3521
3522        mContext.enforceCallingOrSelfPermission(
3523                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3524                "getPermissionFlags");
3525
3526        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3527                "getPermissionFlags");
3528
3529        synchronized (mPackages) {
3530            final PackageParser.Package pkg = mPackages.get(packageName);
3531            if (pkg == null) {
3532                throw new IllegalArgumentException("Unknown package: " + packageName);
3533            }
3534
3535            final BasePermission bp = mSettings.mPermissions.get(name);
3536            if (bp == null) {
3537                throw new IllegalArgumentException("Unknown permission: " + name);
3538            }
3539
3540            SettingBase sb = (SettingBase) pkg.mExtras;
3541            if (sb == null) {
3542                throw new IllegalArgumentException("Unknown package: " + packageName);
3543            }
3544
3545            PermissionsState permissionsState = sb.getPermissionsState();
3546            return permissionsState.getPermissionFlags(name, userId);
3547        }
3548    }
3549
3550    @Override
3551    public void updatePermissionFlags(String name, String packageName, int flagMask,
3552            int flagValues, int userId) {
3553        if (!sUserManager.exists(userId)) {
3554            return;
3555        }
3556
3557        mContext.enforceCallingOrSelfPermission(
3558                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3559                "updatePermissionFlags");
3560
3561        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3562                "updatePermissionFlags");
3563
3564        // Only the system can change system fixed flags.
3565        if (getCallingUid() != Process.SYSTEM_UID) {
3566            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3567            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3568        }
3569
3570        synchronized (mPackages) {
3571            final PackageParser.Package pkg = mPackages.get(packageName);
3572            if (pkg == null) {
3573                throw new IllegalArgumentException("Unknown package: " + packageName);
3574            }
3575
3576            final BasePermission bp = mSettings.mPermissions.get(name);
3577            if (bp == null) {
3578                throw new IllegalArgumentException("Unknown permission: " + name);
3579            }
3580
3581            SettingBase sb = (SettingBase) pkg.mExtras;
3582            if (sb == null) {
3583                throw new IllegalArgumentException("Unknown package: " + packageName);
3584            }
3585
3586            PermissionsState permissionsState = sb.getPermissionsState();
3587
3588            // Only the package manager can change flags for system component permissions.
3589            final int flags = permissionsState.getPermissionFlags(bp.name, userId);
3590            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3591                return;
3592            }
3593
3594            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3595
3596            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3597                // Install and runtime permissions are stored in different places,
3598                // so figure out what permission changed and persist the change.
3599                if (permissionsState.getInstallPermissionState(name) != null) {
3600                    scheduleWriteSettingsLocked();
3601                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3602                        || hadState) {
3603                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3604                }
3605            }
3606        }
3607    }
3608
3609    /**
3610     * Update the permission flags for all packages and runtime permissions of a user in order
3611     * to allow device or profile owner to remove POLICY_FIXED.
3612     */
3613    @Override
3614    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3615        if (!sUserManager.exists(userId)) {
3616            return;
3617        }
3618
3619        mContext.enforceCallingOrSelfPermission(
3620                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3621                "updatePermissionFlagsForAllApps");
3622
3623        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3624                "updatePermissionFlagsForAllApps");
3625
3626        // Only the system can change system fixed flags.
3627        if (getCallingUid() != Process.SYSTEM_UID) {
3628            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3629            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3630        }
3631
3632        synchronized (mPackages) {
3633            boolean changed = false;
3634            final int packageCount = mPackages.size();
3635            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
3636                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
3637                SettingBase sb = (SettingBase) pkg.mExtras;
3638                if (sb == null) {
3639                    continue;
3640                }
3641                PermissionsState permissionsState = sb.getPermissionsState();
3642                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
3643                        userId, flagMask, flagValues);
3644            }
3645            if (changed) {
3646                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3647            }
3648        }
3649    }
3650
3651    @Override
3652    public boolean shouldShowRequestPermissionRationale(String permissionName,
3653            String packageName, int userId) {
3654        if (UserHandle.getCallingUserId() != userId) {
3655            mContext.enforceCallingPermission(
3656                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3657                    "canShowRequestPermissionRationale for user " + userId);
3658        }
3659
3660        final int uid = getPackageUid(packageName, userId);
3661        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
3662            return false;
3663        }
3664
3665        if (checkPermission(permissionName, packageName, userId)
3666                == PackageManager.PERMISSION_GRANTED) {
3667            return false;
3668        }
3669
3670        final int flags;
3671
3672        final long identity = Binder.clearCallingIdentity();
3673        try {
3674            flags = getPermissionFlags(permissionName,
3675                    packageName, userId);
3676        } finally {
3677            Binder.restoreCallingIdentity(identity);
3678        }
3679
3680        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
3681                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
3682                | PackageManager.FLAG_PERMISSION_USER_FIXED;
3683
3684        if ((flags & fixedFlags) != 0) {
3685            return false;
3686        }
3687
3688        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
3689    }
3690
3691    void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) {
3692        BasePermission bp = mSettings.mPermissions.get(permission);
3693        if (bp == null) {
3694            throw new SecurityException("Missing " + permission + " permission");
3695        }
3696
3697        SettingBase sb = (SettingBase) pkg.mExtras;
3698        PermissionsState permissionsState = sb.getPermissionsState();
3699
3700        if (permissionsState.grantInstallPermission(bp) !=
3701                PermissionsState.PERMISSION_OPERATION_FAILURE) {
3702            scheduleWriteSettingsLocked();
3703        }
3704    }
3705
3706    @Override
3707    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3708        mContext.enforceCallingOrSelfPermission(
3709                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
3710                "addOnPermissionsChangeListener");
3711
3712        synchronized (mPackages) {
3713            mOnPermissionChangeListeners.addListenerLocked(listener);
3714        }
3715    }
3716
3717    @Override
3718    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3719        synchronized (mPackages) {
3720            mOnPermissionChangeListeners.removeListenerLocked(listener);
3721        }
3722    }
3723
3724    @Override
3725    public boolean isProtectedBroadcast(String actionName) {
3726        synchronized (mPackages) {
3727            return mProtectedBroadcasts.contains(actionName);
3728        }
3729    }
3730
3731    @Override
3732    public int checkSignatures(String pkg1, String pkg2) {
3733        synchronized (mPackages) {
3734            final PackageParser.Package p1 = mPackages.get(pkg1);
3735            final PackageParser.Package p2 = mPackages.get(pkg2);
3736            if (p1 == null || p1.mExtras == null
3737                    || p2 == null || p2.mExtras == null) {
3738                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3739            }
3740            return compareSignatures(p1.mSignatures, p2.mSignatures);
3741        }
3742    }
3743
3744    @Override
3745    public int checkUidSignatures(int uid1, int uid2) {
3746        // Map to base uids.
3747        uid1 = UserHandle.getAppId(uid1);
3748        uid2 = UserHandle.getAppId(uid2);
3749        // reader
3750        synchronized (mPackages) {
3751            Signature[] s1;
3752            Signature[] s2;
3753            Object obj = mSettings.getUserIdLPr(uid1);
3754            if (obj != null) {
3755                if (obj instanceof SharedUserSetting) {
3756                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3757                } else if (obj instanceof PackageSetting) {
3758                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3759                } else {
3760                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3761                }
3762            } else {
3763                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3764            }
3765            obj = mSettings.getUserIdLPr(uid2);
3766            if (obj != null) {
3767                if (obj instanceof SharedUserSetting) {
3768                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3769                } else if (obj instanceof PackageSetting) {
3770                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3771                } else {
3772                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3773                }
3774            } else {
3775                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3776            }
3777            return compareSignatures(s1, s2);
3778        }
3779    }
3780
3781    private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) {
3782        final long identity = Binder.clearCallingIdentity();
3783        try {
3784            if (sb instanceof SharedUserSetting) {
3785                SharedUserSetting sus = (SharedUserSetting) sb;
3786                final int packageCount = sus.packages.size();
3787                for (int i = 0; i < packageCount; i++) {
3788                    PackageSetting susPs = sus.packages.valueAt(i);
3789                    if (userId == UserHandle.USER_ALL) {
3790                        killApplication(susPs.pkg.packageName, susPs.appId, reason);
3791                    } else {
3792                        final int uid = UserHandle.getUid(userId, susPs.appId);
3793                        killUid(uid, reason);
3794                    }
3795                }
3796            } else if (sb instanceof PackageSetting) {
3797                PackageSetting ps = (PackageSetting) sb;
3798                if (userId == UserHandle.USER_ALL) {
3799                    killApplication(ps.pkg.packageName, ps.appId, reason);
3800                } else {
3801                    final int uid = UserHandle.getUid(userId, ps.appId);
3802                    killUid(uid, reason);
3803                }
3804            }
3805        } finally {
3806            Binder.restoreCallingIdentity(identity);
3807        }
3808    }
3809
3810    private static void killUid(int uid, String reason) {
3811        IActivityManager am = ActivityManagerNative.getDefault();
3812        if (am != null) {
3813            try {
3814                am.killUid(uid, reason);
3815            } catch (RemoteException e) {
3816                /* ignore - same process */
3817            }
3818        }
3819    }
3820
3821    /**
3822     * Compares two sets of signatures. Returns:
3823     * <br />
3824     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3825     * <br />
3826     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3827     * <br />
3828     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3829     * <br />
3830     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3831     * <br />
3832     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3833     */
3834    static int compareSignatures(Signature[] s1, Signature[] s2) {
3835        if (s1 == null) {
3836            return s2 == null
3837                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3838                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3839        }
3840
3841        if (s2 == null) {
3842            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3843        }
3844
3845        if (s1.length != s2.length) {
3846            return PackageManager.SIGNATURE_NO_MATCH;
3847        }
3848
3849        // Since both signature sets are of size 1, we can compare without HashSets.
3850        if (s1.length == 1) {
3851            return s1[0].equals(s2[0]) ?
3852                    PackageManager.SIGNATURE_MATCH :
3853                    PackageManager.SIGNATURE_NO_MATCH;
3854        }
3855
3856        ArraySet<Signature> set1 = new ArraySet<Signature>();
3857        for (Signature sig : s1) {
3858            set1.add(sig);
3859        }
3860        ArraySet<Signature> set2 = new ArraySet<Signature>();
3861        for (Signature sig : s2) {
3862            set2.add(sig);
3863        }
3864        // Make sure s2 contains all signatures in s1.
3865        if (set1.equals(set2)) {
3866            return PackageManager.SIGNATURE_MATCH;
3867        }
3868        return PackageManager.SIGNATURE_NO_MATCH;
3869    }
3870
3871    /**
3872     * If the database version for this type of package (internal storage or
3873     * external storage) is less than the version where package signatures
3874     * were updated, return true.
3875     */
3876    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3877        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
3878                DatabaseVersion.SIGNATURE_END_ENTITY))
3879                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
3880                        DatabaseVersion.SIGNATURE_END_ENTITY));
3881    }
3882
3883    /**
3884     * Used for backward compatibility to make sure any packages with
3885     * certificate chains get upgraded to the new style. {@code existingSigs}
3886     * will be in the old format (since they were stored on disk from before the
3887     * system upgrade) and {@code scannedSigs} will be in the newer format.
3888     */
3889    private int compareSignaturesCompat(PackageSignatures existingSigs,
3890            PackageParser.Package scannedPkg) {
3891        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
3892            return PackageManager.SIGNATURE_NO_MATCH;
3893        }
3894
3895        ArraySet<Signature> existingSet = new ArraySet<Signature>();
3896        for (Signature sig : existingSigs.mSignatures) {
3897            existingSet.add(sig);
3898        }
3899        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
3900        for (Signature sig : scannedPkg.mSignatures) {
3901            try {
3902                Signature[] chainSignatures = sig.getChainSignatures();
3903                for (Signature chainSig : chainSignatures) {
3904                    scannedCompatSet.add(chainSig);
3905                }
3906            } catch (CertificateEncodingException e) {
3907                scannedCompatSet.add(sig);
3908            }
3909        }
3910        /*
3911         * Make sure the expanded scanned set contains all signatures in the
3912         * existing one.
3913         */
3914        if (scannedCompatSet.equals(existingSet)) {
3915            // Migrate the old signatures to the new scheme.
3916            existingSigs.assignSignatures(scannedPkg.mSignatures);
3917            // The new KeySets will be re-added later in the scanning process.
3918            synchronized (mPackages) {
3919                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
3920            }
3921            return PackageManager.SIGNATURE_MATCH;
3922        }
3923        return PackageManager.SIGNATURE_NO_MATCH;
3924    }
3925
3926    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3927        if (isExternal(scannedPkg)) {
3928            return mSettings.isExternalDatabaseVersionOlderThan(
3929                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3930        } else {
3931            return mSettings.isInternalDatabaseVersionOlderThan(
3932                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3933        }
3934    }
3935
3936    private int compareSignaturesRecover(PackageSignatures existingSigs,
3937            PackageParser.Package scannedPkg) {
3938        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
3939            return PackageManager.SIGNATURE_NO_MATCH;
3940        }
3941
3942        String msg = null;
3943        try {
3944            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
3945                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
3946                        + scannedPkg.packageName);
3947                return PackageManager.SIGNATURE_MATCH;
3948            }
3949        } catch (CertificateException e) {
3950            msg = e.getMessage();
3951        }
3952
3953        logCriticalInfo(Log.INFO,
3954                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
3955        return PackageManager.SIGNATURE_NO_MATCH;
3956    }
3957
3958    @Override
3959    public String[] getPackagesForUid(int uid) {
3960        uid = UserHandle.getAppId(uid);
3961        // reader
3962        synchronized (mPackages) {
3963            Object obj = mSettings.getUserIdLPr(uid);
3964            if (obj instanceof SharedUserSetting) {
3965                final SharedUserSetting sus = (SharedUserSetting) obj;
3966                final int N = sus.packages.size();
3967                final String[] res = new String[N];
3968                final Iterator<PackageSetting> it = sus.packages.iterator();
3969                int i = 0;
3970                while (it.hasNext()) {
3971                    res[i++] = it.next().name;
3972                }
3973                return res;
3974            } else if (obj instanceof PackageSetting) {
3975                final PackageSetting ps = (PackageSetting) obj;
3976                return new String[] { ps.name };
3977            }
3978        }
3979        return null;
3980    }
3981
3982    @Override
3983    public String getNameForUid(int uid) {
3984        // reader
3985        synchronized (mPackages) {
3986            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3987            if (obj instanceof SharedUserSetting) {
3988                final SharedUserSetting sus = (SharedUserSetting) obj;
3989                return sus.name + ":" + sus.userId;
3990            } else if (obj instanceof PackageSetting) {
3991                final PackageSetting ps = (PackageSetting) obj;
3992                return ps.name;
3993            }
3994        }
3995        return null;
3996    }
3997
3998    @Override
3999    public int getUidForSharedUser(String sharedUserName) {
4000        if(sharedUserName == null) {
4001            return -1;
4002        }
4003        // reader
4004        synchronized (mPackages) {
4005            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4006            if (suid == null) {
4007                return -1;
4008            }
4009            return suid.userId;
4010        }
4011    }
4012
4013    @Override
4014    public int getFlagsForUid(int uid) {
4015        synchronized (mPackages) {
4016            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4017            if (obj instanceof SharedUserSetting) {
4018                final SharedUserSetting sus = (SharedUserSetting) obj;
4019                return sus.pkgFlags;
4020            } else if (obj instanceof PackageSetting) {
4021                final PackageSetting ps = (PackageSetting) obj;
4022                return ps.pkgFlags;
4023            }
4024        }
4025        return 0;
4026    }
4027
4028    @Override
4029    public int getPrivateFlagsForUid(int uid) {
4030        synchronized (mPackages) {
4031            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4032            if (obj instanceof SharedUserSetting) {
4033                final SharedUserSetting sus = (SharedUserSetting) obj;
4034                return sus.pkgPrivateFlags;
4035            } else if (obj instanceof PackageSetting) {
4036                final PackageSetting ps = (PackageSetting) obj;
4037                return ps.pkgPrivateFlags;
4038            }
4039        }
4040        return 0;
4041    }
4042
4043    @Override
4044    public boolean isUidPrivileged(int uid) {
4045        uid = UserHandle.getAppId(uid);
4046        // reader
4047        synchronized (mPackages) {
4048            Object obj = mSettings.getUserIdLPr(uid);
4049            if (obj instanceof SharedUserSetting) {
4050                final SharedUserSetting sus = (SharedUserSetting) obj;
4051                final Iterator<PackageSetting> it = sus.packages.iterator();
4052                while (it.hasNext()) {
4053                    if (it.next().isPrivileged()) {
4054                        return true;
4055                    }
4056                }
4057            } else if (obj instanceof PackageSetting) {
4058                final PackageSetting ps = (PackageSetting) obj;
4059                return ps.isPrivileged();
4060            }
4061        }
4062        return false;
4063    }
4064
4065    @Override
4066    public String[] getAppOpPermissionPackages(String permissionName) {
4067        synchronized (mPackages) {
4068            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4069            if (pkgs == null) {
4070                return null;
4071            }
4072            return pkgs.toArray(new String[pkgs.size()]);
4073        }
4074    }
4075
4076    @Override
4077    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4078            int flags, int userId) {
4079        if (!sUserManager.exists(userId)) return null;
4080        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4081        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4082        return chooseBestActivity(intent, resolvedType, flags, query, userId);
4083    }
4084
4085    @Override
4086    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4087            IntentFilter filter, int match, ComponentName activity) {
4088        final int userId = UserHandle.getCallingUserId();
4089        if (DEBUG_PREFERRED) {
4090            Log.v(TAG, "setLastChosenActivity intent=" + intent
4091                + " resolvedType=" + resolvedType
4092                + " flags=" + flags
4093                + " filter=" + filter
4094                + " match=" + match
4095                + " activity=" + activity);
4096            filter.dump(new PrintStreamPrinter(System.out), "    ");
4097        }
4098        intent.setComponent(null);
4099        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4100        // Find any earlier preferred or last chosen entries and nuke them
4101        findPreferredActivity(intent, resolvedType,
4102                flags, query, 0, false, true, false, userId);
4103        // Add the new activity as the last chosen for this filter
4104        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4105                "Setting last chosen");
4106    }
4107
4108    @Override
4109    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4110        final int userId = UserHandle.getCallingUserId();
4111        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4112        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4113        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4114                false, false, false, userId);
4115    }
4116
4117    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4118            int flags, List<ResolveInfo> query, int userId) {
4119        if (query != null) {
4120            final int N = query.size();
4121            if (N == 1) {
4122                return query.get(0);
4123            } else if (N > 1) {
4124                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4125                // If there is more than one activity with the same priority,
4126                // then let the user decide between them.
4127                ResolveInfo r0 = query.get(0);
4128                ResolveInfo r1 = query.get(1);
4129                if (DEBUG_INTENT_MATCHING || debug) {
4130                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4131                            + r1.activityInfo.name + "=" + r1.priority);
4132                }
4133                // If the first activity has a higher priority, or a different
4134                // default, then it is always desireable to pick it.
4135                if (r0.priority != r1.priority
4136                        || r0.preferredOrder != r1.preferredOrder
4137                        || r0.isDefault != r1.isDefault) {
4138                    return query.get(0);
4139                }
4140                // If we have saved a preference for a preferred activity for
4141                // this Intent, use that.
4142                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4143                        flags, query, r0.priority, true, false, debug, userId);
4144                if (ri != null) {
4145                    return ri;
4146                }
4147                if (userId != 0) {
4148                    ri = new ResolveInfo(mResolveInfo);
4149                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
4150                    ri.activityInfo.applicationInfo = new ApplicationInfo(
4151                            ri.activityInfo.applicationInfo);
4152                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4153                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4154                    return ri;
4155                }
4156                return mResolveInfo;
4157            }
4158        }
4159        return null;
4160    }
4161
4162    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4163            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4164        final int N = query.size();
4165        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4166                .get(userId);
4167        // Get the list of persistent preferred activities that handle the intent
4168        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4169        List<PersistentPreferredActivity> pprefs = ppir != null
4170                ? ppir.queryIntent(intent, resolvedType,
4171                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4172                : null;
4173        if (pprefs != null && pprefs.size() > 0) {
4174            final int M = pprefs.size();
4175            for (int i=0; i<M; i++) {
4176                final PersistentPreferredActivity ppa = pprefs.get(i);
4177                if (DEBUG_PREFERRED || debug) {
4178                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4179                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4180                            + "\n  component=" + ppa.mComponent);
4181                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4182                }
4183                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4184                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4185                if (DEBUG_PREFERRED || debug) {
4186                    Slog.v(TAG, "Found persistent preferred activity:");
4187                    if (ai != null) {
4188                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4189                    } else {
4190                        Slog.v(TAG, "  null");
4191                    }
4192                }
4193                if (ai == null) {
4194                    // This previously registered persistent preferred activity
4195                    // component is no longer known. Ignore it and do NOT remove it.
4196                    continue;
4197                }
4198                for (int j=0; j<N; j++) {
4199                    final ResolveInfo ri = query.get(j);
4200                    if (!ri.activityInfo.applicationInfo.packageName
4201                            .equals(ai.applicationInfo.packageName)) {
4202                        continue;
4203                    }
4204                    if (!ri.activityInfo.name.equals(ai.name)) {
4205                        continue;
4206                    }
4207                    //  Found a persistent preference that can handle the intent.
4208                    if (DEBUG_PREFERRED || debug) {
4209                        Slog.v(TAG, "Returning persistent preferred activity: " +
4210                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4211                    }
4212                    return ri;
4213                }
4214            }
4215        }
4216        return null;
4217    }
4218
4219    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4220            List<ResolveInfo> query, int priority, boolean always,
4221            boolean removeMatches, boolean debug, int userId) {
4222        if (!sUserManager.exists(userId)) return null;
4223        // writer
4224        synchronized (mPackages) {
4225            if (intent.getSelector() != null) {
4226                intent = intent.getSelector();
4227            }
4228            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4229
4230            // Try to find a matching persistent preferred activity.
4231            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4232                    debug, userId);
4233
4234            // If a persistent preferred activity matched, use it.
4235            if (pri != null) {
4236                return pri;
4237            }
4238
4239            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4240            // Get the list of preferred activities that handle the intent
4241            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4242            List<PreferredActivity> prefs = pir != null
4243                    ? pir.queryIntent(intent, resolvedType,
4244                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4245                    : null;
4246            if (prefs != null && prefs.size() > 0) {
4247                boolean changed = false;
4248                try {
4249                    // First figure out how good the original match set is.
4250                    // We will only allow preferred activities that came
4251                    // from the same match quality.
4252                    int match = 0;
4253
4254                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4255
4256                    final int N = query.size();
4257                    for (int j=0; j<N; j++) {
4258                        final ResolveInfo ri = query.get(j);
4259                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4260                                + ": 0x" + Integer.toHexString(match));
4261                        if (ri.match > match) {
4262                            match = ri.match;
4263                        }
4264                    }
4265
4266                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4267                            + Integer.toHexString(match));
4268
4269                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4270                    final int M = prefs.size();
4271                    for (int i=0; i<M; i++) {
4272                        final PreferredActivity pa = prefs.get(i);
4273                        if (DEBUG_PREFERRED || debug) {
4274                            Slog.v(TAG, "Checking PreferredActivity ds="
4275                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4276                                    + "\n  component=" + pa.mPref.mComponent);
4277                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4278                        }
4279                        if (pa.mPref.mMatch != match) {
4280                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4281                                    + Integer.toHexString(pa.mPref.mMatch));
4282                            continue;
4283                        }
4284                        // If it's not an "always" type preferred activity and that's what we're
4285                        // looking for, skip it.
4286                        if (always && !pa.mPref.mAlways) {
4287                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4288                            continue;
4289                        }
4290                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4291                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4292                        if (DEBUG_PREFERRED || debug) {
4293                            Slog.v(TAG, "Found preferred activity:");
4294                            if (ai != null) {
4295                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4296                            } else {
4297                                Slog.v(TAG, "  null");
4298                            }
4299                        }
4300                        if (ai == null) {
4301                            // This previously registered preferred activity
4302                            // component is no longer known.  Most likely an update
4303                            // to the app was installed and in the new version this
4304                            // component no longer exists.  Clean it up by removing
4305                            // it from the preferred activities list, and skip it.
4306                            Slog.w(TAG, "Removing dangling preferred activity: "
4307                                    + pa.mPref.mComponent);
4308                            pir.removeFilter(pa);
4309                            changed = true;
4310                            continue;
4311                        }
4312                        for (int j=0; j<N; j++) {
4313                            final ResolveInfo ri = query.get(j);
4314                            if (!ri.activityInfo.applicationInfo.packageName
4315                                    .equals(ai.applicationInfo.packageName)) {
4316                                continue;
4317                            }
4318                            if (!ri.activityInfo.name.equals(ai.name)) {
4319                                continue;
4320                            }
4321
4322                            if (removeMatches) {
4323                                pir.removeFilter(pa);
4324                                changed = true;
4325                                if (DEBUG_PREFERRED) {
4326                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4327                                }
4328                                break;
4329                            }
4330
4331                            // Okay we found a previously set preferred or last chosen app.
4332                            // If the result set is different from when this
4333                            // was created, we need to clear it and re-ask the
4334                            // user their preference, if we're looking for an "always" type entry.
4335                            if (always && !pa.mPref.sameSet(query)) {
4336                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4337                                        + intent + " type " + resolvedType);
4338                                if (DEBUG_PREFERRED) {
4339                                    Slog.v(TAG, "Removing preferred activity since set changed "
4340                                            + pa.mPref.mComponent);
4341                                }
4342                                pir.removeFilter(pa);
4343                                // Re-add the filter as a "last chosen" entry (!always)
4344                                PreferredActivity lastChosen = new PreferredActivity(
4345                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4346                                pir.addFilter(lastChosen);
4347                                changed = true;
4348                                return null;
4349                            }
4350
4351                            // Yay! Either the set matched or we're looking for the last chosen
4352                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4353                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4354                            return ri;
4355                        }
4356                    }
4357                } finally {
4358                    if (changed) {
4359                        if (DEBUG_PREFERRED) {
4360                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4361                        }
4362                        scheduleWritePackageRestrictionsLocked(userId);
4363                    }
4364                }
4365            }
4366        }
4367        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4368        return null;
4369    }
4370
4371    /*
4372     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4373     */
4374    @Override
4375    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4376            int targetUserId) {
4377        mContext.enforceCallingOrSelfPermission(
4378                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4379        List<CrossProfileIntentFilter> matches =
4380                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4381        if (matches != null) {
4382            int size = matches.size();
4383            for (int i = 0; i < size; i++) {
4384                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4385            }
4386        }
4387        if (hasWebURI(intent)) {
4388            // cross-profile app linking works only towards the parent.
4389            final UserInfo parent = getProfileParent(sourceUserId);
4390            synchronized(mPackages) {
4391                return getCrossProfileDomainPreferredLpr(intent, resolvedType, 0, sourceUserId,
4392                        parent.id) != null;
4393            }
4394        }
4395        return false;
4396    }
4397
4398    private UserInfo getProfileParent(int userId) {
4399        final long identity = Binder.clearCallingIdentity();
4400        try {
4401            return sUserManager.getProfileParent(userId);
4402        } finally {
4403            Binder.restoreCallingIdentity(identity);
4404        }
4405    }
4406
4407    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4408            String resolvedType, int userId) {
4409        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4410        if (resolver != null) {
4411            return resolver.queryIntent(intent, resolvedType, false, userId);
4412        }
4413        return null;
4414    }
4415
4416    @Override
4417    public List<ResolveInfo> queryIntentActivities(Intent intent,
4418            String resolvedType, int flags, int userId) {
4419        if (!sUserManager.exists(userId)) return Collections.emptyList();
4420        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4421        ComponentName comp = intent.getComponent();
4422        if (comp == null) {
4423            if (intent.getSelector() != null) {
4424                intent = intent.getSelector();
4425                comp = intent.getComponent();
4426            }
4427        }
4428
4429        if (comp != null) {
4430            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4431            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4432            if (ai != null) {
4433                final ResolveInfo ri = new ResolveInfo();
4434                ri.activityInfo = ai;
4435                list.add(ri);
4436            }
4437            return list;
4438        }
4439
4440        // reader
4441        synchronized (mPackages) {
4442            final String pkgName = intent.getPackage();
4443            if (pkgName == null) {
4444                List<CrossProfileIntentFilter> matchingFilters =
4445                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4446                // Check for results that need to skip the current profile.
4447                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4448                        resolvedType, flags, userId);
4449                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4450                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4451                    result.add(xpResolveInfo);
4452                    return filterIfNotPrimaryUser(result, userId);
4453                }
4454
4455                // Check for results in the current profile.
4456                List<ResolveInfo> result = mActivities.queryIntent(
4457                        intent, resolvedType, flags, userId);
4458
4459                // Check for cross profile results.
4460                xpResolveInfo = queryCrossProfileIntents(
4461                        matchingFilters, intent, resolvedType, flags, userId);
4462                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4463                    result.add(xpResolveInfo);
4464                    Collections.sort(result, mResolvePrioritySorter);
4465                }
4466                result = filterIfNotPrimaryUser(result, userId);
4467                if (hasWebURI(intent)) {
4468                    CrossProfileDomainInfo xpDomainInfo = null;
4469                    final UserInfo parent = getProfileParent(userId);
4470                    if (parent != null) {
4471                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4472                                flags, userId, parent.id);
4473                    }
4474                    if (xpDomainInfo != null) {
4475                        if (xpResolveInfo != null) {
4476                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4477                            // in the result.
4478                            result.remove(xpResolveInfo);
4479                        }
4480                        if (result.size() == 0) {
4481                            result.add(xpDomainInfo.resolveInfo);
4482                            return result;
4483                        }
4484                    } else if (result.size() <= 1) {
4485                        return result;
4486                    }
4487                    result = filterCandidatesWithDomainPreferredActivitiesLPr(flags, result,
4488                            xpDomainInfo);
4489                    Collections.sort(result, mResolvePrioritySorter);
4490                }
4491                return result;
4492            }
4493            final PackageParser.Package pkg = mPackages.get(pkgName);
4494            if (pkg != null) {
4495                return filterIfNotPrimaryUser(
4496                        mActivities.queryIntentForPackage(
4497                                intent, resolvedType, flags, pkg.activities, userId),
4498                        userId);
4499            }
4500            return new ArrayList<ResolveInfo>();
4501        }
4502    }
4503
4504    private static class CrossProfileDomainInfo {
4505        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4506        ResolveInfo resolveInfo;
4507        /* Best domain verification status of the activities found in the other profile */
4508        int bestDomainVerificationStatus;
4509    }
4510
4511    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4512            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4513        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
4514                sourceUserId)) {
4515            return null;
4516        }
4517        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4518                resolvedType, flags, parentUserId);
4519
4520        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4521            return null;
4522        }
4523        CrossProfileDomainInfo result = null;
4524        int size = resultTargetUser.size();
4525        for (int i = 0; i < size; i++) {
4526            ResolveInfo riTargetUser = resultTargetUser.get(i);
4527            // Intent filter verification is only for filters that specify a host. So don't return
4528            // those that handle all web uris.
4529            if (riTargetUser.handleAllWebDataURI) {
4530                continue;
4531            }
4532            String packageName = riTargetUser.activityInfo.packageName;
4533            PackageSetting ps = mSettings.mPackages.get(packageName);
4534            if (ps == null) {
4535                continue;
4536            }
4537            int status = getDomainVerificationStatusLPr(ps, parentUserId);
4538            if (result == null) {
4539                result = new CrossProfileDomainInfo();
4540                result.resolveInfo =
4541                        createForwardingResolveInfo(null, sourceUserId, parentUserId);
4542                result.bestDomainVerificationStatus = status;
4543            } else {
4544                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
4545                        result.bestDomainVerificationStatus);
4546            }
4547        }
4548        return result;
4549    }
4550
4551    /**
4552     * Verification statuses are ordered from the worse to the best, except for
4553     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
4554     */
4555    private int bestDomainVerificationStatus(int status1, int status2) {
4556        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4557            return status2;
4558        }
4559        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4560            return status1;
4561        }
4562        return (int) MathUtils.max(status1, status2);
4563    }
4564
4565    private boolean isUserEnabled(int userId) {
4566        long callingId = Binder.clearCallingIdentity();
4567        try {
4568            UserInfo userInfo = sUserManager.getUserInfo(userId);
4569            return userInfo != null && userInfo.isEnabled();
4570        } finally {
4571            Binder.restoreCallingIdentity(callingId);
4572        }
4573    }
4574
4575    /**
4576     * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
4577     *
4578     * @return filtered list
4579     */
4580    private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
4581        if (userId == UserHandle.USER_OWNER) {
4582            return resolveInfos;
4583        }
4584        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4585            ResolveInfo info = resolveInfos.get(i);
4586            if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
4587                resolveInfos.remove(i);
4588            }
4589        }
4590        return resolveInfos;
4591    }
4592
4593    private static boolean hasWebURI(Intent intent) {
4594        if (intent.getData() == null) {
4595            return false;
4596        }
4597        final String scheme = intent.getScheme();
4598        if (TextUtils.isEmpty(scheme)) {
4599            return false;
4600        }
4601        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4602    }
4603
4604    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(
4605            int flags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo) {
4606        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4607            Slog.v("TAG", "Filtering results with preferred activities. Candidates count: " +
4608                    candidates.size());
4609        }
4610
4611        final int userId = UserHandle.getCallingUserId();
4612        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4613        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
4614        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4615        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4616        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4617
4618        synchronized (mPackages) {
4619            final int count = candidates.size();
4620            // First, try to use linked apps. Partition the candidates into four lists:
4621            // one for the final results, one for the "do not use ever", one for "undefined status"
4622            // and finally one for "browser app type".
4623            for (int n=0; n<count; n++) {
4624                ResolveInfo info = candidates.get(n);
4625                String packageName = info.activityInfo.packageName;
4626                PackageSetting ps = mSettings.mPackages.get(packageName);
4627                if (ps != null) {
4628                    // Add to the special match all list (Browser use case)
4629                    if (info.handleAllWebDataURI) {
4630                        matchAllList.add(info);
4631                        continue;
4632                    }
4633                    // Try to get the status from User settings first
4634                    int status = getDomainVerificationStatusLPr(ps, userId);
4635                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4636                        if (DEBUG_DOMAIN_VERIFICATION) {
4637                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName);
4638                        }
4639                        alwaysList.add(info);
4640                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4641                        if (DEBUG_DOMAIN_VERIFICATION) {
4642                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
4643                        }
4644                        neverList.add(info);
4645                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
4646                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
4647                        if (DEBUG_DOMAIN_VERIFICATION) {
4648                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
4649                        }
4650                        undefinedList.add(info);
4651                    }
4652                }
4653            }
4654            // First try to add the "always" resolution for the current user if there is any
4655            if (alwaysList.size() > 0) {
4656                result.addAll(alwaysList);
4657            // if there is an "always" for the parent user, add it.
4658            } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus
4659                    == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4660                result.add(xpDomainInfo.resolveInfo);
4661            } else {
4662                // Add all undefined Apps as we want them to appear in the Disambiguation dialog.
4663                result.addAll(undefinedList);
4664                if (xpDomainInfo != null && (
4665                        xpDomainInfo.bestDomainVerificationStatus
4666                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
4667                        || xpDomainInfo.bestDomainVerificationStatus
4668                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) {
4669                    result.add(xpDomainInfo.resolveInfo);
4670                }
4671                // Also add Browsers (all of them or only the default one)
4672                if ((flags & MATCH_ALL) != 0) {
4673                    result.addAll(matchAllList);
4674                } else {
4675                    // Try to add the Default Browser if we can
4676                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(
4677                            UserHandle.myUserId());
4678                    if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
4679                        boolean defaultBrowserFound = false;
4680                        final int browserCount = matchAllList.size();
4681                        for (int n=0; n<browserCount; n++) {
4682                            ResolveInfo browser = matchAllList.get(n);
4683                            if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) {
4684                                result.add(browser);
4685                                defaultBrowserFound = true;
4686                                break;
4687                            }
4688                        }
4689                        if (!defaultBrowserFound) {
4690                            result.addAll(matchAllList);
4691                        }
4692                    } else {
4693                        result.addAll(matchAllList);
4694                    }
4695                }
4696
4697                // If there is nothing selected, add all candidates and remove the ones that the user
4698                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
4699                if (result.size() == 0) {
4700                    result.addAll(candidates);
4701                    result.removeAll(neverList);
4702                }
4703            }
4704        }
4705        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4706            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
4707                    result.size());
4708            for (ResolveInfo info : result) {
4709                Slog.v(TAG, "  + " + info.activityInfo);
4710            }
4711        }
4712        return result;
4713    }
4714
4715    private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4716        int status = ps.getDomainVerificationStatusForUser(userId);
4717        // if none available, get the master status
4718        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4719            if (ps.getIntentFilterVerificationInfo() != null) {
4720                status = ps.getIntentFilterVerificationInfo().getStatus();
4721            }
4722        }
4723        return status;
4724    }
4725
4726    private ResolveInfo querySkipCurrentProfileIntents(
4727            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4728            int flags, int sourceUserId) {
4729        if (matchingFilters != null) {
4730            int size = matchingFilters.size();
4731            for (int i = 0; i < size; i ++) {
4732                CrossProfileIntentFilter filter = matchingFilters.get(i);
4733                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4734                    // Checking if there are activities in the target user that can handle the
4735                    // intent.
4736                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4737                            flags, sourceUserId);
4738                    if (resolveInfo != null) {
4739                        return resolveInfo;
4740                    }
4741                }
4742            }
4743        }
4744        return null;
4745    }
4746
4747    // Return matching ResolveInfo if any for skip current profile intent filters.
4748    private ResolveInfo queryCrossProfileIntents(
4749            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4750            int flags, int sourceUserId) {
4751        if (matchingFilters != null) {
4752            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4753            // match the same intent. For performance reasons, it is better not to
4754            // run queryIntent twice for the same userId
4755            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4756            int size = matchingFilters.size();
4757            for (int i = 0; i < size; i++) {
4758                CrossProfileIntentFilter filter = matchingFilters.get(i);
4759                int targetUserId = filter.getTargetUserId();
4760                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4761                        && !alreadyTriedUserIds.get(targetUserId)) {
4762                    // Checking if there are activities in the target user that can handle the
4763                    // intent.
4764                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4765                            flags, sourceUserId);
4766                    if (resolveInfo != null) return resolveInfo;
4767                    alreadyTriedUserIds.put(targetUserId, true);
4768                }
4769            }
4770        }
4771        return null;
4772    }
4773
4774    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
4775            String resolvedType, int flags, int sourceUserId) {
4776        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4777                resolvedType, flags, filter.getTargetUserId());
4778        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
4779            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
4780        }
4781        return null;
4782    }
4783
4784    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
4785            int sourceUserId, int targetUserId) {
4786        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4787        String className;
4788        if (targetUserId == UserHandle.USER_OWNER) {
4789            className = FORWARD_INTENT_TO_USER_OWNER;
4790        } else {
4791            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4792        }
4793        ComponentName forwardingActivityComponentName = new ComponentName(
4794                mAndroidApplication.packageName, className);
4795        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
4796                sourceUserId);
4797        if (targetUserId == UserHandle.USER_OWNER) {
4798            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
4799            forwardingResolveInfo.noResourceId = true;
4800        }
4801        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
4802        forwardingResolveInfo.priority = 0;
4803        forwardingResolveInfo.preferredOrder = 0;
4804        forwardingResolveInfo.match = 0;
4805        forwardingResolveInfo.isDefault = true;
4806        forwardingResolveInfo.filter = filter;
4807        forwardingResolveInfo.targetUserId = targetUserId;
4808        return forwardingResolveInfo;
4809    }
4810
4811    @Override
4812    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
4813            Intent[] specifics, String[] specificTypes, Intent intent,
4814            String resolvedType, int flags, int userId) {
4815        if (!sUserManager.exists(userId)) return Collections.emptyList();
4816        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
4817                false, "query intent activity options");
4818        final String resultsAction = intent.getAction();
4819
4820        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
4821                | PackageManager.GET_RESOLVED_FILTER, userId);
4822
4823        if (DEBUG_INTENT_MATCHING) {
4824            Log.v(TAG, "Query " + intent + ": " + results);
4825        }
4826
4827        int specificsPos = 0;
4828        int N;
4829
4830        // todo: note that the algorithm used here is O(N^2).  This
4831        // isn't a problem in our current environment, but if we start running
4832        // into situations where we have more than 5 or 10 matches then this
4833        // should probably be changed to something smarter...
4834
4835        // First we go through and resolve each of the specific items
4836        // that were supplied, taking care of removing any corresponding
4837        // duplicate items in the generic resolve list.
4838        if (specifics != null) {
4839            for (int i=0; i<specifics.length; i++) {
4840                final Intent sintent = specifics[i];
4841                if (sintent == null) {
4842                    continue;
4843                }
4844
4845                if (DEBUG_INTENT_MATCHING) {
4846                    Log.v(TAG, "Specific #" + i + ": " + sintent);
4847                }
4848
4849                String action = sintent.getAction();
4850                if (resultsAction != null && resultsAction.equals(action)) {
4851                    // If this action was explicitly requested, then don't
4852                    // remove things that have it.
4853                    action = null;
4854                }
4855
4856                ResolveInfo ri = null;
4857                ActivityInfo ai = null;
4858
4859                ComponentName comp = sintent.getComponent();
4860                if (comp == null) {
4861                    ri = resolveIntent(
4862                        sintent,
4863                        specificTypes != null ? specificTypes[i] : null,
4864                            flags, userId);
4865                    if (ri == null) {
4866                        continue;
4867                    }
4868                    if (ri == mResolveInfo) {
4869                        // ACK!  Must do something better with this.
4870                    }
4871                    ai = ri.activityInfo;
4872                    comp = new ComponentName(ai.applicationInfo.packageName,
4873                            ai.name);
4874                } else {
4875                    ai = getActivityInfo(comp, flags, userId);
4876                    if (ai == null) {
4877                        continue;
4878                    }
4879                }
4880
4881                // Look for any generic query activities that are duplicates
4882                // of this specific one, and remove them from the results.
4883                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
4884                N = results.size();
4885                int j;
4886                for (j=specificsPos; j<N; j++) {
4887                    ResolveInfo sri = results.get(j);
4888                    if ((sri.activityInfo.name.equals(comp.getClassName())
4889                            && sri.activityInfo.applicationInfo.packageName.equals(
4890                                    comp.getPackageName()))
4891                        || (action != null && sri.filter.matchAction(action))) {
4892                        results.remove(j);
4893                        if (DEBUG_INTENT_MATCHING) Log.v(
4894                            TAG, "Removing duplicate item from " + j
4895                            + " due to specific " + specificsPos);
4896                        if (ri == null) {
4897                            ri = sri;
4898                        }
4899                        j--;
4900                        N--;
4901                    }
4902                }
4903
4904                // Add this specific item to its proper place.
4905                if (ri == null) {
4906                    ri = new ResolveInfo();
4907                    ri.activityInfo = ai;
4908                }
4909                results.add(specificsPos, ri);
4910                ri.specificIndex = i;
4911                specificsPos++;
4912            }
4913        }
4914
4915        // Now we go through the remaining generic results and remove any
4916        // duplicate actions that are found here.
4917        N = results.size();
4918        for (int i=specificsPos; i<N-1; i++) {
4919            final ResolveInfo rii = results.get(i);
4920            if (rii.filter == null) {
4921                continue;
4922            }
4923
4924            // Iterate over all of the actions of this result's intent
4925            // filter...  typically this should be just one.
4926            final Iterator<String> it = rii.filter.actionsIterator();
4927            if (it == null) {
4928                continue;
4929            }
4930            while (it.hasNext()) {
4931                final String action = it.next();
4932                if (resultsAction != null && resultsAction.equals(action)) {
4933                    // If this action was explicitly requested, then don't
4934                    // remove things that have it.
4935                    continue;
4936                }
4937                for (int j=i+1; j<N; j++) {
4938                    final ResolveInfo rij = results.get(j);
4939                    if (rij.filter != null && rij.filter.hasAction(action)) {
4940                        results.remove(j);
4941                        if (DEBUG_INTENT_MATCHING) Log.v(
4942                            TAG, "Removing duplicate item from " + j
4943                            + " due to action " + action + " at " + i);
4944                        j--;
4945                        N--;
4946                    }
4947                }
4948            }
4949
4950            // If the caller didn't request filter information, drop it now
4951            // so we don't have to marshall/unmarshall it.
4952            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4953                rii.filter = null;
4954            }
4955        }
4956
4957        // Filter out the caller activity if so requested.
4958        if (caller != null) {
4959            N = results.size();
4960            for (int i=0; i<N; i++) {
4961                ActivityInfo ainfo = results.get(i).activityInfo;
4962                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
4963                        && caller.getClassName().equals(ainfo.name)) {
4964                    results.remove(i);
4965                    break;
4966                }
4967            }
4968        }
4969
4970        // If the caller didn't request filter information,
4971        // drop them now so we don't have to
4972        // marshall/unmarshall it.
4973        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4974            N = results.size();
4975            for (int i=0; i<N; i++) {
4976                results.get(i).filter = null;
4977            }
4978        }
4979
4980        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
4981        return results;
4982    }
4983
4984    @Override
4985    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
4986            int userId) {
4987        if (!sUserManager.exists(userId)) return Collections.emptyList();
4988        ComponentName comp = intent.getComponent();
4989        if (comp == null) {
4990            if (intent.getSelector() != null) {
4991                intent = intent.getSelector();
4992                comp = intent.getComponent();
4993            }
4994        }
4995        if (comp != null) {
4996            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4997            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
4998            if (ai != null) {
4999                ResolveInfo ri = new ResolveInfo();
5000                ri.activityInfo = ai;
5001                list.add(ri);
5002            }
5003            return list;
5004        }
5005
5006        // reader
5007        synchronized (mPackages) {
5008            String pkgName = intent.getPackage();
5009            if (pkgName == null) {
5010                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5011            }
5012            final PackageParser.Package pkg = mPackages.get(pkgName);
5013            if (pkg != null) {
5014                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5015                        userId);
5016            }
5017            return null;
5018        }
5019    }
5020
5021    @Override
5022    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5023        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5024        if (!sUserManager.exists(userId)) return null;
5025        if (query != null) {
5026            if (query.size() >= 1) {
5027                // If there is more than one service with the same priority,
5028                // just arbitrarily pick the first one.
5029                return query.get(0);
5030            }
5031        }
5032        return null;
5033    }
5034
5035    @Override
5036    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5037            int userId) {
5038        if (!sUserManager.exists(userId)) return Collections.emptyList();
5039        ComponentName comp = intent.getComponent();
5040        if (comp == null) {
5041            if (intent.getSelector() != null) {
5042                intent = intent.getSelector();
5043                comp = intent.getComponent();
5044            }
5045        }
5046        if (comp != null) {
5047            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5048            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5049            if (si != null) {
5050                final ResolveInfo ri = new ResolveInfo();
5051                ri.serviceInfo = si;
5052                list.add(ri);
5053            }
5054            return list;
5055        }
5056
5057        // reader
5058        synchronized (mPackages) {
5059            String pkgName = intent.getPackage();
5060            if (pkgName == null) {
5061                return mServices.queryIntent(intent, resolvedType, flags, userId);
5062            }
5063            final PackageParser.Package pkg = mPackages.get(pkgName);
5064            if (pkg != null) {
5065                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5066                        userId);
5067            }
5068            return null;
5069        }
5070    }
5071
5072    @Override
5073    public List<ResolveInfo> queryIntentContentProviders(
5074            Intent intent, String resolvedType, int flags, int userId) {
5075        if (!sUserManager.exists(userId)) return Collections.emptyList();
5076        ComponentName comp = intent.getComponent();
5077        if (comp == null) {
5078            if (intent.getSelector() != null) {
5079                intent = intent.getSelector();
5080                comp = intent.getComponent();
5081            }
5082        }
5083        if (comp != null) {
5084            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5085            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5086            if (pi != null) {
5087                final ResolveInfo ri = new ResolveInfo();
5088                ri.providerInfo = pi;
5089                list.add(ri);
5090            }
5091            return list;
5092        }
5093
5094        // reader
5095        synchronized (mPackages) {
5096            String pkgName = intent.getPackage();
5097            if (pkgName == null) {
5098                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5099            }
5100            final PackageParser.Package pkg = mPackages.get(pkgName);
5101            if (pkg != null) {
5102                return mProviders.queryIntentForPackage(
5103                        intent, resolvedType, flags, pkg.providers, userId);
5104            }
5105            return null;
5106        }
5107    }
5108
5109    @Override
5110    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5111        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5112
5113        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5114
5115        // writer
5116        synchronized (mPackages) {
5117            ArrayList<PackageInfo> list;
5118            if (listUninstalled) {
5119                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5120                for (PackageSetting ps : mSettings.mPackages.values()) {
5121                    PackageInfo pi;
5122                    if (ps.pkg != null) {
5123                        pi = generatePackageInfo(ps.pkg, flags, userId);
5124                    } else {
5125                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5126                    }
5127                    if (pi != null) {
5128                        list.add(pi);
5129                    }
5130                }
5131            } else {
5132                list = new ArrayList<PackageInfo>(mPackages.size());
5133                for (PackageParser.Package p : mPackages.values()) {
5134                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5135                    if (pi != null) {
5136                        list.add(pi);
5137                    }
5138                }
5139            }
5140
5141            return new ParceledListSlice<PackageInfo>(list);
5142        }
5143    }
5144
5145    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5146            String[] permissions, boolean[] tmp, int flags, int userId) {
5147        int numMatch = 0;
5148        final PermissionsState permissionsState = ps.getPermissionsState();
5149        for (int i=0; i<permissions.length; i++) {
5150            final String permission = permissions[i];
5151            if (permissionsState.hasPermission(permission, userId)) {
5152                tmp[i] = true;
5153                numMatch++;
5154            } else {
5155                tmp[i] = false;
5156            }
5157        }
5158        if (numMatch == 0) {
5159            return;
5160        }
5161        PackageInfo pi;
5162        if (ps.pkg != null) {
5163            pi = generatePackageInfo(ps.pkg, flags, userId);
5164        } else {
5165            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5166        }
5167        // The above might return null in cases of uninstalled apps or install-state
5168        // skew across users/profiles.
5169        if (pi != null) {
5170            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5171                if (numMatch == permissions.length) {
5172                    pi.requestedPermissions = permissions;
5173                } else {
5174                    pi.requestedPermissions = new String[numMatch];
5175                    numMatch = 0;
5176                    for (int i=0; i<permissions.length; i++) {
5177                        if (tmp[i]) {
5178                            pi.requestedPermissions[numMatch] = permissions[i];
5179                            numMatch++;
5180                        }
5181                    }
5182                }
5183            }
5184            list.add(pi);
5185        }
5186    }
5187
5188    @Override
5189    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5190            String[] permissions, int flags, int userId) {
5191        if (!sUserManager.exists(userId)) return null;
5192        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5193
5194        // writer
5195        synchronized (mPackages) {
5196            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5197            boolean[] tmpBools = new boolean[permissions.length];
5198            if (listUninstalled) {
5199                for (PackageSetting ps : mSettings.mPackages.values()) {
5200                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5201                }
5202            } else {
5203                for (PackageParser.Package pkg : mPackages.values()) {
5204                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5205                    if (ps != null) {
5206                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5207                                userId);
5208                    }
5209                }
5210            }
5211
5212            return new ParceledListSlice<PackageInfo>(list);
5213        }
5214    }
5215
5216    @Override
5217    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5218        if (!sUserManager.exists(userId)) return null;
5219        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5220
5221        // writer
5222        synchronized (mPackages) {
5223            ArrayList<ApplicationInfo> list;
5224            if (listUninstalled) {
5225                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5226                for (PackageSetting ps : mSettings.mPackages.values()) {
5227                    ApplicationInfo ai;
5228                    if (ps.pkg != null) {
5229                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5230                                ps.readUserState(userId), userId);
5231                    } else {
5232                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5233                    }
5234                    if (ai != null) {
5235                        list.add(ai);
5236                    }
5237                }
5238            } else {
5239                list = new ArrayList<ApplicationInfo>(mPackages.size());
5240                for (PackageParser.Package p : mPackages.values()) {
5241                    if (p.mExtras != null) {
5242                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5243                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5244                        if (ai != null) {
5245                            list.add(ai);
5246                        }
5247                    }
5248                }
5249            }
5250
5251            return new ParceledListSlice<ApplicationInfo>(list);
5252        }
5253    }
5254
5255    public List<ApplicationInfo> getPersistentApplications(int flags) {
5256        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5257
5258        // reader
5259        synchronized (mPackages) {
5260            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5261            final int userId = UserHandle.getCallingUserId();
5262            while (i.hasNext()) {
5263                final PackageParser.Package p = i.next();
5264                if (p.applicationInfo != null
5265                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5266                        && (!mSafeMode || isSystemApp(p))) {
5267                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5268                    if (ps != null) {
5269                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5270                                ps.readUserState(userId), userId);
5271                        if (ai != null) {
5272                            finalList.add(ai);
5273                        }
5274                    }
5275                }
5276            }
5277        }
5278
5279        return finalList;
5280    }
5281
5282    @Override
5283    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5284        if (!sUserManager.exists(userId)) return null;
5285        // reader
5286        synchronized (mPackages) {
5287            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5288            PackageSetting ps = provider != null
5289                    ? mSettings.mPackages.get(provider.owner.packageName)
5290                    : null;
5291            return ps != null
5292                    && mSettings.isEnabledLPr(provider.info, flags, userId)
5293                    && (!mSafeMode || (provider.info.applicationInfo.flags
5294                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5295                    ? PackageParser.generateProviderInfo(provider, flags,
5296                            ps.readUserState(userId), userId)
5297                    : null;
5298        }
5299    }
5300
5301    /**
5302     * @deprecated
5303     */
5304    @Deprecated
5305    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5306        // reader
5307        synchronized (mPackages) {
5308            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5309                    .entrySet().iterator();
5310            final int userId = UserHandle.getCallingUserId();
5311            while (i.hasNext()) {
5312                Map.Entry<String, PackageParser.Provider> entry = i.next();
5313                PackageParser.Provider p = entry.getValue();
5314                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5315
5316                if (ps != null && p.syncable
5317                        && (!mSafeMode || (p.info.applicationInfo.flags
5318                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5319                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5320                            ps.readUserState(userId), userId);
5321                    if (info != null) {
5322                        outNames.add(entry.getKey());
5323                        outInfo.add(info);
5324                    }
5325                }
5326            }
5327        }
5328    }
5329
5330    @Override
5331    public List<ProviderInfo> queryContentProviders(String processName,
5332            int uid, int flags) {
5333        ArrayList<ProviderInfo> finalList = null;
5334        // reader
5335        synchronized (mPackages) {
5336            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5337            final int userId = processName != null ?
5338                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
5339            while (i.hasNext()) {
5340                final PackageParser.Provider p = i.next();
5341                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5342                if (ps != null && p.info.authority != null
5343                        && (processName == null
5344                                || (p.info.processName.equals(processName)
5345                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5346                        && mSettings.isEnabledLPr(p.info, flags, userId)
5347                        && (!mSafeMode
5348                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5349                    if (finalList == null) {
5350                        finalList = new ArrayList<ProviderInfo>(3);
5351                    }
5352                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5353                            ps.readUserState(userId), userId);
5354                    if (info != null) {
5355                        finalList.add(info);
5356                    }
5357                }
5358            }
5359        }
5360
5361        if (finalList != null) {
5362            Collections.sort(finalList, mProviderInitOrderSorter);
5363        }
5364
5365        return finalList;
5366    }
5367
5368    @Override
5369    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
5370            int flags) {
5371        // reader
5372        synchronized (mPackages) {
5373            final PackageParser.Instrumentation i = mInstrumentation.get(name);
5374            return PackageParser.generateInstrumentationInfo(i, flags);
5375        }
5376    }
5377
5378    @Override
5379    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
5380            int flags) {
5381        ArrayList<InstrumentationInfo> finalList =
5382            new ArrayList<InstrumentationInfo>();
5383
5384        // reader
5385        synchronized (mPackages) {
5386            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
5387            while (i.hasNext()) {
5388                final PackageParser.Instrumentation p = i.next();
5389                if (targetPackage == null
5390                        || targetPackage.equals(p.info.targetPackage)) {
5391                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
5392                            flags);
5393                    if (ii != null) {
5394                        finalList.add(ii);
5395                    }
5396                }
5397            }
5398        }
5399
5400        return finalList;
5401    }
5402
5403    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
5404        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
5405        if (overlays == null) {
5406            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
5407            return;
5408        }
5409        for (PackageParser.Package opkg : overlays.values()) {
5410            // Not much to do if idmap fails: we already logged the error
5411            // and we certainly don't want to abort installation of pkg simply
5412            // because an overlay didn't fit properly. For these reasons,
5413            // ignore the return value of createIdmapForPackagePairLI.
5414            createIdmapForPackagePairLI(pkg, opkg);
5415        }
5416    }
5417
5418    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
5419            PackageParser.Package opkg) {
5420        if (!opkg.mTrustedOverlay) {
5421            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
5422                    opkg.baseCodePath + ": overlay not trusted");
5423            return false;
5424        }
5425        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
5426        if (overlaySet == null) {
5427            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
5428                    opkg.baseCodePath + " but target package has no known overlays");
5429            return false;
5430        }
5431        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
5432        // TODO: generate idmap for split APKs
5433        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
5434            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
5435                    + opkg.baseCodePath);
5436            return false;
5437        }
5438        PackageParser.Package[] overlayArray =
5439            overlaySet.values().toArray(new PackageParser.Package[0]);
5440        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
5441            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
5442                return p1.mOverlayPriority - p2.mOverlayPriority;
5443            }
5444        };
5445        Arrays.sort(overlayArray, cmp);
5446
5447        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5448        int i = 0;
5449        for (PackageParser.Package p : overlayArray) {
5450            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5451        }
5452        return true;
5453    }
5454
5455    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5456        final File[] files = dir.listFiles();
5457        if (ArrayUtils.isEmpty(files)) {
5458            Log.d(TAG, "No files in app dir " + dir);
5459            return;
5460        }
5461
5462        if (DEBUG_PACKAGE_SCANNING) {
5463            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
5464                    + " flags=0x" + Integer.toHexString(parseFlags));
5465        }
5466
5467        for (File file : files) {
5468            final boolean isPackage = (isApkFile(file) || file.isDirectory())
5469                    && !PackageInstallerService.isStageName(file.getName());
5470            if (!isPackage) {
5471                // Ignore entries which are not packages
5472                continue;
5473            }
5474            try {
5475                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
5476                        scanFlags, currentTime, null);
5477            } catch (PackageManagerException e) {
5478                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
5479
5480                // Delete invalid userdata apps
5481                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
5482                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
5483                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
5484                    if (file.isDirectory()) {
5485                        mInstaller.rmPackageDir(file.getAbsolutePath());
5486                    } else {
5487                        file.delete();
5488                    }
5489                }
5490            }
5491        }
5492    }
5493
5494    private static File getSettingsProblemFile() {
5495        File dataDir = Environment.getDataDirectory();
5496        File systemDir = new File(dataDir, "system");
5497        File fname = new File(systemDir, "uiderrors.txt");
5498        return fname;
5499    }
5500
5501    static void reportSettingsProblem(int priority, String msg) {
5502        logCriticalInfo(priority, msg);
5503    }
5504
5505    static void logCriticalInfo(int priority, String msg) {
5506        Slog.println(priority, TAG, msg);
5507        EventLogTags.writePmCriticalInfo(msg);
5508        try {
5509            File fname = getSettingsProblemFile();
5510            FileOutputStream out = new FileOutputStream(fname, true);
5511            PrintWriter pw = new FastPrintWriter(out);
5512            SimpleDateFormat formatter = new SimpleDateFormat();
5513            String dateString = formatter.format(new Date(System.currentTimeMillis()));
5514            pw.println(dateString + ": " + msg);
5515            pw.close();
5516            FileUtils.setPermissions(
5517                    fname.toString(),
5518                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5519                    -1, -1);
5520        } catch (java.io.IOException e) {
5521        }
5522    }
5523
5524    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5525            PackageParser.Package pkg, File srcFile, int parseFlags)
5526            throws PackageManagerException {
5527        if (ps != null
5528                && ps.codePath.equals(srcFile)
5529                && ps.timeStamp == srcFile.lastModified()
5530                && !isCompatSignatureUpdateNeeded(pkg)
5531                && !isRecoverSignatureUpdateNeeded(pkg)) {
5532            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5533            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5534            ArraySet<PublicKey> signingKs;
5535            synchronized (mPackages) {
5536                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
5537            }
5538            if (ps.signatures.mSignatures != null
5539                    && ps.signatures.mSignatures.length != 0
5540                    && signingKs != null) {
5541                // Optimization: reuse the existing cached certificates
5542                // if the package appears to be unchanged.
5543                pkg.mSignatures = ps.signatures.mSignatures;
5544                pkg.mSigningKeys = signingKs;
5545                return;
5546            }
5547
5548            Slog.w(TAG, "PackageSetting for " + ps.name
5549                    + " is missing signatures.  Collecting certs again to recover them.");
5550        } else {
5551            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
5552        }
5553
5554        try {
5555            pp.collectCertificates(pkg, parseFlags);
5556            pp.collectManifestDigest(pkg);
5557        } catch (PackageParserException e) {
5558            throw PackageManagerException.from(e);
5559        }
5560    }
5561
5562    /*
5563     *  Scan a package and return the newly parsed package.
5564     *  Returns null in case of errors and the error code is stored in mLastScanError
5565     */
5566    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
5567            long currentTime, UserHandle user) throws PackageManagerException {
5568        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
5569        parseFlags |= mDefParseFlags;
5570        PackageParser pp = new PackageParser();
5571        pp.setSeparateProcesses(mSeparateProcesses);
5572        pp.setOnlyCoreApps(mOnlyCore);
5573        pp.setDisplayMetrics(mMetrics);
5574
5575        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
5576            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
5577        }
5578
5579        final PackageParser.Package pkg;
5580        try {
5581            pkg = pp.parsePackage(scanFile, parseFlags);
5582        } catch (PackageParserException e) {
5583            throw PackageManagerException.from(e);
5584        }
5585
5586        PackageSetting ps = null;
5587        PackageSetting updatedPkg;
5588        // reader
5589        synchronized (mPackages) {
5590            // Look to see if we already know about this package.
5591            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
5592            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
5593                // This package has been renamed to its original name.  Let's
5594                // use that.
5595                ps = mSettings.peekPackageLPr(oldName);
5596            }
5597            // If there was no original package, see one for the real package name.
5598            if (ps == null) {
5599                ps = mSettings.peekPackageLPr(pkg.packageName);
5600            }
5601            // Check to see if this package could be hiding/updating a system
5602            // package.  Must look for it either under the original or real
5603            // package name depending on our state.
5604            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
5605            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
5606        }
5607        boolean updatedPkgBetter = false;
5608        // First check if this is a system package that may involve an update
5609        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5610            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
5611            // it needs to drop FLAG_PRIVILEGED.
5612            if (locationIsPrivileged(scanFile)) {
5613                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5614            } else {
5615                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5616            }
5617
5618            if (ps != null && !ps.codePath.equals(scanFile)) {
5619                // The path has changed from what was last scanned...  check the
5620                // version of the new path against what we have stored to determine
5621                // what to do.
5622                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
5623                if (pkg.mVersionCode <= ps.versionCode) {
5624                    // The system package has been updated and the code path does not match
5625                    // Ignore entry. Skip it.
5626                    Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5627                            + " ignored: updated version " + ps.versionCode
5628                            + " better than this " + pkg.mVersionCode);
5629                    if (!updatedPkg.codePath.equals(scanFile)) {
5630                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5631                                + ps.name + " changing from " + updatedPkg.codePathString
5632                                + " to " + scanFile);
5633                        updatedPkg.codePath = scanFile;
5634                        updatedPkg.codePathString = scanFile.toString();
5635                        updatedPkg.resourcePath = scanFile;
5636                        updatedPkg.resourcePathString = scanFile.toString();
5637                    }
5638                    updatedPkg.pkg = pkg;
5639                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null);
5640                } else {
5641                    // The current app on the system partition is better than
5642                    // what we have updated to on the data partition; switch
5643                    // back to the system partition version.
5644                    // At this point, its safely assumed that package installation for
5645                    // apps in system partition will go through. If not there won't be a working
5646                    // version of the app
5647                    // writer
5648                    synchronized (mPackages) {
5649                        // Just remove the loaded entries from package lists.
5650                        mPackages.remove(ps.name);
5651                    }
5652
5653                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5654                            + " reverting from " + ps.codePathString
5655                            + ": new version " + pkg.mVersionCode
5656                            + " better than installed " + ps.versionCode);
5657
5658                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5659                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5660                    synchronized (mInstallLock) {
5661                        args.cleanUpResourcesLI();
5662                    }
5663                    synchronized (mPackages) {
5664                        mSettings.enableSystemPackageLPw(ps.name);
5665                    }
5666                    updatedPkgBetter = true;
5667                }
5668            }
5669        }
5670
5671        if (updatedPkg != null) {
5672            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5673            // initially
5674            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5675
5676            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5677            // flag set initially
5678            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5679                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5680            }
5681        }
5682
5683        // Verify certificates against what was last scanned
5684        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5685
5686        /*
5687         * A new system app appeared, but we already had a non-system one of the
5688         * same name installed earlier.
5689         */
5690        boolean shouldHideSystemApp = false;
5691        if (updatedPkg == null && ps != null
5692                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5693            /*
5694             * Check to make sure the signatures match first. If they don't,
5695             * wipe the installed application and its data.
5696             */
5697            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5698                    != PackageManager.SIGNATURE_MATCH) {
5699                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5700                        + " signatures don't match existing userdata copy; removing");
5701                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5702                ps = null;
5703            } else {
5704                /*
5705                 * If the newly-added system app is an older version than the
5706                 * already installed version, hide it. It will be scanned later
5707                 * and re-added like an update.
5708                 */
5709                if (pkg.mVersionCode <= ps.versionCode) {
5710                    shouldHideSystemApp = true;
5711                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5712                            + " but new version " + pkg.mVersionCode + " better than installed "
5713                            + ps.versionCode + "; hiding system");
5714                } else {
5715                    /*
5716                     * The newly found system app is a newer version that the
5717                     * one previously installed. Simply remove the
5718                     * already-installed application and replace it with our own
5719                     * while keeping the application data.
5720                     */
5721                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5722                            + " reverting from " + ps.codePathString + ": new version "
5723                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5724                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5725                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5726                    synchronized (mInstallLock) {
5727                        args.cleanUpResourcesLI();
5728                    }
5729                }
5730            }
5731        }
5732
5733        // The apk is forward locked (not public) if its code and resources
5734        // are kept in different files. (except for app in either system or
5735        // vendor path).
5736        // TODO grab this value from PackageSettings
5737        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5738            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5739                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5740            }
5741        }
5742
5743        // TODO: extend to support forward-locked splits
5744        String resourcePath = null;
5745        String baseResourcePath = null;
5746        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5747            if (ps != null && ps.resourcePathString != null) {
5748                resourcePath = ps.resourcePathString;
5749                baseResourcePath = ps.resourcePathString;
5750            } else {
5751                // Should not happen at all. Just log an error.
5752                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5753            }
5754        } else {
5755            resourcePath = pkg.codePath;
5756            baseResourcePath = pkg.baseCodePath;
5757        }
5758
5759        // Set application objects path explicitly.
5760        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
5761        pkg.applicationInfo.setCodePath(pkg.codePath);
5762        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5763        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5764        pkg.applicationInfo.setResourcePath(resourcePath);
5765        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5766        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5767
5768        // Note that we invoke the following method only if we are about to unpack an application
5769        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5770                | SCAN_UPDATE_SIGNATURE, currentTime, user);
5771
5772        /*
5773         * If the system app should be overridden by a previously installed
5774         * data, hide the system app now and let the /data/app scan pick it up
5775         * again.
5776         */
5777        if (shouldHideSystemApp) {
5778            synchronized (mPackages) {
5779                /*
5780                 * We have to grant systems permissions before we hide, because
5781                 * grantPermissions will assume the package update is trying to
5782                 * expand its permissions.
5783                 */
5784                grantPermissionsLPw(pkg, true, pkg.packageName);
5785                mSettings.disableSystemPackageLPw(pkg.packageName);
5786            }
5787        }
5788
5789        return scannedPkg;
5790    }
5791
5792    private static String fixProcessName(String defProcessName,
5793            String processName, int uid) {
5794        if (processName == null) {
5795            return defProcessName;
5796        }
5797        return processName;
5798    }
5799
5800    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
5801            throws PackageManagerException {
5802        if (pkgSetting.signatures.mSignatures != null) {
5803            // Already existing package. Make sure signatures match
5804            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
5805                    == PackageManager.SIGNATURE_MATCH;
5806            if (!match) {
5807                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
5808                        == PackageManager.SIGNATURE_MATCH;
5809            }
5810            if (!match) {
5811                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
5812                        == PackageManager.SIGNATURE_MATCH;
5813            }
5814            if (!match) {
5815                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5816                        + pkg.packageName + " signatures do not match the "
5817                        + "previously installed version; ignoring!");
5818            }
5819        }
5820
5821        // Check for shared user signatures
5822        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
5823            // Already existing package. Make sure signatures match
5824            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5825                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
5826            if (!match) {
5827                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
5828                        == PackageManager.SIGNATURE_MATCH;
5829            }
5830            if (!match) {
5831                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
5832                        == PackageManager.SIGNATURE_MATCH;
5833            }
5834            if (!match) {
5835                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
5836                        "Package " + pkg.packageName
5837                        + " has no signatures that match those in shared user "
5838                        + pkgSetting.sharedUser.name + "; ignoring!");
5839            }
5840        }
5841    }
5842
5843    /**
5844     * Enforces that only the system UID or root's UID can call a method exposed
5845     * via Binder.
5846     *
5847     * @param message used as message if SecurityException is thrown
5848     * @throws SecurityException if the caller is not system or root
5849     */
5850    private static final void enforceSystemOrRoot(String message) {
5851        final int uid = Binder.getCallingUid();
5852        if (uid != Process.SYSTEM_UID && uid != 0) {
5853            throw new SecurityException(message);
5854        }
5855    }
5856
5857    @Override
5858    public void performBootDexOpt() {
5859        enforceSystemOrRoot("Only the system can request dexopt be performed");
5860
5861        // Before everything else, see whether we need to fstrim.
5862        try {
5863            IMountService ms = PackageHelper.getMountService();
5864            if (ms != null) {
5865                final boolean isUpgrade = isUpgrade();
5866                boolean doTrim = isUpgrade;
5867                if (doTrim) {
5868                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
5869                } else {
5870                    final long interval = android.provider.Settings.Global.getLong(
5871                            mContext.getContentResolver(),
5872                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
5873                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
5874                    if (interval > 0) {
5875                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
5876                        if (timeSinceLast > interval) {
5877                            doTrim = true;
5878                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
5879                                    + "; running immediately");
5880                        }
5881                    }
5882                }
5883                if (doTrim) {
5884                    if (!isFirstBoot()) {
5885                        try {
5886                            ActivityManagerNative.getDefault().showBootMessage(
5887                                    mContext.getResources().getString(
5888                                            R.string.android_upgrading_fstrim), true);
5889                        } catch (RemoteException e) {
5890                        }
5891                    }
5892                    ms.runMaintenance();
5893                }
5894            } else {
5895                Slog.e(TAG, "Mount service unavailable!");
5896            }
5897        } catch (RemoteException e) {
5898            // Can't happen; MountService is local
5899        }
5900
5901        final ArraySet<PackageParser.Package> pkgs;
5902        synchronized (mPackages) {
5903            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
5904        }
5905
5906        if (pkgs != null) {
5907            // Sort apps by importance for dexopt ordering. Important apps are given more priority
5908            // in case the device runs out of space.
5909            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
5910            // Give priority to core apps.
5911            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5912                PackageParser.Package pkg = it.next();
5913                if (pkg.coreApp) {
5914                    if (DEBUG_DEXOPT) {
5915                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
5916                    }
5917                    sortedPkgs.add(pkg);
5918                    it.remove();
5919                }
5920            }
5921            // Give priority to system apps that listen for pre boot complete.
5922            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
5923            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
5924            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5925                PackageParser.Package pkg = it.next();
5926                if (pkgNames.contains(pkg.packageName)) {
5927                    if (DEBUG_DEXOPT) {
5928                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
5929                    }
5930                    sortedPkgs.add(pkg);
5931                    it.remove();
5932                }
5933            }
5934            // Give priority to system apps.
5935            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5936                PackageParser.Package pkg = it.next();
5937                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
5938                    if (DEBUG_DEXOPT) {
5939                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
5940                    }
5941                    sortedPkgs.add(pkg);
5942                    it.remove();
5943                }
5944            }
5945            // Give priority to updated system apps.
5946            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5947                PackageParser.Package pkg = it.next();
5948                if (pkg.isUpdatedSystemApp()) {
5949                    if (DEBUG_DEXOPT) {
5950                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
5951                    }
5952                    sortedPkgs.add(pkg);
5953                    it.remove();
5954                }
5955            }
5956            // Give priority to apps that listen for boot complete.
5957            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
5958            pkgNames = getPackageNamesForIntent(intent);
5959            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5960                PackageParser.Package pkg = it.next();
5961                if (pkgNames.contains(pkg.packageName)) {
5962                    if (DEBUG_DEXOPT) {
5963                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
5964                    }
5965                    sortedPkgs.add(pkg);
5966                    it.remove();
5967                }
5968            }
5969            // Filter out packages that aren't recently used.
5970            filterRecentlyUsedApps(pkgs);
5971            // Add all remaining apps.
5972            for (PackageParser.Package pkg : pkgs) {
5973                if (DEBUG_DEXOPT) {
5974                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
5975                }
5976                sortedPkgs.add(pkg);
5977            }
5978
5979            // If we want to be lazy, filter everything that wasn't recently used.
5980            if (mLazyDexOpt) {
5981                filterRecentlyUsedApps(sortedPkgs);
5982            }
5983
5984            int i = 0;
5985            int total = sortedPkgs.size();
5986            File dataDir = Environment.getDataDirectory();
5987            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
5988            if (lowThreshold == 0) {
5989                throw new IllegalStateException("Invalid low memory threshold");
5990            }
5991            for (PackageParser.Package pkg : sortedPkgs) {
5992                long usableSpace = dataDir.getUsableSpace();
5993                if (usableSpace < lowThreshold) {
5994                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
5995                    break;
5996                }
5997                performBootDexOpt(pkg, ++i, total);
5998            }
5999        }
6000    }
6001
6002    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
6003        // Filter out packages that aren't recently used.
6004        //
6005        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
6006        // should do a full dexopt.
6007        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
6008            int total = pkgs.size();
6009            int skipped = 0;
6010            long now = System.currentTimeMillis();
6011            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
6012                PackageParser.Package pkg = i.next();
6013                long then = pkg.mLastPackageUsageTimeInMills;
6014                if (then + mDexOptLRUThresholdInMills < now) {
6015                    if (DEBUG_DEXOPT) {
6016                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
6017                              ((then == 0) ? "never" : new Date(then)));
6018                    }
6019                    i.remove();
6020                    skipped++;
6021                }
6022            }
6023            if (DEBUG_DEXOPT) {
6024                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
6025            }
6026        }
6027    }
6028
6029    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
6030        List<ResolveInfo> ris = null;
6031        try {
6032            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6033                    intent, null, 0, UserHandle.USER_OWNER);
6034        } catch (RemoteException e) {
6035        }
6036        ArraySet<String> pkgNames = new ArraySet<String>();
6037        if (ris != null) {
6038            for (ResolveInfo ri : ris) {
6039                pkgNames.add(ri.activityInfo.packageName);
6040            }
6041        }
6042        return pkgNames;
6043    }
6044
6045    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
6046        if (DEBUG_DEXOPT) {
6047            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
6048        }
6049        if (!isFirstBoot()) {
6050            try {
6051                ActivityManagerNative.getDefault().showBootMessage(
6052                        mContext.getResources().getString(R.string.android_upgrading_apk,
6053                                curr, total), true);
6054            } catch (RemoteException e) {
6055            }
6056        }
6057        PackageParser.Package p = pkg;
6058        synchronized (mInstallLock) {
6059            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
6060                    false /* force dex */, false /* defer */, true /* include dependencies */);
6061        }
6062    }
6063
6064    @Override
6065    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6066        return performDexOpt(packageName, instructionSet, false);
6067    }
6068
6069    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
6070        boolean dexopt = mLazyDexOpt || backgroundDexopt;
6071        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
6072        if (!dexopt && !updateUsage) {
6073            // We aren't going to dexopt or update usage, so bail early.
6074            return false;
6075        }
6076        PackageParser.Package p;
6077        final String targetInstructionSet;
6078        synchronized (mPackages) {
6079            p = mPackages.get(packageName);
6080            if (p == null) {
6081                return false;
6082            }
6083            if (updateUsage) {
6084                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6085            }
6086            mPackageUsage.write(false);
6087            if (!dexopt) {
6088                // We aren't going to dexopt, so bail early.
6089                return false;
6090            }
6091
6092            targetInstructionSet = instructionSet != null ? instructionSet :
6093                    getPrimaryInstructionSet(p.applicationInfo);
6094            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
6095                return false;
6096            }
6097        }
6098
6099        synchronized (mInstallLock) {
6100            final String[] instructionSets = new String[] { targetInstructionSet };
6101            int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6102                    false /* forceDex */, false /* defer */, true /* inclDependencies */);
6103            return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6104        }
6105    }
6106
6107    public ArraySet<String> getPackagesThatNeedDexOpt() {
6108        ArraySet<String> pkgs = null;
6109        synchronized (mPackages) {
6110            for (PackageParser.Package p : mPackages.values()) {
6111                if (DEBUG_DEXOPT) {
6112                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6113                }
6114                if (!p.mDexOptPerformed.isEmpty()) {
6115                    continue;
6116                }
6117                if (pkgs == null) {
6118                    pkgs = new ArraySet<String>();
6119                }
6120                pkgs.add(p.packageName);
6121            }
6122        }
6123        return pkgs;
6124    }
6125
6126    public void shutdown() {
6127        mPackageUsage.write(true);
6128    }
6129
6130    @Override
6131    public void forceDexOpt(String packageName) {
6132        enforceSystemOrRoot("forceDexOpt");
6133
6134        PackageParser.Package pkg;
6135        synchronized (mPackages) {
6136            pkg = mPackages.get(packageName);
6137            if (pkg == null) {
6138                throw new IllegalArgumentException("Missing package: " + packageName);
6139            }
6140        }
6141
6142        synchronized (mInstallLock) {
6143            final String[] instructionSets = new String[] {
6144                    getPrimaryInstructionSet(pkg.applicationInfo) };
6145            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6146                    true /*forceDex*/, false /* defer */, true /* inclDependencies */);
6147            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6148                throw new IllegalStateException("Failed to dexopt: " + res);
6149            }
6150        }
6151    }
6152
6153    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6154        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6155            Slog.w(TAG, "Unable to update from " + oldPkg.name
6156                    + " to " + newPkg.packageName
6157                    + ": old package not in system partition");
6158            return false;
6159        } else if (mPackages.get(oldPkg.name) != null) {
6160            Slog.w(TAG, "Unable to update from " + oldPkg.name
6161                    + " to " + newPkg.packageName
6162                    + ": old package still exists");
6163            return false;
6164        }
6165        return true;
6166    }
6167
6168    private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
6169        int[] users = sUserManager.getUserIds();
6170        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
6171        if (res < 0) {
6172            return res;
6173        }
6174        for (int user : users) {
6175            if (user != 0) {
6176                res = mInstaller.createUserData(volumeUuid, packageName,
6177                        UserHandle.getUid(user, uid), user, seinfo);
6178                if (res < 0) {
6179                    return res;
6180                }
6181            }
6182        }
6183        return res;
6184    }
6185
6186    private int removeDataDirsLI(String volumeUuid, String packageName) {
6187        int[] users = sUserManager.getUserIds();
6188        int res = 0;
6189        for (int user : users) {
6190            int resInner = mInstaller.remove(volumeUuid, packageName, user);
6191            if (resInner < 0) {
6192                res = resInner;
6193            }
6194        }
6195
6196        return res;
6197    }
6198
6199    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6200        int[] users = sUserManager.getUserIds();
6201        int res = 0;
6202        for (int user : users) {
6203            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
6204            if (resInner < 0) {
6205                res = resInner;
6206            }
6207        }
6208        return res;
6209    }
6210
6211    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6212            PackageParser.Package changingLib) {
6213        if (file.path != null) {
6214            usesLibraryFiles.add(file.path);
6215            return;
6216        }
6217        PackageParser.Package p = mPackages.get(file.apk);
6218        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6219            // If we are doing this while in the middle of updating a library apk,
6220            // then we need to make sure to use that new apk for determining the
6221            // dependencies here.  (We haven't yet finished committing the new apk
6222            // to the package manager state.)
6223            if (p == null || p.packageName.equals(changingLib.packageName)) {
6224                p = changingLib;
6225            }
6226        }
6227        if (p != null) {
6228            usesLibraryFiles.addAll(p.getAllCodePaths());
6229        }
6230    }
6231
6232    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6233            PackageParser.Package changingLib) throws PackageManagerException {
6234        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6235            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6236            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6237            for (int i=0; i<N; i++) {
6238                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6239                if (file == null) {
6240                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6241                            "Package " + pkg.packageName + " requires unavailable shared library "
6242                            + pkg.usesLibraries.get(i) + "; failing!");
6243                }
6244                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6245            }
6246            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6247            for (int i=0; i<N; i++) {
6248                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6249                if (file == null) {
6250                    Slog.w(TAG, "Package " + pkg.packageName
6251                            + " desires unavailable shared library "
6252                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6253                } else {
6254                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6255                }
6256            }
6257            N = usesLibraryFiles.size();
6258            if (N > 0) {
6259                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6260            } else {
6261                pkg.usesLibraryFiles = null;
6262            }
6263        }
6264    }
6265
6266    private static boolean hasString(List<String> list, List<String> which) {
6267        if (list == null) {
6268            return false;
6269        }
6270        for (int i=list.size()-1; i>=0; i--) {
6271            for (int j=which.size()-1; j>=0; j--) {
6272                if (which.get(j).equals(list.get(i))) {
6273                    return true;
6274                }
6275            }
6276        }
6277        return false;
6278    }
6279
6280    private void updateAllSharedLibrariesLPw() {
6281        for (PackageParser.Package pkg : mPackages.values()) {
6282            try {
6283                updateSharedLibrariesLPw(pkg, null);
6284            } catch (PackageManagerException e) {
6285                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6286            }
6287        }
6288    }
6289
6290    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6291            PackageParser.Package changingPkg) {
6292        ArrayList<PackageParser.Package> res = null;
6293        for (PackageParser.Package pkg : mPackages.values()) {
6294            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6295                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6296                if (res == null) {
6297                    res = new ArrayList<PackageParser.Package>();
6298                }
6299                res.add(pkg);
6300                try {
6301                    updateSharedLibrariesLPw(pkg, changingPkg);
6302                } catch (PackageManagerException e) {
6303                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6304                }
6305            }
6306        }
6307        return res;
6308    }
6309
6310    /**
6311     * Derive the value of the {@code cpuAbiOverride} based on the provided
6312     * value and an optional stored value from the package settings.
6313     */
6314    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6315        String cpuAbiOverride = null;
6316
6317        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6318            cpuAbiOverride = null;
6319        } else if (abiOverride != null) {
6320            cpuAbiOverride = abiOverride;
6321        } else if (settings != null) {
6322            cpuAbiOverride = settings.cpuAbiOverrideString;
6323        }
6324
6325        return cpuAbiOverride;
6326    }
6327
6328    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6329            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6330        boolean success = false;
6331        try {
6332            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6333                    currentTime, user);
6334            success = true;
6335            return res;
6336        } finally {
6337            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6338                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6339            }
6340        }
6341    }
6342
6343    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6344            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6345        final File scanFile = new File(pkg.codePath);
6346        if (pkg.applicationInfo.getCodePath() == null ||
6347                pkg.applicationInfo.getResourcePath() == null) {
6348            // Bail out. The resource and code paths haven't been set.
6349            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6350                    "Code and resource paths haven't been set correctly");
6351        }
6352
6353        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6354            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6355        } else {
6356            // Only allow system apps to be flagged as core apps.
6357            pkg.coreApp = false;
6358        }
6359
6360        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6361            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6362        }
6363
6364        if (mCustomResolverComponentName != null &&
6365                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6366            setUpCustomResolverActivity(pkg);
6367        }
6368
6369        if (pkg.packageName.equals("android")) {
6370            synchronized (mPackages) {
6371                if (mAndroidApplication != null) {
6372                    Slog.w(TAG, "*************************************************");
6373                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6374                    Slog.w(TAG, " file=" + scanFile);
6375                    Slog.w(TAG, "*************************************************");
6376                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6377                            "Core android package being redefined.  Skipping.");
6378                }
6379
6380                // Set up information for our fall-back user intent resolution activity.
6381                mPlatformPackage = pkg;
6382                pkg.mVersionCode = mSdkVersion;
6383                mAndroidApplication = pkg.applicationInfo;
6384
6385                if (!mResolverReplaced) {
6386                    mResolveActivity.applicationInfo = mAndroidApplication;
6387                    mResolveActivity.name = ResolverActivity.class.getName();
6388                    mResolveActivity.packageName = mAndroidApplication.packageName;
6389                    mResolveActivity.processName = "system:ui";
6390                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6391                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6392                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6393                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6394                    mResolveActivity.exported = true;
6395                    mResolveActivity.enabled = true;
6396                    mResolveInfo.activityInfo = mResolveActivity;
6397                    mResolveInfo.priority = 0;
6398                    mResolveInfo.preferredOrder = 0;
6399                    mResolveInfo.match = 0;
6400                    mResolveComponentName = new ComponentName(
6401                            mAndroidApplication.packageName, mResolveActivity.name);
6402                }
6403            }
6404        }
6405
6406        if (DEBUG_PACKAGE_SCANNING) {
6407            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6408                Log.d(TAG, "Scanning package " + pkg.packageName);
6409        }
6410
6411        if (mPackages.containsKey(pkg.packageName)
6412                || mSharedLibraries.containsKey(pkg.packageName)) {
6413            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6414                    "Application package " + pkg.packageName
6415                    + " already installed.  Skipping duplicate.");
6416        }
6417
6418        // If we're only installing presumed-existing packages, require that the
6419        // scanned APK is both already known and at the path previously established
6420        // for it.  Previously unknown packages we pick up normally, but if we have an
6421        // a priori expectation about this package's install presence, enforce it.
6422        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6423            PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6424            if (known != null) {
6425                if (DEBUG_PACKAGE_SCANNING) {
6426                    Log.d(TAG, "Examining " + pkg.codePath
6427                            + " and requiring known paths " + known.codePathString
6428                            + " & " + known.resourcePathString);
6429                }
6430                if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6431                        || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6432                    throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6433                            "Application package " + pkg.packageName
6434                            + " found at " + pkg.applicationInfo.getCodePath()
6435                            + " but expected at " + known.codePathString + "; ignoring.");
6436                }
6437            }
6438        }
6439
6440        // Initialize package source and resource directories
6441        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6442        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6443
6444        SharedUserSetting suid = null;
6445        PackageSetting pkgSetting = null;
6446
6447        if (!isSystemApp(pkg)) {
6448            // Only system apps can use these features.
6449            pkg.mOriginalPackages = null;
6450            pkg.mRealPackage = null;
6451            pkg.mAdoptPermissions = null;
6452        }
6453
6454        // writer
6455        synchronized (mPackages) {
6456            if (pkg.mSharedUserId != null) {
6457                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6458                if (suid == null) {
6459                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6460                            "Creating application package " + pkg.packageName
6461                            + " for shared user failed");
6462                }
6463                if (DEBUG_PACKAGE_SCANNING) {
6464                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6465                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6466                                + "): packages=" + suid.packages);
6467                }
6468            }
6469
6470            // Check if we are renaming from an original package name.
6471            PackageSetting origPackage = null;
6472            String realName = null;
6473            if (pkg.mOriginalPackages != null) {
6474                // This package may need to be renamed to a previously
6475                // installed name.  Let's check on that...
6476                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
6477                if (pkg.mOriginalPackages.contains(renamed)) {
6478                    // This package had originally been installed as the
6479                    // original name, and we have already taken care of
6480                    // transitioning to the new one.  Just update the new
6481                    // one to continue using the old name.
6482                    realName = pkg.mRealPackage;
6483                    if (!pkg.packageName.equals(renamed)) {
6484                        // Callers into this function may have already taken
6485                        // care of renaming the package; only do it here if
6486                        // it is not already done.
6487                        pkg.setPackageName(renamed);
6488                    }
6489
6490                } else {
6491                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
6492                        if ((origPackage = mSettings.peekPackageLPr(
6493                                pkg.mOriginalPackages.get(i))) != null) {
6494                            // We do have the package already installed under its
6495                            // original name...  should we use it?
6496                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
6497                                // New package is not compatible with original.
6498                                origPackage = null;
6499                                continue;
6500                            } else if (origPackage.sharedUser != null) {
6501                                // Make sure uid is compatible between packages.
6502                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6503                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6504                                            + " to " + pkg.packageName + ": old uid "
6505                                            + origPackage.sharedUser.name
6506                                            + " differs from " + pkg.mSharedUserId);
6507                                    origPackage = null;
6508                                    continue;
6509                                }
6510                            } else {
6511                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6512                                        + pkg.packageName + " to old name " + origPackage.name);
6513                            }
6514                            break;
6515                        }
6516                    }
6517                }
6518            }
6519
6520            if (mTransferedPackages.contains(pkg.packageName)) {
6521                Slog.w(TAG, "Package " + pkg.packageName
6522                        + " was transferred to another, but its .apk remains");
6523            }
6524
6525            // Just create the setting, don't add it yet. For already existing packages
6526            // the PkgSetting exists already and doesn't have to be created.
6527            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6528                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6529                    pkg.applicationInfo.primaryCpuAbi,
6530                    pkg.applicationInfo.secondaryCpuAbi,
6531                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6532                    user, false);
6533            if (pkgSetting == null) {
6534                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6535                        "Creating application package " + pkg.packageName + " failed");
6536            }
6537
6538            if (pkgSetting.origPackage != null) {
6539                // If we are first transitioning from an original package,
6540                // fix up the new package's name now.  We need to do this after
6541                // looking up the package under its new name, so getPackageLP
6542                // can take care of fiddling things correctly.
6543                pkg.setPackageName(origPackage.name);
6544
6545                // File a report about this.
6546                String msg = "New package " + pkgSetting.realName
6547                        + " renamed to replace old package " + pkgSetting.name;
6548                reportSettingsProblem(Log.WARN, msg);
6549
6550                // Make a note of it.
6551                mTransferedPackages.add(origPackage.name);
6552
6553                // No longer need to retain this.
6554                pkgSetting.origPackage = null;
6555            }
6556
6557            if (realName != null) {
6558                // Make a note of it.
6559                mTransferedPackages.add(pkg.packageName);
6560            }
6561
6562            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6563                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6564            }
6565
6566            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6567                // Check all shared libraries and map to their actual file path.
6568                // We only do this here for apps not on a system dir, because those
6569                // are the only ones that can fail an install due to this.  We
6570                // will take care of the system apps by updating all of their
6571                // library paths after the scan is done.
6572                updateSharedLibrariesLPw(pkg, null);
6573            }
6574
6575            if (mFoundPolicyFile) {
6576                SELinuxMMAC.assignSeinfoValue(pkg);
6577            }
6578
6579            pkg.applicationInfo.uid = pkgSetting.appId;
6580            pkg.mExtras = pkgSetting;
6581            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
6582                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
6583                    // We just determined the app is signed correctly, so bring
6584                    // over the latest parsed certs.
6585                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6586                } else {
6587                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6588                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6589                                "Package " + pkg.packageName + " upgrade keys do not match the "
6590                                + "previously installed version");
6591                    } else {
6592                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
6593                        String msg = "System package " + pkg.packageName
6594                            + " signature changed; retaining data.";
6595                        reportSettingsProblem(Log.WARN, msg);
6596                    }
6597                }
6598            } else {
6599                try {
6600                    verifySignaturesLP(pkgSetting, pkg);
6601                    // We just determined the app is signed correctly, so bring
6602                    // over the latest parsed certs.
6603                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6604                } catch (PackageManagerException e) {
6605                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6606                        throw e;
6607                    }
6608                    // The signature has changed, but this package is in the system
6609                    // image...  let's recover!
6610                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6611                    // However...  if this package is part of a shared user, but it
6612                    // doesn't match the signature of the shared user, let's fail.
6613                    // What this means is that you can't change the signatures
6614                    // associated with an overall shared user, which doesn't seem all
6615                    // that unreasonable.
6616                    if (pkgSetting.sharedUser != null) {
6617                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6618                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
6619                            throw new PackageManagerException(
6620                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
6621                                            "Signature mismatch for shared user : "
6622                                            + pkgSetting.sharedUser);
6623                        }
6624                    }
6625                    // File a report about this.
6626                    String msg = "System package " + pkg.packageName
6627                        + " signature changed; retaining data.";
6628                    reportSettingsProblem(Log.WARN, msg);
6629                }
6630            }
6631            // Verify that this new package doesn't have any content providers
6632            // that conflict with existing packages.  Only do this if the
6633            // package isn't already installed, since we don't want to break
6634            // things that are installed.
6635            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6636                final int N = pkg.providers.size();
6637                int i;
6638                for (i=0; i<N; i++) {
6639                    PackageParser.Provider p = pkg.providers.get(i);
6640                    if (p.info.authority != null) {
6641                        String names[] = p.info.authority.split(";");
6642                        for (int j = 0; j < names.length; j++) {
6643                            if (mProvidersByAuthority.containsKey(names[j])) {
6644                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6645                                final String otherPackageName =
6646                                        ((other != null && other.getComponentName() != null) ?
6647                                                other.getComponentName().getPackageName() : "?");
6648                                throw new PackageManagerException(
6649                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
6650                                                "Can't install because provider name " + names[j]
6651                                                + " (in package " + pkg.applicationInfo.packageName
6652                                                + ") is already used by " + otherPackageName);
6653                            }
6654                        }
6655                    }
6656                }
6657            }
6658
6659            if (pkg.mAdoptPermissions != null) {
6660                // This package wants to adopt ownership of permissions from
6661                // another package.
6662                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6663                    final String origName = pkg.mAdoptPermissions.get(i);
6664                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
6665                    if (orig != null) {
6666                        if (verifyPackageUpdateLPr(orig, pkg)) {
6667                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
6668                                    + pkg.packageName);
6669                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
6670                        }
6671                    }
6672                }
6673            }
6674        }
6675
6676        final String pkgName = pkg.packageName;
6677
6678        final long scanFileTime = scanFile.lastModified();
6679        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6680        pkg.applicationInfo.processName = fixProcessName(
6681                pkg.applicationInfo.packageName,
6682                pkg.applicationInfo.processName,
6683                pkg.applicationInfo.uid);
6684
6685        File dataPath;
6686        if (mPlatformPackage == pkg) {
6687            // The system package is special.
6688            dataPath = new File(Environment.getDataDirectory(), "system");
6689
6690            pkg.applicationInfo.dataDir = dataPath.getPath();
6691
6692        } else {
6693            // This is a normal package, need to make its data directory.
6694            dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid,
6695                    UserHandle.USER_OWNER, pkg.packageName);
6696
6697            boolean uidError = false;
6698            if (dataPath.exists()) {
6699                int currentUid = 0;
6700                try {
6701                    StructStat stat = Os.stat(dataPath.getPath());
6702                    currentUid = stat.st_uid;
6703                } catch (ErrnoException e) {
6704                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6705                }
6706
6707                // If we have mismatched owners for the data path, we have a problem.
6708                if (currentUid != pkg.applicationInfo.uid) {
6709                    boolean recovered = false;
6710                    if (currentUid == 0) {
6711                        // The directory somehow became owned by root.  Wow.
6712                        // This is probably because the system was stopped while
6713                        // installd was in the middle of messing with its libs
6714                        // directory.  Ask installd to fix that.
6715                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
6716                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
6717                        if (ret >= 0) {
6718                            recovered = true;
6719                            String msg = "Package " + pkg.packageName
6720                                    + " unexpectedly changed to uid 0; recovered to " +
6721                                    + pkg.applicationInfo.uid;
6722                            reportSettingsProblem(Log.WARN, msg);
6723                        }
6724                    }
6725                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6726                            || (scanFlags&SCAN_BOOTING) != 0)) {
6727                        // If this is a system app, we can at least delete its
6728                        // current data so the application will still work.
6729                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
6730                        if (ret >= 0) {
6731                            // TODO: Kill the processes first
6732                            // Old data gone!
6733                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6734                                    ? "System package " : "Third party package ";
6735                            String msg = prefix + pkg.packageName
6736                                    + " has changed from uid: "
6737                                    + currentUid + " to "
6738                                    + pkg.applicationInfo.uid + "; old data erased";
6739                            reportSettingsProblem(Log.WARN, msg);
6740                            recovered = true;
6741
6742                            // And now re-install the app.
6743                            ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6744                                    pkg.applicationInfo.seinfo);
6745                            if (ret == -1) {
6746                                // Ack should not happen!
6747                                msg = prefix + pkg.packageName
6748                                        + " could not have data directory re-created after delete.";
6749                                reportSettingsProblem(Log.WARN, msg);
6750                                throw new PackageManagerException(
6751                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6752                            }
6753                        }
6754                        if (!recovered) {
6755                            mHasSystemUidErrors = true;
6756                        }
6757                    } else if (!recovered) {
6758                        // If we allow this install to proceed, we will be broken.
6759                        // Abort, abort!
6760                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
6761                                "scanPackageLI");
6762                    }
6763                    if (!recovered) {
6764                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
6765                            + pkg.applicationInfo.uid + "/fs_"
6766                            + currentUid;
6767                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
6768                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
6769                        String msg = "Package " + pkg.packageName
6770                                + " has mismatched uid: "
6771                                + currentUid + " on disk, "
6772                                + pkg.applicationInfo.uid + " in settings";
6773                        // writer
6774                        synchronized (mPackages) {
6775                            mSettings.mReadMessages.append(msg);
6776                            mSettings.mReadMessages.append('\n');
6777                            uidError = true;
6778                            if (!pkgSetting.uidError) {
6779                                reportSettingsProblem(Log.ERROR, msg);
6780                            }
6781                        }
6782                    }
6783                }
6784                pkg.applicationInfo.dataDir = dataPath.getPath();
6785                if (mShouldRestoreconData) {
6786                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
6787                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
6788                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
6789                }
6790            } else {
6791                if (DEBUG_PACKAGE_SCANNING) {
6792                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6793                        Log.v(TAG, "Want this data dir: " + dataPath);
6794                }
6795                //invoke installer to do the actual installation
6796                int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6797                        pkg.applicationInfo.seinfo);
6798                if (ret < 0) {
6799                    // Error from installer
6800                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6801                            "Unable to create data dirs [errorCode=" + ret + "]");
6802                }
6803
6804                if (dataPath.exists()) {
6805                    pkg.applicationInfo.dataDir = dataPath.getPath();
6806                } else {
6807                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
6808                    pkg.applicationInfo.dataDir = null;
6809                }
6810            }
6811
6812            pkgSetting.uidError = uidError;
6813        }
6814
6815        final String path = scanFile.getPath();
6816        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
6817
6818        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
6819            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
6820
6821            // Some system apps still use directory structure for native libraries
6822            // in which case we might end up not detecting abi solely based on apk
6823            // structure. Try to detect abi based on directory structure.
6824            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
6825                    pkg.applicationInfo.primaryCpuAbi == null) {
6826                setBundledAppAbisAndRoots(pkg, pkgSetting);
6827                setNativeLibraryPaths(pkg);
6828            }
6829
6830        } else {
6831            if ((scanFlags & SCAN_MOVE) != 0) {
6832                // We haven't run dex-opt for this move (since we've moved the compiled output too)
6833                // but we already have this packages package info in the PackageSetting. We just
6834                // use that and derive the native library path based on the new codepath.
6835                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
6836                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
6837            }
6838
6839            // Set native library paths again. For moves, the path will be updated based on the
6840            // ABIs we've determined above. For non-moves, the path will be updated based on the
6841            // ABIs we determined during compilation, but the path will depend on the final
6842            // package path (after the rename away from the stage path).
6843            setNativeLibraryPaths(pkg);
6844        }
6845
6846        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
6847        final int[] userIds = sUserManager.getUserIds();
6848        synchronized (mInstallLock) {
6849            // Make sure all user data directories are ready to roll; we're okay
6850            // if they already exist
6851            if (!TextUtils.isEmpty(pkg.volumeUuid)) {
6852                for (int userId : userIds) {
6853                    if (userId != 0) {
6854                        mInstaller.createUserData(pkg.volumeUuid, pkg.packageName,
6855                                UserHandle.getUid(userId, pkg.applicationInfo.uid), userId,
6856                                pkg.applicationInfo.seinfo);
6857                    }
6858                }
6859            }
6860
6861            // Create a native library symlink only if we have native libraries
6862            // and if the native libraries are 32 bit libraries. We do not provide
6863            // this symlink for 64 bit libraries.
6864            if (pkg.applicationInfo.primaryCpuAbi != null &&
6865                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
6866                final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
6867                for (int userId : userIds) {
6868                    if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
6869                            nativeLibPath, userId) < 0) {
6870                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
6871                                "Failed linking native library dir (user=" + userId + ")");
6872                    }
6873                }
6874            }
6875        }
6876
6877        // This is a special case for the "system" package, where the ABI is
6878        // dictated by the zygote configuration (and init.rc). We should keep track
6879        // of this ABI so that we can deal with "normal" applications that run under
6880        // the same UID correctly.
6881        if (mPlatformPackage == pkg) {
6882            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
6883                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
6884        }
6885
6886        // If there's a mismatch between the abi-override in the package setting
6887        // and the abiOverride specified for the install. Warn about this because we
6888        // would've already compiled the app without taking the package setting into
6889        // account.
6890        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
6891            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
6892                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
6893                        " for package: " + pkg.packageName);
6894            }
6895        }
6896
6897        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6898        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6899        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
6900
6901        // Copy the derived override back to the parsed package, so that we can
6902        // update the package settings accordingly.
6903        pkg.cpuAbiOverride = cpuAbiOverride;
6904
6905        if (DEBUG_ABI_SELECTION) {
6906            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
6907                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
6908                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
6909        }
6910
6911        // Push the derived path down into PackageSettings so we know what to
6912        // clean up at uninstall time.
6913        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
6914
6915        if (DEBUG_ABI_SELECTION) {
6916            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
6917                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
6918                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
6919        }
6920
6921        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
6922            // We don't do this here during boot because we can do it all
6923            // at once after scanning all existing packages.
6924            //
6925            // We also do this *before* we perform dexopt on this package, so that
6926            // we can avoid redundant dexopts, and also to make sure we've got the
6927            // code and package path correct.
6928            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
6929                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
6930        }
6931
6932        if ((scanFlags & SCAN_NO_DEX) == 0) {
6933            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
6934                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */);
6935            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6936                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
6937            }
6938        }
6939        if (mFactoryTest && pkg.requestedPermissions.contains(
6940                android.Manifest.permission.FACTORY_TEST)) {
6941            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
6942        }
6943
6944        ArrayList<PackageParser.Package> clientLibPkgs = null;
6945
6946        // writer
6947        synchronized (mPackages) {
6948            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6949                // Only system apps can add new shared libraries.
6950                if (pkg.libraryNames != null) {
6951                    for (int i=0; i<pkg.libraryNames.size(); i++) {
6952                        String name = pkg.libraryNames.get(i);
6953                        boolean allowed = false;
6954                        if (pkg.isUpdatedSystemApp()) {
6955                            // New library entries can only be added through the
6956                            // system image.  This is important to get rid of a lot
6957                            // of nasty edge cases: for example if we allowed a non-
6958                            // system update of the app to add a library, then uninstalling
6959                            // the update would make the library go away, and assumptions
6960                            // we made such as through app install filtering would now
6961                            // have allowed apps on the device which aren't compatible
6962                            // with it.  Better to just have the restriction here, be
6963                            // conservative, and create many fewer cases that can negatively
6964                            // impact the user experience.
6965                            final PackageSetting sysPs = mSettings
6966                                    .getDisabledSystemPkgLPr(pkg.packageName);
6967                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
6968                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
6969                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
6970                                        allowed = true;
6971                                        allowed = true;
6972                                        break;
6973                                    }
6974                                }
6975                            }
6976                        } else {
6977                            allowed = true;
6978                        }
6979                        if (allowed) {
6980                            if (!mSharedLibraries.containsKey(name)) {
6981                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
6982                            } else if (!name.equals(pkg.packageName)) {
6983                                Slog.w(TAG, "Package " + pkg.packageName + " library "
6984                                        + name + " already exists; skipping");
6985                            }
6986                        } else {
6987                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
6988                                    + name + " that is not declared on system image; skipping");
6989                        }
6990                    }
6991                    if ((scanFlags&SCAN_BOOTING) == 0) {
6992                        // If we are not booting, we need to update any applications
6993                        // that are clients of our shared library.  If we are booting,
6994                        // this will all be done once the scan is complete.
6995                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
6996                    }
6997                }
6998            }
6999        }
7000
7001        // We also need to dexopt any apps that are dependent on this library.  Note that
7002        // if these fail, we should abort the install since installing the library will
7003        // result in some apps being broken.
7004        if (clientLibPkgs != null) {
7005            if ((scanFlags & SCAN_NO_DEX) == 0) {
7006                for (int i = 0; i < clientLibPkgs.size(); i++) {
7007                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
7008                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
7009                            null /* instruction sets */, forceDex,
7010                            (scanFlags & SCAN_DEFER_DEX) != 0, false);
7011                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7012                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
7013                                "scanPackageLI failed to dexopt clientLibPkgs");
7014                    }
7015                }
7016            }
7017        }
7018
7019        // Also need to kill any apps that are dependent on the library.
7020        if (clientLibPkgs != null) {
7021            for (int i=0; i<clientLibPkgs.size(); i++) {
7022                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7023                killApplication(clientPkg.applicationInfo.packageName,
7024                        clientPkg.applicationInfo.uid, "update lib");
7025            }
7026        }
7027
7028        // Make sure we're not adding any bogus keyset info
7029        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7030        ksms.assertScannedPackageValid(pkg);
7031
7032        // writer
7033        synchronized (mPackages) {
7034            // We don't expect installation to fail beyond this point
7035
7036            // Add the new setting to mSettings
7037            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7038            // Add the new setting to mPackages
7039            mPackages.put(pkg.applicationInfo.packageName, pkg);
7040            // Make sure we don't accidentally delete its data.
7041            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7042            while (iter.hasNext()) {
7043                PackageCleanItem item = iter.next();
7044                if (pkgName.equals(item.packageName)) {
7045                    iter.remove();
7046                }
7047            }
7048
7049            // Take care of first install / last update times.
7050            if (currentTime != 0) {
7051                if (pkgSetting.firstInstallTime == 0) {
7052                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7053                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7054                    pkgSetting.lastUpdateTime = currentTime;
7055                }
7056            } else if (pkgSetting.firstInstallTime == 0) {
7057                // We need *something*.  Take time time stamp of the file.
7058                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7059            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7060                if (scanFileTime != pkgSetting.timeStamp) {
7061                    // A package on the system image has changed; consider this
7062                    // to be an update.
7063                    pkgSetting.lastUpdateTime = scanFileTime;
7064                }
7065            }
7066
7067            // Add the package's KeySets to the global KeySetManagerService
7068            ksms.addScannedPackageLPw(pkg);
7069
7070            int N = pkg.providers.size();
7071            StringBuilder r = null;
7072            int i;
7073            for (i=0; i<N; i++) {
7074                PackageParser.Provider p = pkg.providers.get(i);
7075                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7076                        p.info.processName, pkg.applicationInfo.uid);
7077                mProviders.addProvider(p);
7078                p.syncable = p.info.isSyncable;
7079                if (p.info.authority != null) {
7080                    String names[] = p.info.authority.split(";");
7081                    p.info.authority = null;
7082                    for (int j = 0; j < names.length; j++) {
7083                        if (j == 1 && p.syncable) {
7084                            // We only want the first authority for a provider to possibly be
7085                            // syncable, so if we already added this provider using a different
7086                            // authority clear the syncable flag. We copy the provider before
7087                            // changing it because the mProviders object contains a reference
7088                            // to a provider that we don't want to change.
7089                            // Only do this for the second authority since the resulting provider
7090                            // object can be the same for all future authorities for this provider.
7091                            p = new PackageParser.Provider(p);
7092                            p.syncable = false;
7093                        }
7094                        if (!mProvidersByAuthority.containsKey(names[j])) {
7095                            mProvidersByAuthority.put(names[j], p);
7096                            if (p.info.authority == null) {
7097                                p.info.authority = names[j];
7098                            } else {
7099                                p.info.authority = p.info.authority + ";" + names[j];
7100                            }
7101                            if (DEBUG_PACKAGE_SCANNING) {
7102                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7103                                    Log.d(TAG, "Registered content provider: " + names[j]
7104                                            + ", className = " + p.info.name + ", isSyncable = "
7105                                            + p.info.isSyncable);
7106                            }
7107                        } else {
7108                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7109                            Slog.w(TAG, "Skipping provider name " + names[j] +
7110                                    " (in package " + pkg.applicationInfo.packageName +
7111                                    "): name already used by "
7112                                    + ((other != null && other.getComponentName() != null)
7113                                            ? other.getComponentName().getPackageName() : "?"));
7114                        }
7115                    }
7116                }
7117                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7118                    if (r == null) {
7119                        r = new StringBuilder(256);
7120                    } else {
7121                        r.append(' ');
7122                    }
7123                    r.append(p.info.name);
7124                }
7125            }
7126            if (r != null) {
7127                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7128            }
7129
7130            N = pkg.services.size();
7131            r = null;
7132            for (i=0; i<N; i++) {
7133                PackageParser.Service s = pkg.services.get(i);
7134                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7135                        s.info.processName, pkg.applicationInfo.uid);
7136                mServices.addService(s);
7137                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7138                    if (r == null) {
7139                        r = new StringBuilder(256);
7140                    } else {
7141                        r.append(' ');
7142                    }
7143                    r.append(s.info.name);
7144                }
7145            }
7146            if (r != null) {
7147                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7148            }
7149
7150            N = pkg.receivers.size();
7151            r = null;
7152            for (i=0; i<N; i++) {
7153                PackageParser.Activity a = pkg.receivers.get(i);
7154                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7155                        a.info.processName, pkg.applicationInfo.uid);
7156                mReceivers.addActivity(a, "receiver");
7157                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7158                    if (r == null) {
7159                        r = new StringBuilder(256);
7160                    } else {
7161                        r.append(' ');
7162                    }
7163                    r.append(a.info.name);
7164                }
7165            }
7166            if (r != null) {
7167                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7168            }
7169
7170            N = pkg.activities.size();
7171            r = null;
7172            for (i=0; i<N; i++) {
7173                PackageParser.Activity a = pkg.activities.get(i);
7174                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7175                        a.info.processName, pkg.applicationInfo.uid);
7176                mActivities.addActivity(a, "activity");
7177                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7178                    if (r == null) {
7179                        r = new StringBuilder(256);
7180                    } else {
7181                        r.append(' ');
7182                    }
7183                    r.append(a.info.name);
7184                }
7185            }
7186            if (r != null) {
7187                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7188            }
7189
7190            N = pkg.permissionGroups.size();
7191            r = null;
7192            for (i=0; i<N; i++) {
7193                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7194                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7195                if (cur == null) {
7196                    mPermissionGroups.put(pg.info.name, pg);
7197                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7198                        if (r == null) {
7199                            r = new StringBuilder(256);
7200                        } else {
7201                            r.append(' ');
7202                        }
7203                        r.append(pg.info.name);
7204                    }
7205                } else {
7206                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7207                            + pg.info.packageName + " ignored: original from "
7208                            + cur.info.packageName);
7209                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7210                        if (r == null) {
7211                            r = new StringBuilder(256);
7212                        } else {
7213                            r.append(' ');
7214                        }
7215                        r.append("DUP:");
7216                        r.append(pg.info.name);
7217                    }
7218                }
7219            }
7220            if (r != null) {
7221                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7222            }
7223
7224            N = pkg.permissions.size();
7225            r = null;
7226            for (i=0; i<N; i++) {
7227                PackageParser.Permission p = pkg.permissions.get(i);
7228
7229                // Now that permission groups have a special meaning, we ignore permission
7230                // groups for legacy apps to prevent unexpected behavior. In particular,
7231                // permissions for one app being granted to someone just becuase they happen
7232                // to be in a group defined by another app (before this had no implications).
7233                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7234                    p.group = mPermissionGroups.get(p.info.group);
7235                    // Warn for a permission in an unknown group.
7236                    if (p.info.group != null && p.group == null) {
7237                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7238                                + p.info.packageName + " in an unknown group " + p.info.group);
7239                    }
7240                }
7241
7242                ArrayMap<String, BasePermission> permissionMap =
7243                        p.tree ? mSettings.mPermissionTrees
7244                                : mSettings.mPermissions;
7245                BasePermission bp = permissionMap.get(p.info.name);
7246
7247                // Allow system apps to redefine non-system permissions
7248                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7249                    final boolean currentOwnerIsSystem = (bp.perm != null
7250                            && isSystemApp(bp.perm.owner));
7251                    if (isSystemApp(p.owner)) {
7252                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7253                            // It's a built-in permission and no owner, take ownership now
7254                            bp.packageSetting = pkgSetting;
7255                            bp.perm = p;
7256                            bp.uid = pkg.applicationInfo.uid;
7257                            bp.sourcePackage = p.info.packageName;
7258                        } else if (!currentOwnerIsSystem) {
7259                            String msg = "New decl " + p.owner + " of permission  "
7260                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7261                            reportSettingsProblem(Log.WARN, msg);
7262                            bp = null;
7263                        }
7264                    }
7265                }
7266
7267                if (bp == null) {
7268                    bp = new BasePermission(p.info.name, p.info.packageName,
7269                            BasePermission.TYPE_NORMAL);
7270                    permissionMap.put(p.info.name, bp);
7271                }
7272
7273                if (bp.perm == null) {
7274                    if (bp.sourcePackage == null
7275                            || bp.sourcePackage.equals(p.info.packageName)) {
7276                        BasePermission tree = findPermissionTreeLP(p.info.name);
7277                        if (tree == null
7278                                || tree.sourcePackage.equals(p.info.packageName)) {
7279                            bp.packageSetting = pkgSetting;
7280                            bp.perm = p;
7281                            bp.uid = pkg.applicationInfo.uid;
7282                            bp.sourcePackage = p.info.packageName;
7283                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7284                                if (r == null) {
7285                                    r = new StringBuilder(256);
7286                                } else {
7287                                    r.append(' ');
7288                                }
7289                                r.append(p.info.name);
7290                            }
7291                        } else {
7292                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7293                                    + p.info.packageName + " ignored: base tree "
7294                                    + tree.name + " is from package "
7295                                    + tree.sourcePackage);
7296                        }
7297                    } else {
7298                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7299                                + p.info.packageName + " ignored: original from "
7300                                + bp.sourcePackage);
7301                    }
7302                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7303                    if (r == null) {
7304                        r = new StringBuilder(256);
7305                    } else {
7306                        r.append(' ');
7307                    }
7308                    r.append("DUP:");
7309                    r.append(p.info.name);
7310                }
7311                if (bp.perm == p) {
7312                    bp.protectionLevel = p.info.protectionLevel;
7313                }
7314            }
7315
7316            if (r != null) {
7317                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7318            }
7319
7320            N = pkg.instrumentation.size();
7321            r = null;
7322            for (i=0; i<N; i++) {
7323                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7324                a.info.packageName = pkg.applicationInfo.packageName;
7325                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7326                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7327                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7328                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7329                a.info.dataDir = pkg.applicationInfo.dataDir;
7330
7331                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7332                // need other information about the application, like the ABI and what not ?
7333                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7334                mInstrumentation.put(a.getComponentName(), a);
7335                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7336                    if (r == null) {
7337                        r = new StringBuilder(256);
7338                    } else {
7339                        r.append(' ');
7340                    }
7341                    r.append(a.info.name);
7342                }
7343            }
7344            if (r != null) {
7345                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7346            }
7347
7348            if (pkg.protectedBroadcasts != null) {
7349                N = pkg.protectedBroadcasts.size();
7350                for (i=0; i<N; i++) {
7351                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7352                }
7353            }
7354
7355            pkgSetting.setTimeStamp(scanFileTime);
7356
7357            // Create idmap files for pairs of (packages, overlay packages).
7358            // Note: "android", ie framework-res.apk, is handled by native layers.
7359            if (pkg.mOverlayTarget != null) {
7360                // This is an overlay package.
7361                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7362                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7363                        mOverlays.put(pkg.mOverlayTarget,
7364                                new ArrayMap<String, PackageParser.Package>());
7365                    }
7366                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7367                    map.put(pkg.packageName, pkg);
7368                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7369                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7370                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7371                                "scanPackageLI failed to createIdmap");
7372                    }
7373                }
7374            } else if (mOverlays.containsKey(pkg.packageName) &&
7375                    !pkg.packageName.equals("android")) {
7376                // This is a regular package, with one or more known overlay packages.
7377                createIdmapsForPackageLI(pkg);
7378            }
7379        }
7380
7381        return pkg;
7382    }
7383
7384    /**
7385     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7386     * is derived purely on the basis of the contents of {@code scanFile} and
7387     * {@code cpuAbiOverride}.
7388     *
7389     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7390     */
7391    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7392                                 String cpuAbiOverride, boolean extractLibs)
7393            throws PackageManagerException {
7394        // TODO: We can probably be smarter about this stuff. For installed apps,
7395        // we can calculate this information at install time once and for all. For
7396        // system apps, we can probably assume that this information doesn't change
7397        // after the first boot scan. As things stand, we do lots of unnecessary work.
7398
7399        // Give ourselves some initial paths; we'll come back for another
7400        // pass once we've determined ABI below.
7401        setNativeLibraryPaths(pkg);
7402
7403        // We would never need to extract libs for forward-locked and external packages,
7404        // since the container service will do it for us. We shouldn't attempt to
7405        // extract libs from system app when it was not updated.
7406        if (pkg.isForwardLocked() || isExternal(pkg) ||
7407            (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) {
7408            extractLibs = false;
7409        }
7410
7411        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7412        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7413
7414        NativeLibraryHelper.Handle handle = null;
7415        try {
7416            handle = NativeLibraryHelper.Handle.create(scanFile);
7417            // TODO(multiArch): This can be null for apps that didn't go through the
7418            // usual installation process. We can calculate it again, like we
7419            // do during install time.
7420            //
7421            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7422            // unnecessary.
7423            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7424
7425            // Null out the abis so that they can be recalculated.
7426            pkg.applicationInfo.primaryCpuAbi = null;
7427            pkg.applicationInfo.secondaryCpuAbi = null;
7428            if (isMultiArch(pkg.applicationInfo)) {
7429                // Warn if we've set an abiOverride for multi-lib packages..
7430                // By definition, we need to copy both 32 and 64 bit libraries for
7431                // such packages.
7432                if (pkg.cpuAbiOverride != null
7433                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7434                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7435                }
7436
7437                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7438                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7439                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7440                    if (extractLibs) {
7441                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7442                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7443                                useIsaSpecificSubdirs);
7444                    } else {
7445                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7446                    }
7447                }
7448
7449                maybeThrowExceptionForMultiArchCopy(
7450                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7451
7452                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7453                    if (extractLibs) {
7454                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7455                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7456                                useIsaSpecificSubdirs);
7457                    } else {
7458                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7459                    }
7460                }
7461
7462                maybeThrowExceptionForMultiArchCopy(
7463                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7464
7465                if (abi64 >= 0) {
7466                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7467                }
7468
7469                if (abi32 >= 0) {
7470                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7471                    if (abi64 >= 0) {
7472                        pkg.applicationInfo.secondaryCpuAbi = abi;
7473                    } else {
7474                        pkg.applicationInfo.primaryCpuAbi = abi;
7475                    }
7476                }
7477            } else {
7478                String[] abiList = (cpuAbiOverride != null) ?
7479                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7480
7481                // Enable gross and lame hacks for apps that are built with old
7482                // SDK tools. We must scan their APKs for renderscript bitcode and
7483                // not launch them if it's present. Don't bother checking on devices
7484                // that don't have 64 bit support.
7485                boolean needsRenderScriptOverride = false;
7486                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7487                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7488                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7489                    needsRenderScriptOverride = true;
7490                }
7491
7492                final int copyRet;
7493                if (extractLibs) {
7494                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7495                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7496                } else {
7497                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7498                }
7499
7500                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7501                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7502                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7503                }
7504
7505                if (copyRet >= 0) {
7506                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7507                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7508                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7509                } else if (needsRenderScriptOverride) {
7510                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7511                }
7512            }
7513        } catch (IOException ioe) {
7514            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7515        } finally {
7516            IoUtils.closeQuietly(handle);
7517        }
7518
7519        // Now that we've calculated the ABIs and determined if it's an internal app,
7520        // we will go ahead and populate the nativeLibraryPath.
7521        setNativeLibraryPaths(pkg);
7522    }
7523
7524    /**
7525     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7526     * i.e, so that all packages can be run inside a single process if required.
7527     *
7528     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7529     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7530     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7531     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7532     * updating a package that belongs to a shared user.
7533     *
7534     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7535     * adds unnecessary complexity.
7536     */
7537    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7538            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
7539        String requiredInstructionSet = null;
7540        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7541            requiredInstructionSet = VMRuntime.getInstructionSet(
7542                     scannedPackage.applicationInfo.primaryCpuAbi);
7543        }
7544
7545        PackageSetting requirer = null;
7546        for (PackageSetting ps : packagesForUser) {
7547            // If packagesForUser contains scannedPackage, we skip it. This will happen
7548            // when scannedPackage is an update of an existing package. Without this check,
7549            // we will never be able to change the ABI of any package belonging to a shared
7550            // user, even if it's compatible with other packages.
7551            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7552                if (ps.primaryCpuAbiString == null) {
7553                    continue;
7554                }
7555
7556                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7557                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7558                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7559                    // this but there's not much we can do.
7560                    String errorMessage = "Instruction set mismatch, "
7561                            + ((requirer == null) ? "[caller]" : requirer)
7562                            + " requires " + requiredInstructionSet + " whereas " + ps
7563                            + " requires " + instructionSet;
7564                    Slog.w(TAG, errorMessage);
7565                }
7566
7567                if (requiredInstructionSet == null) {
7568                    requiredInstructionSet = instructionSet;
7569                    requirer = ps;
7570                }
7571            }
7572        }
7573
7574        if (requiredInstructionSet != null) {
7575            String adjustedAbi;
7576            if (requirer != null) {
7577                // requirer != null implies that either scannedPackage was null or that scannedPackage
7578                // did not require an ABI, in which case we have to adjust scannedPackage to match
7579                // the ABI of the set (which is the same as requirer's ABI)
7580                adjustedAbi = requirer.primaryCpuAbiString;
7581                if (scannedPackage != null) {
7582                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7583                }
7584            } else {
7585                // requirer == null implies that we're updating all ABIs in the set to
7586                // match scannedPackage.
7587                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7588            }
7589
7590            for (PackageSetting ps : packagesForUser) {
7591                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7592                    if (ps.primaryCpuAbiString != null) {
7593                        continue;
7594                    }
7595
7596                    ps.primaryCpuAbiString = adjustedAbi;
7597                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7598                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7599                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7600
7601                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
7602                                null /* instruction sets */, forceDexOpt, deferDexOpt, true);
7603                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7604                            ps.primaryCpuAbiString = null;
7605                            ps.pkg.applicationInfo.primaryCpuAbi = null;
7606                            return;
7607                        } else {
7608                            mInstaller.rmdex(ps.codePathString,
7609                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
7610                        }
7611                    }
7612                }
7613            }
7614        }
7615    }
7616
7617    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7618        synchronized (mPackages) {
7619            mResolverReplaced = true;
7620            // Set up information for custom user intent resolution activity.
7621            mResolveActivity.applicationInfo = pkg.applicationInfo;
7622            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7623            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7624            mResolveActivity.processName = pkg.applicationInfo.packageName;
7625            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7626            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7627                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7628            mResolveActivity.theme = 0;
7629            mResolveActivity.exported = true;
7630            mResolveActivity.enabled = true;
7631            mResolveInfo.activityInfo = mResolveActivity;
7632            mResolveInfo.priority = 0;
7633            mResolveInfo.preferredOrder = 0;
7634            mResolveInfo.match = 0;
7635            mResolveComponentName = mCustomResolverComponentName;
7636            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7637                    mResolveComponentName);
7638        }
7639    }
7640
7641    private static String calculateBundledApkRoot(final String codePathString) {
7642        final File codePath = new File(codePathString);
7643        final File codeRoot;
7644        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7645            codeRoot = Environment.getRootDirectory();
7646        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7647            codeRoot = Environment.getOemDirectory();
7648        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7649            codeRoot = Environment.getVendorDirectory();
7650        } else {
7651            // Unrecognized code path; take its top real segment as the apk root:
7652            // e.g. /something/app/blah.apk => /something
7653            try {
7654                File f = codePath.getCanonicalFile();
7655                File parent = f.getParentFile();    // non-null because codePath is a file
7656                File tmp;
7657                while ((tmp = parent.getParentFile()) != null) {
7658                    f = parent;
7659                    parent = tmp;
7660                }
7661                codeRoot = f;
7662                Slog.w(TAG, "Unrecognized code path "
7663                        + codePath + " - using " + codeRoot);
7664            } catch (IOException e) {
7665                // Can't canonicalize the code path -- shenanigans?
7666                Slog.w(TAG, "Can't canonicalize code path " + codePath);
7667                return Environment.getRootDirectory().getPath();
7668            }
7669        }
7670        return codeRoot.getPath();
7671    }
7672
7673    /**
7674     * Derive and set the location of native libraries for the given package,
7675     * which varies depending on where and how the package was installed.
7676     */
7677    private void setNativeLibraryPaths(PackageParser.Package pkg) {
7678        final ApplicationInfo info = pkg.applicationInfo;
7679        final String codePath = pkg.codePath;
7680        final File codeFile = new File(codePath);
7681        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7682        final boolean asecApp = info.isForwardLocked() || isExternal(info);
7683
7684        info.nativeLibraryRootDir = null;
7685        info.nativeLibraryRootRequiresIsa = false;
7686        info.nativeLibraryDir = null;
7687        info.secondaryNativeLibraryDir = null;
7688
7689        if (isApkFile(codeFile)) {
7690            // Monolithic install
7691            if (bundledApp) {
7692                // If "/system/lib64/apkname" exists, assume that is the per-package
7693                // native library directory to use; otherwise use "/system/lib/apkname".
7694                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
7695                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
7696                        getPrimaryInstructionSet(info));
7697
7698                // This is a bundled system app so choose the path based on the ABI.
7699                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
7700                // is just the default path.
7701                final String apkName = deriveCodePathName(codePath);
7702                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
7703                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
7704                        apkName).getAbsolutePath();
7705
7706                if (info.secondaryCpuAbi != null) {
7707                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7708                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7709                            secondaryLibDir, apkName).getAbsolutePath();
7710                }
7711            } else if (asecApp) {
7712                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
7713                        .getAbsolutePath();
7714            } else {
7715                final String apkName = deriveCodePathName(codePath);
7716                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
7717                        .getAbsolutePath();
7718            }
7719
7720            info.nativeLibraryRootRequiresIsa = false;
7721            info.nativeLibraryDir = info.nativeLibraryRootDir;
7722        } else {
7723            // Cluster install
7724            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7725            info.nativeLibraryRootRequiresIsa = true;
7726
7727            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7728                    getPrimaryInstructionSet(info)).getAbsolutePath();
7729
7730            if (info.secondaryCpuAbi != null) {
7731                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7732                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7733            }
7734        }
7735    }
7736
7737    /**
7738     * Calculate the abis and roots for a bundled app. These can uniquely
7739     * be determined from the contents of the system partition, i.e whether
7740     * it contains 64 or 32 bit shared libraries etc. We do not validate any
7741     * of this information, and instead assume that the system was built
7742     * sensibly.
7743     */
7744    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
7745                                           PackageSetting pkgSetting) {
7746        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
7747
7748        // If "/system/lib64/apkname" exists, assume that is the per-package
7749        // native library directory to use; otherwise use "/system/lib/apkname".
7750        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
7751        setBundledAppAbi(pkg, apkRoot, apkName);
7752        // pkgSetting might be null during rescan following uninstall of updates
7753        // to a bundled app, so accommodate that possibility.  The settings in
7754        // that case will be established later from the parsed package.
7755        //
7756        // If the settings aren't null, sync them up with what we've just derived.
7757        // note that apkRoot isn't stored in the package settings.
7758        if (pkgSetting != null) {
7759            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7760            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7761        }
7762    }
7763
7764    /**
7765     * Deduces the ABI of a bundled app and sets the relevant fields on the
7766     * parsed pkg object.
7767     *
7768     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
7769     *        under which system libraries are installed.
7770     * @param apkName the name of the installed package.
7771     */
7772    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7773        final File codeFile = new File(pkg.codePath);
7774
7775        final boolean has64BitLibs;
7776        final boolean has32BitLibs;
7777        if (isApkFile(codeFile)) {
7778            // Monolithic install
7779            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7780            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7781        } else {
7782            // Cluster install
7783            final File rootDir = new File(codeFile, LIB_DIR_NAME);
7784            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7785                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7786                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7787                has64BitLibs = (new File(rootDir, isa)).exists();
7788            } else {
7789                has64BitLibs = false;
7790            }
7791            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7792                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7793                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7794                has32BitLibs = (new File(rootDir, isa)).exists();
7795            } else {
7796                has32BitLibs = false;
7797            }
7798        }
7799
7800        if (has64BitLibs && !has32BitLibs) {
7801            // The package has 64 bit libs, but not 32 bit libs. Its primary
7802            // ABI should be 64 bit. We can safely assume here that the bundled
7803            // native libraries correspond to the most preferred ABI in the list.
7804
7805            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7806            pkg.applicationInfo.secondaryCpuAbi = null;
7807        } else if (has32BitLibs && !has64BitLibs) {
7808            // The package has 32 bit libs but not 64 bit libs. Its primary
7809            // ABI should be 32 bit.
7810
7811            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7812            pkg.applicationInfo.secondaryCpuAbi = null;
7813        } else if (has32BitLibs && has64BitLibs) {
7814            // The application has both 64 and 32 bit bundled libraries. We check
7815            // here that the app declares multiArch support, and warn if it doesn't.
7816            //
7817            // We will be lenient here and record both ABIs. The primary will be the
7818            // ABI that's higher on the list, i.e, a device that's configured to prefer
7819            // 64 bit apps will see a 64 bit primary ABI,
7820
7821            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
7822                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
7823            }
7824
7825            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
7826                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7827                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7828            } else {
7829                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7830                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7831            }
7832        } else {
7833            pkg.applicationInfo.primaryCpuAbi = null;
7834            pkg.applicationInfo.secondaryCpuAbi = null;
7835        }
7836    }
7837
7838    private void killApplication(String pkgName, int appId, String reason) {
7839        // Request the ActivityManager to kill the process(only for existing packages)
7840        // so that we do not end up in a confused state while the user is still using the older
7841        // version of the application while the new one gets installed.
7842        IActivityManager am = ActivityManagerNative.getDefault();
7843        if (am != null) {
7844            try {
7845                am.killApplicationWithAppId(pkgName, appId, reason);
7846            } catch (RemoteException e) {
7847            }
7848        }
7849    }
7850
7851    void removePackageLI(PackageSetting ps, boolean chatty) {
7852        if (DEBUG_INSTALL) {
7853            if (chatty)
7854                Log.d(TAG, "Removing package " + ps.name);
7855        }
7856
7857        // writer
7858        synchronized (mPackages) {
7859            mPackages.remove(ps.name);
7860            final PackageParser.Package pkg = ps.pkg;
7861            if (pkg != null) {
7862                cleanPackageDataStructuresLILPw(pkg, chatty);
7863            }
7864        }
7865    }
7866
7867    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
7868        if (DEBUG_INSTALL) {
7869            if (chatty)
7870                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
7871        }
7872
7873        // writer
7874        synchronized (mPackages) {
7875            mPackages.remove(pkg.applicationInfo.packageName);
7876            cleanPackageDataStructuresLILPw(pkg, chatty);
7877        }
7878    }
7879
7880    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
7881        int N = pkg.providers.size();
7882        StringBuilder r = null;
7883        int i;
7884        for (i=0; i<N; i++) {
7885            PackageParser.Provider p = pkg.providers.get(i);
7886            mProviders.removeProvider(p);
7887            if (p.info.authority == null) {
7888
7889                /* There was another ContentProvider with this authority when
7890                 * this app was installed so this authority is null,
7891                 * Ignore it as we don't have to unregister the provider.
7892                 */
7893                continue;
7894            }
7895            String names[] = p.info.authority.split(";");
7896            for (int j = 0; j < names.length; j++) {
7897                if (mProvidersByAuthority.get(names[j]) == p) {
7898                    mProvidersByAuthority.remove(names[j]);
7899                    if (DEBUG_REMOVE) {
7900                        if (chatty)
7901                            Log.d(TAG, "Unregistered content provider: " + names[j]
7902                                    + ", className = " + p.info.name + ", isSyncable = "
7903                                    + p.info.isSyncable);
7904                    }
7905                }
7906            }
7907            if (DEBUG_REMOVE && chatty) {
7908                if (r == null) {
7909                    r = new StringBuilder(256);
7910                } else {
7911                    r.append(' ');
7912                }
7913                r.append(p.info.name);
7914            }
7915        }
7916        if (r != null) {
7917            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
7918        }
7919
7920        N = pkg.services.size();
7921        r = null;
7922        for (i=0; i<N; i++) {
7923            PackageParser.Service s = pkg.services.get(i);
7924            mServices.removeService(s);
7925            if (chatty) {
7926                if (r == null) {
7927                    r = new StringBuilder(256);
7928                } else {
7929                    r.append(' ');
7930                }
7931                r.append(s.info.name);
7932            }
7933        }
7934        if (r != null) {
7935            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
7936        }
7937
7938        N = pkg.receivers.size();
7939        r = null;
7940        for (i=0; i<N; i++) {
7941            PackageParser.Activity a = pkg.receivers.get(i);
7942            mReceivers.removeActivity(a, "receiver");
7943            if (DEBUG_REMOVE && chatty) {
7944                if (r == null) {
7945                    r = new StringBuilder(256);
7946                } else {
7947                    r.append(' ');
7948                }
7949                r.append(a.info.name);
7950            }
7951        }
7952        if (r != null) {
7953            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
7954        }
7955
7956        N = pkg.activities.size();
7957        r = null;
7958        for (i=0; i<N; i++) {
7959            PackageParser.Activity a = pkg.activities.get(i);
7960            mActivities.removeActivity(a, "activity");
7961            if (DEBUG_REMOVE && chatty) {
7962                if (r == null) {
7963                    r = new StringBuilder(256);
7964                } else {
7965                    r.append(' ');
7966                }
7967                r.append(a.info.name);
7968            }
7969        }
7970        if (r != null) {
7971            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
7972        }
7973
7974        N = pkg.permissions.size();
7975        r = null;
7976        for (i=0; i<N; i++) {
7977            PackageParser.Permission p = pkg.permissions.get(i);
7978            BasePermission bp = mSettings.mPermissions.get(p.info.name);
7979            if (bp == null) {
7980                bp = mSettings.mPermissionTrees.get(p.info.name);
7981            }
7982            if (bp != null && bp.perm == p) {
7983                bp.perm = null;
7984                if (DEBUG_REMOVE && chatty) {
7985                    if (r == null) {
7986                        r = new StringBuilder(256);
7987                    } else {
7988                        r.append(' ');
7989                    }
7990                    r.append(p.info.name);
7991                }
7992            }
7993            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7994                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
7995                if (appOpPerms != null) {
7996                    appOpPerms.remove(pkg.packageName);
7997                }
7998            }
7999        }
8000        if (r != null) {
8001            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8002        }
8003
8004        N = pkg.requestedPermissions.size();
8005        r = null;
8006        for (i=0; i<N; i++) {
8007            String perm = pkg.requestedPermissions.get(i);
8008            BasePermission bp = mSettings.mPermissions.get(perm);
8009            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8010                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
8011                if (appOpPerms != null) {
8012                    appOpPerms.remove(pkg.packageName);
8013                    if (appOpPerms.isEmpty()) {
8014                        mAppOpPermissionPackages.remove(perm);
8015                    }
8016                }
8017            }
8018        }
8019        if (r != null) {
8020            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8021        }
8022
8023        N = pkg.instrumentation.size();
8024        r = null;
8025        for (i=0; i<N; i++) {
8026            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8027            mInstrumentation.remove(a.getComponentName());
8028            if (DEBUG_REMOVE && chatty) {
8029                if (r == null) {
8030                    r = new StringBuilder(256);
8031                } else {
8032                    r.append(' ');
8033                }
8034                r.append(a.info.name);
8035            }
8036        }
8037        if (r != null) {
8038            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8039        }
8040
8041        r = null;
8042        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8043            // Only system apps can hold shared libraries.
8044            if (pkg.libraryNames != null) {
8045                for (i=0; i<pkg.libraryNames.size(); i++) {
8046                    String name = pkg.libraryNames.get(i);
8047                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8048                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8049                        mSharedLibraries.remove(name);
8050                        if (DEBUG_REMOVE && chatty) {
8051                            if (r == null) {
8052                                r = new StringBuilder(256);
8053                            } else {
8054                                r.append(' ');
8055                            }
8056                            r.append(name);
8057                        }
8058                    }
8059                }
8060            }
8061        }
8062        if (r != null) {
8063            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8064        }
8065    }
8066
8067    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8068        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8069            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8070                return true;
8071            }
8072        }
8073        return false;
8074    }
8075
8076    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8077    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8078    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8079
8080    private void updatePermissionsLPw(String changingPkg,
8081            PackageParser.Package pkgInfo, int flags) {
8082        // Make sure there are no dangling permission trees.
8083        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8084        while (it.hasNext()) {
8085            final BasePermission bp = it.next();
8086            if (bp.packageSetting == null) {
8087                // We may not yet have parsed the package, so just see if
8088                // we still know about its settings.
8089                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8090            }
8091            if (bp.packageSetting == null) {
8092                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8093                        + " from package " + bp.sourcePackage);
8094                it.remove();
8095            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8096                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8097                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8098                            + " from package " + bp.sourcePackage);
8099                    flags |= UPDATE_PERMISSIONS_ALL;
8100                    it.remove();
8101                }
8102            }
8103        }
8104
8105        // Make sure all dynamic permissions have been assigned to a package,
8106        // and make sure there are no dangling permissions.
8107        it = mSettings.mPermissions.values().iterator();
8108        while (it.hasNext()) {
8109            final BasePermission bp = it.next();
8110            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8111                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8112                        + bp.name + " pkg=" + bp.sourcePackage
8113                        + " info=" + bp.pendingInfo);
8114                if (bp.packageSetting == null && bp.pendingInfo != null) {
8115                    final BasePermission tree = findPermissionTreeLP(bp.name);
8116                    if (tree != null && tree.perm != null) {
8117                        bp.packageSetting = tree.packageSetting;
8118                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8119                                new PermissionInfo(bp.pendingInfo));
8120                        bp.perm.info.packageName = tree.perm.info.packageName;
8121                        bp.perm.info.name = bp.name;
8122                        bp.uid = tree.uid;
8123                    }
8124                }
8125            }
8126            if (bp.packageSetting == null) {
8127                // We may not yet have parsed the package, so just see if
8128                // we still know about its settings.
8129                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8130            }
8131            if (bp.packageSetting == null) {
8132                Slog.w(TAG, "Removing dangling permission: " + bp.name
8133                        + " from package " + bp.sourcePackage);
8134                it.remove();
8135            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8136                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8137                    Slog.i(TAG, "Removing old permission: " + bp.name
8138                            + " from package " + bp.sourcePackage);
8139                    flags |= UPDATE_PERMISSIONS_ALL;
8140                    it.remove();
8141                }
8142            }
8143        }
8144
8145        // Now update the permissions for all packages, in particular
8146        // replace the granted permissions of the system packages.
8147        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8148            for (PackageParser.Package pkg : mPackages.values()) {
8149                if (pkg != pkgInfo) {
8150                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
8151                            changingPkg);
8152                }
8153            }
8154        }
8155
8156        if (pkgInfo != null) {
8157            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
8158        }
8159    }
8160
8161    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8162            String packageOfInterest) {
8163        // IMPORTANT: There are two types of permissions: install and runtime.
8164        // Install time permissions are granted when the app is installed to
8165        // all device users and users added in the future. Runtime permissions
8166        // are granted at runtime explicitly to specific users. Normal and signature
8167        // protected permissions are install time permissions. Dangerous permissions
8168        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8169        // otherwise they are runtime permissions. This function does not manage
8170        // runtime permissions except for the case an app targeting Lollipop MR1
8171        // being upgraded to target a newer SDK, in which case dangerous permissions
8172        // are transformed from install time to runtime ones.
8173
8174        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8175        if (ps == null) {
8176            return;
8177        }
8178
8179        PermissionsState permissionsState = ps.getPermissionsState();
8180        PermissionsState origPermissions = permissionsState;
8181
8182        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8183
8184        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8185
8186        boolean changedInstallPermission = false;
8187
8188        if (replace) {
8189            ps.installPermissionsFixed = false;
8190            if (!ps.isSharedUser()) {
8191                origPermissions = new PermissionsState(permissionsState);
8192                permissionsState.reset();
8193            }
8194        }
8195
8196        permissionsState.setGlobalGids(mGlobalGids);
8197
8198        final int N = pkg.requestedPermissions.size();
8199        for (int i=0; i<N; i++) {
8200            final String name = pkg.requestedPermissions.get(i);
8201            final BasePermission bp = mSettings.mPermissions.get(name);
8202
8203            if (DEBUG_INSTALL) {
8204                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8205            }
8206
8207            if (bp == null || bp.packageSetting == null) {
8208                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8209                    Slog.w(TAG, "Unknown permission " + name
8210                            + " in package " + pkg.packageName);
8211                }
8212                continue;
8213            }
8214
8215            final String perm = bp.name;
8216            boolean allowedSig = false;
8217            int grant = GRANT_DENIED;
8218
8219            // Keep track of app op permissions.
8220            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8221                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8222                if (pkgs == null) {
8223                    pkgs = new ArraySet<>();
8224                    mAppOpPermissionPackages.put(bp.name, pkgs);
8225                }
8226                pkgs.add(pkg.packageName);
8227            }
8228
8229            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8230            switch (level) {
8231                case PermissionInfo.PROTECTION_NORMAL: {
8232                    // For all apps normal permissions are install time ones.
8233                    grant = GRANT_INSTALL;
8234                } break;
8235
8236                case PermissionInfo.PROTECTION_DANGEROUS: {
8237                    if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
8238                        // For legacy apps dangerous permissions are install time ones.
8239                        grant = GRANT_INSTALL_LEGACY;
8240                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8241                        // For legacy apps that became modern, install becomes runtime.
8242                        grant = GRANT_UPGRADE;
8243                    } else {
8244                        // For modern apps keep runtime permissions unchanged.
8245                        grant = GRANT_RUNTIME;
8246                    }
8247                } break;
8248
8249                case PermissionInfo.PROTECTION_SIGNATURE: {
8250                    // For all apps signature permissions are install time ones.
8251                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8252                    if (allowedSig) {
8253                        grant = GRANT_INSTALL;
8254                    }
8255                } break;
8256            }
8257
8258            if (DEBUG_INSTALL) {
8259                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8260            }
8261
8262            if (grant != GRANT_DENIED) {
8263                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8264                    // If this is an existing, non-system package, then
8265                    // we can't add any new permissions to it.
8266                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8267                        // Except...  if this is a permission that was added
8268                        // to the platform (note: need to only do this when
8269                        // updating the platform).
8270                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8271                            grant = GRANT_DENIED;
8272                        }
8273                    }
8274                }
8275
8276                switch (grant) {
8277                    case GRANT_INSTALL: {
8278                        // Revoke this as runtime permission to handle the case of
8279                        // a runtime permission being downgraded to an install one.
8280                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8281                            if (origPermissions.getRuntimePermissionState(
8282                                    bp.name, userId) != null) {
8283                                // Revoke the runtime permission and clear the flags.
8284                                origPermissions.revokeRuntimePermission(bp, userId);
8285                                origPermissions.updatePermissionFlags(bp, userId,
8286                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8287                                // If we revoked a permission permission, we have to write.
8288                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8289                                        changedRuntimePermissionUserIds, userId);
8290                            }
8291                        }
8292                        // Grant an install permission.
8293                        if (permissionsState.grantInstallPermission(bp) !=
8294                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8295                            changedInstallPermission = true;
8296                        }
8297                    } break;
8298
8299                    case GRANT_INSTALL_LEGACY: {
8300                        // Grant an install permission.
8301                        if (permissionsState.grantInstallPermission(bp) !=
8302                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8303                            changedInstallPermission = true;
8304                        }
8305                    } break;
8306
8307                    case GRANT_RUNTIME: {
8308                        // Grant previously granted runtime permissions.
8309                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8310                            PermissionState permissionState = origPermissions
8311                                    .getRuntimePermissionState(bp.name, userId);
8312                            final int flags = permissionState != null
8313                                    ? permissionState.getFlags() : 0;
8314                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8315                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8316                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8317                                    // If we cannot put the permission as it was, we have to write.
8318                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8319                                            changedRuntimePermissionUserIds, userId);
8320                                }
8321                            }
8322                            // Propagate the permission flags.
8323                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8324                        }
8325                    } break;
8326
8327                    case GRANT_UPGRADE: {
8328                        // Grant runtime permissions for a previously held install permission.
8329                        PermissionState permissionState = origPermissions
8330                                .getInstallPermissionState(bp.name);
8331                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8332
8333                        if (origPermissions.revokeInstallPermission(bp)
8334                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8335                            // We will be transferring the permission flags, so clear them.
8336                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8337                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8338                            changedInstallPermission = true;
8339                        }
8340
8341                        // If the permission is not to be promoted to runtime we ignore it and
8342                        // also its other flags as they are not applicable to install permissions.
8343                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8344                            for (int userId : currentUserIds) {
8345                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8346                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8347                                    // Transfer the permission flags.
8348                                    permissionsState.updatePermissionFlags(bp, userId,
8349                                            flags, flags);
8350                                    // If we granted the permission, we have to write.
8351                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8352                                            changedRuntimePermissionUserIds, userId);
8353                                }
8354                            }
8355                        }
8356                    } break;
8357
8358                    default: {
8359                        if (packageOfInterest == null
8360                                || packageOfInterest.equals(pkg.packageName)) {
8361                            Slog.w(TAG, "Not granting permission " + perm
8362                                    + " to package " + pkg.packageName
8363                                    + " because it was previously installed without");
8364                        }
8365                    } break;
8366                }
8367            } else {
8368                if (permissionsState.revokeInstallPermission(bp) !=
8369                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8370                    // Also drop the permission flags.
8371                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8372                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8373                    changedInstallPermission = true;
8374                    Slog.i(TAG, "Un-granting permission " + perm
8375                            + " from package " + pkg.packageName
8376                            + " (protectionLevel=" + bp.protectionLevel
8377                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8378                            + ")");
8379                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8380                    // Don't print warning for app op permissions, since it is fine for them
8381                    // not to be granted, there is a UI for the user to decide.
8382                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8383                        Slog.w(TAG, "Not granting permission " + perm
8384                                + " to package " + pkg.packageName
8385                                + " (protectionLevel=" + bp.protectionLevel
8386                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8387                                + ")");
8388                    }
8389                }
8390            }
8391        }
8392
8393        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8394                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8395            // This is the first that we have heard about this package, so the
8396            // permissions we have now selected are fixed until explicitly
8397            // changed.
8398            ps.installPermissionsFixed = true;
8399        }
8400
8401        // Persist the runtime permissions state for users with changes.
8402        for (int userId : changedRuntimePermissionUserIds) {
8403            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
8404        }
8405    }
8406
8407    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8408        boolean allowed = false;
8409        final int NP = PackageParser.NEW_PERMISSIONS.length;
8410        for (int ip=0; ip<NP; ip++) {
8411            final PackageParser.NewPermissionInfo npi
8412                    = PackageParser.NEW_PERMISSIONS[ip];
8413            if (npi.name.equals(perm)
8414                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8415                allowed = true;
8416                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8417                        + pkg.packageName);
8418                break;
8419            }
8420        }
8421        return allowed;
8422    }
8423
8424    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8425            BasePermission bp, PermissionsState origPermissions) {
8426        boolean allowed;
8427        allowed = (compareSignatures(
8428                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8429                        == PackageManager.SIGNATURE_MATCH)
8430                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8431                        == PackageManager.SIGNATURE_MATCH);
8432        if (!allowed && (bp.protectionLevel
8433                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
8434            if (isSystemApp(pkg)) {
8435                // For updated system applications, a system permission
8436                // is granted only if it had been defined by the original application.
8437                if (pkg.isUpdatedSystemApp()) {
8438                    final PackageSetting sysPs = mSettings
8439                            .getDisabledSystemPkgLPr(pkg.packageName);
8440                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8441                        // If the original was granted this permission, we take
8442                        // that grant decision as read and propagate it to the
8443                        // update.
8444                        if (sysPs.isPrivileged()) {
8445                            allowed = true;
8446                        }
8447                    } else {
8448                        // The system apk may have been updated with an older
8449                        // version of the one on the data partition, but which
8450                        // granted a new system permission that it didn't have
8451                        // before.  In this case we do want to allow the app to
8452                        // now get the new permission if the ancestral apk is
8453                        // privileged to get it.
8454                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
8455                            for (int j=0;
8456                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
8457                                if (perm.equals(
8458                                        sysPs.pkg.requestedPermissions.get(j))) {
8459                                    allowed = true;
8460                                    break;
8461                                }
8462                            }
8463                        }
8464                    }
8465                } else {
8466                    allowed = isPrivilegedApp(pkg);
8467                }
8468            }
8469        }
8470        if (!allowed) {
8471            if (!allowed && (bp.protectionLevel
8472                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
8473                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.MNC) {
8474                // If this was a previously normal/dangerous permission that got moved
8475                // to a system permission as part of the runtime permission redesign, then
8476                // we still want to blindly grant it to old apps.
8477                allowed = true;
8478            }
8479            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
8480                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
8481                // If this permission is to be granted to the system installer and
8482                // this app is an installer, then it gets the permission.
8483                allowed = true;
8484            }
8485            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
8486                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
8487                // If this permission is to be granted to the system verifier and
8488                // this app is a verifier, then it gets the permission.
8489                allowed = true;
8490            }
8491            if (!allowed && (bp.protectionLevel
8492                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
8493                    && isSystemApp(pkg)) {
8494                // Any pre-installed system app is allowed to get this permission.
8495                allowed = true;
8496            }
8497            if (!allowed && (bp.protectionLevel
8498                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8499                // For development permissions, a development permission
8500                // is granted only if it was already granted.
8501                allowed = origPermissions.hasInstallPermission(perm);
8502            }
8503        }
8504        return allowed;
8505    }
8506
8507    final class ActivityIntentResolver
8508            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8509        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8510                boolean defaultOnly, int userId) {
8511            if (!sUserManager.exists(userId)) return null;
8512            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8513            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8514        }
8515
8516        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8517                int userId) {
8518            if (!sUserManager.exists(userId)) return null;
8519            mFlags = flags;
8520            return super.queryIntent(intent, resolvedType,
8521                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8522        }
8523
8524        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8525                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8526            if (!sUserManager.exists(userId)) return null;
8527            if (packageActivities == null) {
8528                return null;
8529            }
8530            mFlags = flags;
8531            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8532            final int N = packageActivities.size();
8533            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8534                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8535
8536            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8537            for (int i = 0; i < N; ++i) {
8538                intentFilters = packageActivities.get(i).intents;
8539                if (intentFilters != null && intentFilters.size() > 0) {
8540                    PackageParser.ActivityIntentInfo[] array =
8541                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
8542                    intentFilters.toArray(array);
8543                    listCut.add(array);
8544                }
8545            }
8546            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8547        }
8548
8549        public final void addActivity(PackageParser.Activity a, String type) {
8550            final boolean systemApp = a.info.applicationInfo.isSystemApp();
8551            mActivities.put(a.getComponentName(), a);
8552            if (DEBUG_SHOW_INFO)
8553                Log.v(
8554                TAG, "  " + type + " " +
8555                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8556            if (DEBUG_SHOW_INFO)
8557                Log.v(TAG, "    Class=" + a.info.name);
8558            final int NI = a.intents.size();
8559            for (int j=0; j<NI; j++) {
8560                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8561                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
8562                    intent.setPriority(0);
8563                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
8564                            + a.className + " with priority > 0, forcing to 0");
8565                }
8566                if (DEBUG_SHOW_INFO) {
8567                    Log.v(TAG, "    IntentFilter:");
8568                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8569                }
8570                if (!intent.debugCheck()) {
8571                    Log.w(TAG, "==> For Activity " + a.info.name);
8572                }
8573                addFilter(intent);
8574            }
8575        }
8576
8577        public final void removeActivity(PackageParser.Activity a, String type) {
8578            mActivities.remove(a.getComponentName());
8579            if (DEBUG_SHOW_INFO) {
8580                Log.v(TAG, "  " + type + " "
8581                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
8582                                : a.info.name) + ":");
8583                Log.v(TAG, "    Class=" + a.info.name);
8584            }
8585            final int NI = a.intents.size();
8586            for (int j=0; j<NI; j++) {
8587                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8588                if (DEBUG_SHOW_INFO) {
8589                    Log.v(TAG, "    IntentFilter:");
8590                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8591                }
8592                removeFilter(intent);
8593            }
8594        }
8595
8596        @Override
8597        protected boolean allowFilterResult(
8598                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
8599            ActivityInfo filterAi = filter.activity.info;
8600            for (int i=dest.size()-1; i>=0; i--) {
8601                ActivityInfo destAi = dest.get(i).activityInfo;
8602                if (destAi.name == filterAi.name
8603                        && destAi.packageName == filterAi.packageName) {
8604                    return false;
8605                }
8606            }
8607            return true;
8608        }
8609
8610        @Override
8611        protected ActivityIntentInfo[] newArray(int size) {
8612            return new ActivityIntentInfo[size];
8613        }
8614
8615        @Override
8616        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
8617            if (!sUserManager.exists(userId)) return true;
8618            PackageParser.Package p = filter.activity.owner;
8619            if (p != null) {
8620                PackageSetting ps = (PackageSetting)p.mExtras;
8621                if (ps != null) {
8622                    // System apps are never considered stopped for purposes of
8623                    // filtering, because there may be no way for the user to
8624                    // actually re-launch them.
8625                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
8626                            && ps.getStopped(userId);
8627                }
8628            }
8629            return false;
8630        }
8631
8632        @Override
8633        protected boolean isPackageForFilter(String packageName,
8634                PackageParser.ActivityIntentInfo info) {
8635            return packageName.equals(info.activity.owner.packageName);
8636        }
8637
8638        @Override
8639        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
8640                int match, int userId) {
8641            if (!sUserManager.exists(userId)) return null;
8642            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
8643                return null;
8644            }
8645            final PackageParser.Activity activity = info.activity;
8646            if (mSafeMode && (activity.info.applicationInfo.flags
8647                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8648                return null;
8649            }
8650            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
8651            if (ps == null) {
8652                return null;
8653            }
8654            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
8655                    ps.readUserState(userId), userId);
8656            if (ai == null) {
8657                return null;
8658            }
8659            final ResolveInfo res = new ResolveInfo();
8660            res.activityInfo = ai;
8661            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8662                res.filter = info;
8663            }
8664            if (info != null) {
8665                res.handleAllWebDataURI = info.handleAllWebDataURI();
8666            }
8667            res.priority = info.getPriority();
8668            res.preferredOrder = activity.owner.mPreferredOrder;
8669            //System.out.println("Result: " + res.activityInfo.className +
8670            //                   " = " + res.priority);
8671            res.match = match;
8672            res.isDefault = info.hasDefault;
8673            res.labelRes = info.labelRes;
8674            res.nonLocalizedLabel = info.nonLocalizedLabel;
8675            if (userNeedsBadging(userId)) {
8676                res.noResourceId = true;
8677            } else {
8678                res.icon = info.icon;
8679            }
8680            res.iconResourceId = info.icon;
8681            res.system = res.activityInfo.applicationInfo.isSystemApp();
8682            return res;
8683        }
8684
8685        @Override
8686        protected void sortResults(List<ResolveInfo> results) {
8687            Collections.sort(results, mResolvePrioritySorter);
8688        }
8689
8690        @Override
8691        protected void dumpFilter(PrintWriter out, String prefix,
8692                PackageParser.ActivityIntentInfo filter) {
8693            out.print(prefix); out.print(
8694                    Integer.toHexString(System.identityHashCode(filter.activity)));
8695                    out.print(' ');
8696                    filter.activity.printComponentShortName(out);
8697                    out.print(" filter ");
8698                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8699        }
8700
8701        @Override
8702        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
8703            return filter.activity;
8704        }
8705
8706        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8707            PackageParser.Activity activity = (PackageParser.Activity)label;
8708            out.print(prefix); out.print(
8709                    Integer.toHexString(System.identityHashCode(activity)));
8710                    out.print(' ');
8711                    activity.printComponentShortName(out);
8712            if (count > 1) {
8713                out.print(" ("); out.print(count); out.print(" filters)");
8714            }
8715            out.println();
8716        }
8717
8718//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8719//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8720//            final List<ResolveInfo> retList = Lists.newArrayList();
8721//            while (i.hasNext()) {
8722//                final ResolveInfo resolveInfo = i.next();
8723//                if (isEnabledLP(resolveInfo.activityInfo)) {
8724//                    retList.add(resolveInfo);
8725//                }
8726//            }
8727//            return retList;
8728//        }
8729
8730        // Keys are String (activity class name), values are Activity.
8731        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
8732                = new ArrayMap<ComponentName, PackageParser.Activity>();
8733        private int mFlags;
8734    }
8735
8736    private final class ServiceIntentResolver
8737            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
8738        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8739                boolean defaultOnly, int userId) {
8740            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8741            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8742        }
8743
8744        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8745                int userId) {
8746            if (!sUserManager.exists(userId)) return null;
8747            mFlags = flags;
8748            return super.queryIntent(intent, resolvedType,
8749                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8750        }
8751
8752        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8753                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
8754            if (!sUserManager.exists(userId)) return null;
8755            if (packageServices == null) {
8756                return null;
8757            }
8758            mFlags = flags;
8759            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8760            final int N = packageServices.size();
8761            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
8762                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
8763
8764            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
8765            for (int i = 0; i < N; ++i) {
8766                intentFilters = packageServices.get(i).intents;
8767                if (intentFilters != null && intentFilters.size() > 0) {
8768                    PackageParser.ServiceIntentInfo[] array =
8769                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
8770                    intentFilters.toArray(array);
8771                    listCut.add(array);
8772                }
8773            }
8774            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8775        }
8776
8777        public final void addService(PackageParser.Service s) {
8778            mServices.put(s.getComponentName(), s);
8779            if (DEBUG_SHOW_INFO) {
8780                Log.v(TAG, "  "
8781                        + (s.info.nonLocalizedLabel != null
8782                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8783                Log.v(TAG, "    Class=" + s.info.name);
8784            }
8785            final int NI = s.intents.size();
8786            int j;
8787            for (j=0; j<NI; j++) {
8788                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8789                if (DEBUG_SHOW_INFO) {
8790                    Log.v(TAG, "    IntentFilter:");
8791                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8792                }
8793                if (!intent.debugCheck()) {
8794                    Log.w(TAG, "==> For Service " + s.info.name);
8795                }
8796                addFilter(intent);
8797            }
8798        }
8799
8800        public final void removeService(PackageParser.Service s) {
8801            mServices.remove(s.getComponentName());
8802            if (DEBUG_SHOW_INFO) {
8803                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
8804                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8805                Log.v(TAG, "    Class=" + s.info.name);
8806            }
8807            final int NI = s.intents.size();
8808            int j;
8809            for (j=0; j<NI; j++) {
8810                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8811                if (DEBUG_SHOW_INFO) {
8812                    Log.v(TAG, "    IntentFilter:");
8813                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8814                }
8815                removeFilter(intent);
8816            }
8817        }
8818
8819        @Override
8820        protected boolean allowFilterResult(
8821                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
8822            ServiceInfo filterSi = filter.service.info;
8823            for (int i=dest.size()-1; i>=0; i--) {
8824                ServiceInfo destAi = dest.get(i).serviceInfo;
8825                if (destAi.name == filterSi.name
8826                        && destAi.packageName == filterSi.packageName) {
8827                    return false;
8828                }
8829            }
8830            return true;
8831        }
8832
8833        @Override
8834        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
8835            return new PackageParser.ServiceIntentInfo[size];
8836        }
8837
8838        @Override
8839        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
8840            if (!sUserManager.exists(userId)) return true;
8841            PackageParser.Package p = filter.service.owner;
8842            if (p != null) {
8843                PackageSetting ps = (PackageSetting)p.mExtras;
8844                if (ps != null) {
8845                    // System apps are never considered stopped for purposes of
8846                    // filtering, because there may be no way for the user to
8847                    // actually re-launch them.
8848                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8849                            && ps.getStopped(userId);
8850                }
8851            }
8852            return false;
8853        }
8854
8855        @Override
8856        protected boolean isPackageForFilter(String packageName,
8857                PackageParser.ServiceIntentInfo info) {
8858            return packageName.equals(info.service.owner.packageName);
8859        }
8860
8861        @Override
8862        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
8863                int match, int userId) {
8864            if (!sUserManager.exists(userId)) return null;
8865            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
8866            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
8867                return null;
8868            }
8869            final PackageParser.Service service = info.service;
8870            if (mSafeMode && (service.info.applicationInfo.flags
8871                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8872                return null;
8873            }
8874            PackageSetting ps = (PackageSetting) service.owner.mExtras;
8875            if (ps == null) {
8876                return null;
8877            }
8878            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
8879                    ps.readUserState(userId), userId);
8880            if (si == null) {
8881                return null;
8882            }
8883            final ResolveInfo res = new ResolveInfo();
8884            res.serviceInfo = si;
8885            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8886                res.filter = filter;
8887            }
8888            res.priority = info.getPriority();
8889            res.preferredOrder = service.owner.mPreferredOrder;
8890            res.match = match;
8891            res.isDefault = info.hasDefault;
8892            res.labelRes = info.labelRes;
8893            res.nonLocalizedLabel = info.nonLocalizedLabel;
8894            res.icon = info.icon;
8895            res.system = res.serviceInfo.applicationInfo.isSystemApp();
8896            return res;
8897        }
8898
8899        @Override
8900        protected void sortResults(List<ResolveInfo> results) {
8901            Collections.sort(results, mResolvePrioritySorter);
8902        }
8903
8904        @Override
8905        protected void dumpFilter(PrintWriter out, String prefix,
8906                PackageParser.ServiceIntentInfo filter) {
8907            out.print(prefix); out.print(
8908                    Integer.toHexString(System.identityHashCode(filter.service)));
8909                    out.print(' ');
8910                    filter.service.printComponentShortName(out);
8911                    out.print(" filter ");
8912                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8913        }
8914
8915        @Override
8916        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
8917            return filter.service;
8918        }
8919
8920        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8921            PackageParser.Service service = (PackageParser.Service)label;
8922            out.print(prefix); out.print(
8923                    Integer.toHexString(System.identityHashCode(service)));
8924                    out.print(' ');
8925                    service.printComponentShortName(out);
8926            if (count > 1) {
8927                out.print(" ("); out.print(count); out.print(" filters)");
8928            }
8929            out.println();
8930        }
8931
8932//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8933//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8934//            final List<ResolveInfo> retList = Lists.newArrayList();
8935//            while (i.hasNext()) {
8936//                final ResolveInfo resolveInfo = (ResolveInfo) i;
8937//                if (isEnabledLP(resolveInfo.serviceInfo)) {
8938//                    retList.add(resolveInfo);
8939//                }
8940//            }
8941//            return retList;
8942//        }
8943
8944        // Keys are String (activity class name), values are Activity.
8945        private final ArrayMap<ComponentName, PackageParser.Service> mServices
8946                = new ArrayMap<ComponentName, PackageParser.Service>();
8947        private int mFlags;
8948    };
8949
8950    private final class ProviderIntentResolver
8951            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
8952        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8953                boolean defaultOnly, int userId) {
8954            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8955            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8956        }
8957
8958        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8959                int userId) {
8960            if (!sUserManager.exists(userId))
8961                return null;
8962            mFlags = flags;
8963            return super.queryIntent(intent, resolvedType,
8964                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8965        }
8966
8967        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8968                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
8969            if (!sUserManager.exists(userId))
8970                return null;
8971            if (packageProviders == null) {
8972                return null;
8973            }
8974            mFlags = flags;
8975            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
8976            final int N = packageProviders.size();
8977            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
8978                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
8979
8980            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
8981            for (int i = 0; i < N; ++i) {
8982                intentFilters = packageProviders.get(i).intents;
8983                if (intentFilters != null && intentFilters.size() > 0) {
8984                    PackageParser.ProviderIntentInfo[] array =
8985                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
8986                    intentFilters.toArray(array);
8987                    listCut.add(array);
8988                }
8989            }
8990            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8991        }
8992
8993        public final void addProvider(PackageParser.Provider p) {
8994            if (mProviders.containsKey(p.getComponentName())) {
8995                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
8996                return;
8997            }
8998
8999            mProviders.put(p.getComponentName(), p);
9000            if (DEBUG_SHOW_INFO) {
9001                Log.v(TAG, "  "
9002                        + (p.info.nonLocalizedLabel != null
9003                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
9004                Log.v(TAG, "    Class=" + p.info.name);
9005            }
9006            final int NI = p.intents.size();
9007            int j;
9008            for (j = 0; j < NI; j++) {
9009                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9010                if (DEBUG_SHOW_INFO) {
9011                    Log.v(TAG, "    IntentFilter:");
9012                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9013                }
9014                if (!intent.debugCheck()) {
9015                    Log.w(TAG, "==> For Provider " + p.info.name);
9016                }
9017                addFilter(intent);
9018            }
9019        }
9020
9021        public final void removeProvider(PackageParser.Provider p) {
9022            mProviders.remove(p.getComponentName());
9023            if (DEBUG_SHOW_INFO) {
9024                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9025                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
9026                Log.v(TAG, "    Class=" + p.info.name);
9027            }
9028            final int NI = p.intents.size();
9029            int j;
9030            for (j = 0; j < NI; j++) {
9031                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9032                if (DEBUG_SHOW_INFO) {
9033                    Log.v(TAG, "    IntentFilter:");
9034                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9035                }
9036                removeFilter(intent);
9037            }
9038        }
9039
9040        @Override
9041        protected boolean allowFilterResult(
9042                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9043            ProviderInfo filterPi = filter.provider.info;
9044            for (int i = dest.size() - 1; i >= 0; i--) {
9045                ProviderInfo destPi = dest.get(i).providerInfo;
9046                if (destPi.name == filterPi.name
9047                        && destPi.packageName == filterPi.packageName) {
9048                    return false;
9049                }
9050            }
9051            return true;
9052        }
9053
9054        @Override
9055        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9056            return new PackageParser.ProviderIntentInfo[size];
9057        }
9058
9059        @Override
9060        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9061            if (!sUserManager.exists(userId))
9062                return true;
9063            PackageParser.Package p = filter.provider.owner;
9064            if (p != null) {
9065                PackageSetting ps = (PackageSetting) p.mExtras;
9066                if (ps != null) {
9067                    // System apps are never considered stopped for purposes of
9068                    // filtering, because there may be no way for the user to
9069                    // actually re-launch them.
9070                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9071                            && ps.getStopped(userId);
9072                }
9073            }
9074            return false;
9075        }
9076
9077        @Override
9078        protected boolean isPackageForFilter(String packageName,
9079                PackageParser.ProviderIntentInfo info) {
9080            return packageName.equals(info.provider.owner.packageName);
9081        }
9082
9083        @Override
9084        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9085                int match, int userId) {
9086            if (!sUserManager.exists(userId))
9087                return null;
9088            final PackageParser.ProviderIntentInfo info = filter;
9089            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
9090                return null;
9091            }
9092            final PackageParser.Provider provider = info.provider;
9093            if (mSafeMode && (provider.info.applicationInfo.flags
9094                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
9095                return null;
9096            }
9097            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9098            if (ps == null) {
9099                return null;
9100            }
9101            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9102                    ps.readUserState(userId), userId);
9103            if (pi == null) {
9104                return null;
9105            }
9106            final ResolveInfo res = new ResolveInfo();
9107            res.providerInfo = pi;
9108            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9109                res.filter = filter;
9110            }
9111            res.priority = info.getPriority();
9112            res.preferredOrder = provider.owner.mPreferredOrder;
9113            res.match = match;
9114            res.isDefault = info.hasDefault;
9115            res.labelRes = info.labelRes;
9116            res.nonLocalizedLabel = info.nonLocalizedLabel;
9117            res.icon = info.icon;
9118            res.system = res.providerInfo.applicationInfo.isSystemApp();
9119            return res;
9120        }
9121
9122        @Override
9123        protected void sortResults(List<ResolveInfo> results) {
9124            Collections.sort(results, mResolvePrioritySorter);
9125        }
9126
9127        @Override
9128        protected void dumpFilter(PrintWriter out, String prefix,
9129                PackageParser.ProviderIntentInfo filter) {
9130            out.print(prefix);
9131            out.print(
9132                    Integer.toHexString(System.identityHashCode(filter.provider)));
9133            out.print(' ');
9134            filter.provider.printComponentShortName(out);
9135            out.print(" filter ");
9136            out.println(Integer.toHexString(System.identityHashCode(filter)));
9137        }
9138
9139        @Override
9140        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9141            return filter.provider;
9142        }
9143
9144        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9145            PackageParser.Provider provider = (PackageParser.Provider)label;
9146            out.print(prefix); out.print(
9147                    Integer.toHexString(System.identityHashCode(provider)));
9148                    out.print(' ');
9149                    provider.printComponentShortName(out);
9150            if (count > 1) {
9151                out.print(" ("); out.print(count); out.print(" filters)");
9152            }
9153            out.println();
9154        }
9155
9156        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9157                = new ArrayMap<ComponentName, PackageParser.Provider>();
9158        private int mFlags;
9159    };
9160
9161    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9162            new Comparator<ResolveInfo>() {
9163        public int compare(ResolveInfo r1, ResolveInfo r2) {
9164            int v1 = r1.priority;
9165            int v2 = r2.priority;
9166            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9167            if (v1 != v2) {
9168                return (v1 > v2) ? -1 : 1;
9169            }
9170            v1 = r1.preferredOrder;
9171            v2 = r2.preferredOrder;
9172            if (v1 != v2) {
9173                return (v1 > v2) ? -1 : 1;
9174            }
9175            if (r1.isDefault != r2.isDefault) {
9176                return r1.isDefault ? -1 : 1;
9177            }
9178            v1 = r1.match;
9179            v2 = r2.match;
9180            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9181            if (v1 != v2) {
9182                return (v1 > v2) ? -1 : 1;
9183            }
9184            if (r1.system != r2.system) {
9185                return r1.system ? -1 : 1;
9186            }
9187            return 0;
9188        }
9189    };
9190
9191    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9192            new Comparator<ProviderInfo>() {
9193        public int compare(ProviderInfo p1, ProviderInfo p2) {
9194            final int v1 = p1.initOrder;
9195            final int v2 = p2.initOrder;
9196            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9197        }
9198    };
9199
9200    final void sendPackageBroadcast(final String action, final String pkg,
9201            final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
9202            final int[] userIds) {
9203        mHandler.post(new Runnable() {
9204            @Override
9205            public void run() {
9206                try {
9207                    final IActivityManager am = ActivityManagerNative.getDefault();
9208                    if (am == null) return;
9209                    final int[] resolvedUserIds;
9210                    if (userIds == null) {
9211                        resolvedUserIds = am.getRunningUserIds();
9212                    } else {
9213                        resolvedUserIds = userIds;
9214                    }
9215                    for (int id : resolvedUserIds) {
9216                        final Intent intent = new Intent(action,
9217                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9218                        if (extras != null) {
9219                            intent.putExtras(extras);
9220                        }
9221                        if (targetPkg != null) {
9222                            intent.setPackage(targetPkg);
9223                        }
9224                        // Modify the UID when posting to other users
9225                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9226                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9227                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9228                            intent.putExtra(Intent.EXTRA_UID, uid);
9229                        }
9230                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9231                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
9232                        if (DEBUG_BROADCASTS) {
9233                            RuntimeException here = new RuntimeException("here");
9234                            here.fillInStackTrace();
9235                            Slog.d(TAG, "Sending to user " + id + ": "
9236                                    + intent.toShortString(false, true, false, false)
9237                                    + " " + intent.getExtras(), here);
9238                        }
9239                        am.broadcastIntent(null, intent, null, finishedReceiver,
9240                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9241                                null, finishedReceiver != null, false, id);
9242                    }
9243                } catch (RemoteException ex) {
9244                }
9245            }
9246        });
9247    }
9248
9249    /**
9250     * Check if the external storage media is available. This is true if there
9251     * is a mounted external storage medium or if the external storage is
9252     * emulated.
9253     */
9254    private boolean isExternalMediaAvailable() {
9255        return mMediaMounted || Environment.isExternalStorageEmulated();
9256    }
9257
9258    @Override
9259    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9260        // writer
9261        synchronized (mPackages) {
9262            if (!isExternalMediaAvailable()) {
9263                // If the external storage is no longer mounted at this point,
9264                // the caller may not have been able to delete all of this
9265                // packages files and can not delete any more.  Bail.
9266                return null;
9267            }
9268            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9269            if (lastPackage != null) {
9270                pkgs.remove(lastPackage);
9271            }
9272            if (pkgs.size() > 0) {
9273                return pkgs.get(0);
9274            }
9275        }
9276        return null;
9277    }
9278
9279    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9280        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9281                userId, andCode ? 1 : 0, packageName);
9282        if (mSystemReady) {
9283            msg.sendToTarget();
9284        } else {
9285            if (mPostSystemReadyMessages == null) {
9286                mPostSystemReadyMessages = new ArrayList<>();
9287            }
9288            mPostSystemReadyMessages.add(msg);
9289        }
9290    }
9291
9292    void startCleaningPackages() {
9293        // reader
9294        synchronized (mPackages) {
9295            if (!isExternalMediaAvailable()) {
9296                return;
9297            }
9298            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9299                return;
9300            }
9301        }
9302        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9303        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9304        IActivityManager am = ActivityManagerNative.getDefault();
9305        if (am != null) {
9306            try {
9307                am.startService(null, intent, null, mContext.getOpPackageName(),
9308                        UserHandle.USER_OWNER);
9309            } catch (RemoteException e) {
9310            }
9311        }
9312    }
9313
9314    @Override
9315    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9316            int installFlags, String installerPackageName, VerificationParams verificationParams,
9317            String packageAbiOverride) {
9318        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9319                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9320    }
9321
9322    @Override
9323    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9324            int installFlags, String installerPackageName, VerificationParams verificationParams,
9325            String packageAbiOverride, int userId) {
9326        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9327
9328        final int callingUid = Binder.getCallingUid();
9329        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9330
9331        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9332            try {
9333                if (observer != null) {
9334                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9335                }
9336            } catch (RemoteException re) {
9337            }
9338            return;
9339        }
9340
9341        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9342            installFlags |= PackageManager.INSTALL_FROM_ADB;
9343
9344        } else {
9345            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9346            // about installerPackageName.
9347
9348            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9349            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9350        }
9351
9352        UserHandle user;
9353        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9354            user = UserHandle.ALL;
9355        } else {
9356            user = new UserHandle(userId);
9357        }
9358
9359        // Only system components can circumvent runtime permissions when installing.
9360        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9361                && mContext.checkCallingOrSelfPermission(Manifest.permission
9362                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9363            throw new SecurityException("You need the "
9364                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9365                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9366        }
9367
9368        verificationParams.setInstallerUid(callingUid);
9369
9370        final File originFile = new File(originPath);
9371        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9372
9373        final Message msg = mHandler.obtainMessage(INIT_COPY);
9374        msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName,
9375                null, verificationParams, user, packageAbiOverride);
9376        mHandler.sendMessage(msg);
9377    }
9378
9379    void installStage(String packageName, File stagedDir, String stagedCid,
9380            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
9381            String installerPackageName, int installerUid, UserHandle user) {
9382        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
9383                params.referrerUri, installerUid, null);
9384        verifParams.setInstallerUid(installerUid);
9385
9386        final OriginInfo origin;
9387        if (stagedDir != null) {
9388            origin = OriginInfo.fromStagedFile(stagedDir);
9389        } else {
9390            origin = OriginInfo.fromStagedContainer(stagedCid);
9391        }
9392
9393        final Message msg = mHandler.obtainMessage(INIT_COPY);
9394        msg.obj = new InstallParams(origin, null, observer, params.installFlags,
9395                installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride);
9396        mHandler.sendMessage(msg);
9397    }
9398
9399    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
9400        Bundle extras = new Bundle(1);
9401        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
9402
9403        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
9404                packageName, extras, null, null, new int[] {userId});
9405        try {
9406            IActivityManager am = ActivityManagerNative.getDefault();
9407            final boolean isSystem =
9408                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
9409            if (isSystem && am.isUserRunning(userId, false)) {
9410                // The just-installed/enabled app is bundled on the system, so presumed
9411                // to be able to run automatically without needing an explicit launch.
9412                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
9413                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
9414                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
9415                        .setPackage(packageName);
9416                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
9417                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
9418            }
9419        } catch (RemoteException e) {
9420            // shouldn't happen
9421            Slog.w(TAG, "Unable to bootstrap installed package", e);
9422        }
9423    }
9424
9425    @Override
9426    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9427            int userId) {
9428        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9429        PackageSetting pkgSetting;
9430        final int uid = Binder.getCallingUid();
9431        enforceCrossUserPermission(uid, userId, true, true,
9432                "setApplicationHiddenSetting for user " + userId);
9433
9434        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9435            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9436            return false;
9437        }
9438
9439        long callingId = Binder.clearCallingIdentity();
9440        try {
9441            boolean sendAdded = false;
9442            boolean sendRemoved = false;
9443            // writer
9444            synchronized (mPackages) {
9445                pkgSetting = mSettings.mPackages.get(packageName);
9446                if (pkgSetting == null) {
9447                    return false;
9448                }
9449                if (pkgSetting.getHidden(userId) != hidden) {
9450                    pkgSetting.setHidden(hidden, userId);
9451                    mSettings.writePackageRestrictionsLPr(userId);
9452                    if (hidden) {
9453                        sendRemoved = true;
9454                    } else {
9455                        sendAdded = true;
9456                    }
9457                }
9458            }
9459            if (sendAdded) {
9460                sendPackageAddedForUser(packageName, pkgSetting, userId);
9461                return true;
9462            }
9463            if (sendRemoved) {
9464                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
9465                        "hiding pkg");
9466                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
9467            }
9468        } finally {
9469            Binder.restoreCallingIdentity(callingId);
9470        }
9471        return false;
9472    }
9473
9474    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9475            int userId) {
9476        final PackageRemovedInfo info = new PackageRemovedInfo();
9477        info.removedPackage = packageName;
9478        info.removedUsers = new int[] {userId};
9479        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9480        info.sendBroadcast(false, false, false);
9481    }
9482
9483    /**
9484     * Returns true if application is not found or there was an error. Otherwise it returns
9485     * the hidden state of the package for the given user.
9486     */
9487    @Override
9488    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9489        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9490        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9491                false, "getApplicationHidden for user " + userId);
9492        PackageSetting pkgSetting;
9493        long callingId = Binder.clearCallingIdentity();
9494        try {
9495            // writer
9496            synchronized (mPackages) {
9497                pkgSetting = mSettings.mPackages.get(packageName);
9498                if (pkgSetting == null) {
9499                    return true;
9500                }
9501                return pkgSetting.getHidden(userId);
9502            }
9503        } finally {
9504            Binder.restoreCallingIdentity(callingId);
9505        }
9506    }
9507
9508    /**
9509     * @hide
9510     */
9511    @Override
9512    public int installExistingPackageAsUser(String packageName, int userId) {
9513        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9514                null);
9515        PackageSetting pkgSetting;
9516        final int uid = Binder.getCallingUid();
9517        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9518                + userId);
9519        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9520            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9521        }
9522
9523        long callingId = Binder.clearCallingIdentity();
9524        try {
9525            boolean sendAdded = false;
9526
9527            // writer
9528            synchronized (mPackages) {
9529                pkgSetting = mSettings.mPackages.get(packageName);
9530                if (pkgSetting == null) {
9531                    return PackageManager.INSTALL_FAILED_INVALID_URI;
9532                }
9533                if (!pkgSetting.getInstalled(userId)) {
9534                    pkgSetting.setInstalled(true, userId);
9535                    pkgSetting.setHidden(false, userId);
9536                    mSettings.writePackageRestrictionsLPr(userId);
9537                    sendAdded = true;
9538                }
9539            }
9540
9541            if (sendAdded) {
9542                sendPackageAddedForUser(packageName, pkgSetting, userId);
9543            }
9544        } finally {
9545            Binder.restoreCallingIdentity(callingId);
9546        }
9547
9548        return PackageManager.INSTALL_SUCCEEDED;
9549    }
9550
9551    boolean isUserRestricted(int userId, String restrictionKey) {
9552        Bundle restrictions = sUserManager.getUserRestrictions(userId);
9553        if (restrictions.getBoolean(restrictionKey, false)) {
9554            Log.w(TAG, "User is restricted: " + restrictionKey);
9555            return true;
9556        }
9557        return false;
9558    }
9559
9560    @Override
9561    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
9562        mContext.enforceCallingOrSelfPermission(
9563                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9564                "Only package verification agents can verify applications");
9565
9566        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9567        final PackageVerificationResponse response = new PackageVerificationResponse(
9568                verificationCode, Binder.getCallingUid());
9569        msg.arg1 = id;
9570        msg.obj = response;
9571        mHandler.sendMessage(msg);
9572    }
9573
9574    @Override
9575    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
9576            long millisecondsToDelay) {
9577        mContext.enforceCallingOrSelfPermission(
9578                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9579                "Only package verification agents can extend verification timeouts");
9580
9581        final PackageVerificationState state = mPendingVerification.get(id);
9582        final PackageVerificationResponse response = new PackageVerificationResponse(
9583                verificationCodeAtTimeout, Binder.getCallingUid());
9584
9585        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
9586            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
9587        }
9588        if (millisecondsToDelay < 0) {
9589            millisecondsToDelay = 0;
9590        }
9591        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9592                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9593            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9594        }
9595
9596        if ((state != null) && !state.timeoutExtended()) {
9597            state.extendTimeout();
9598
9599            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9600            msg.arg1 = id;
9601            msg.obj = response;
9602            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
9603        }
9604    }
9605
9606    private void broadcastPackageVerified(int verificationId, Uri packageUri,
9607            int verificationCode, UserHandle user) {
9608        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
9609        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
9610        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9611        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9612        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
9613
9614        mContext.sendBroadcastAsUser(intent, user,
9615                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
9616    }
9617
9618    private ComponentName matchComponentForVerifier(String packageName,
9619            List<ResolveInfo> receivers) {
9620        ActivityInfo targetReceiver = null;
9621
9622        final int NR = receivers.size();
9623        for (int i = 0; i < NR; i++) {
9624            final ResolveInfo info = receivers.get(i);
9625            if (info.activityInfo == null) {
9626                continue;
9627            }
9628
9629            if (packageName.equals(info.activityInfo.packageName)) {
9630                targetReceiver = info.activityInfo;
9631                break;
9632            }
9633        }
9634
9635        if (targetReceiver == null) {
9636            return null;
9637        }
9638
9639        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
9640    }
9641
9642    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
9643            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
9644        if (pkgInfo.verifiers.length == 0) {
9645            return null;
9646        }
9647
9648        final int N = pkgInfo.verifiers.length;
9649        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
9650        for (int i = 0; i < N; i++) {
9651            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
9652
9653            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
9654                    receivers);
9655            if (comp == null) {
9656                continue;
9657            }
9658
9659            final int verifierUid = getUidForVerifier(verifierInfo);
9660            if (verifierUid == -1) {
9661                continue;
9662            }
9663
9664            if (DEBUG_VERIFY) {
9665                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
9666                        + " with the correct signature");
9667            }
9668            sufficientVerifiers.add(comp);
9669            verificationState.addSufficientVerifier(verifierUid);
9670        }
9671
9672        return sufficientVerifiers;
9673    }
9674
9675    private int getUidForVerifier(VerifierInfo verifierInfo) {
9676        synchronized (mPackages) {
9677            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
9678            if (pkg == null) {
9679                return -1;
9680            } else if (pkg.mSignatures.length != 1) {
9681                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9682                        + " has more than one signature; ignoring");
9683                return -1;
9684            }
9685
9686            /*
9687             * If the public key of the package's signature does not match
9688             * our expected public key, then this is a different package and
9689             * we should skip.
9690             */
9691
9692            final byte[] expectedPublicKey;
9693            try {
9694                final Signature verifierSig = pkg.mSignatures[0];
9695                final PublicKey publicKey = verifierSig.getPublicKey();
9696                expectedPublicKey = publicKey.getEncoded();
9697            } catch (CertificateException e) {
9698                return -1;
9699            }
9700
9701            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
9702
9703            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
9704                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9705                        + " does not have the expected public key; ignoring");
9706                return -1;
9707            }
9708
9709            return pkg.applicationInfo.uid;
9710        }
9711    }
9712
9713    @Override
9714    public void finishPackageInstall(int token) {
9715        enforceSystemOrRoot("Only the system is allowed to finish installs");
9716
9717        if (DEBUG_INSTALL) {
9718            Slog.v(TAG, "BM finishing package install for " + token);
9719        }
9720
9721        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9722        mHandler.sendMessage(msg);
9723    }
9724
9725    /**
9726     * Get the verification agent timeout.
9727     *
9728     * @return verification timeout in milliseconds
9729     */
9730    private long getVerificationTimeout() {
9731        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
9732                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
9733                DEFAULT_VERIFICATION_TIMEOUT);
9734    }
9735
9736    /**
9737     * Get the default verification agent response code.
9738     *
9739     * @return default verification response code
9740     */
9741    private int getDefaultVerificationResponse() {
9742        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9743                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
9744                DEFAULT_VERIFICATION_RESPONSE);
9745    }
9746
9747    /**
9748     * Check whether or not package verification has been enabled.
9749     *
9750     * @return true if verification should be performed
9751     */
9752    private boolean isVerificationEnabled(int userId, int installFlags) {
9753        if (!DEFAULT_VERIFY_ENABLE) {
9754            return false;
9755        }
9756
9757        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
9758
9759        // Check if installing from ADB
9760        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
9761            // Do not run verification in a test harness environment
9762            if (ActivityManager.isRunningInTestHarness()) {
9763                return false;
9764            }
9765            if (ensureVerifyAppsEnabled) {
9766                return true;
9767            }
9768            // Check if the developer does not want package verification for ADB installs
9769            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9770                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
9771                return false;
9772            }
9773        }
9774
9775        if (ensureVerifyAppsEnabled) {
9776            return true;
9777        }
9778
9779        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9780                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9781    }
9782
9783    @Override
9784    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9785            throws RemoteException {
9786        mContext.enforceCallingOrSelfPermission(
9787                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9788                "Only intentfilter verification agents can verify applications");
9789
9790        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9791        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9792                Binder.getCallingUid(), verificationCode, failedDomains);
9793        msg.arg1 = id;
9794        msg.obj = response;
9795        mHandler.sendMessage(msg);
9796    }
9797
9798    @Override
9799    public int getIntentVerificationStatus(String packageName, int userId) {
9800        synchronized (mPackages) {
9801            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
9802        }
9803    }
9804
9805    @Override
9806    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
9807        mContext.enforceCallingOrSelfPermission(
9808                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9809
9810        boolean result = false;
9811        synchronized (mPackages) {
9812            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
9813        }
9814        if (result) {
9815            scheduleWritePackageRestrictionsLocked(userId);
9816        }
9817        return result;
9818    }
9819
9820    @Override
9821    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
9822        synchronized (mPackages) {
9823            return mSettings.getIntentFilterVerificationsLPr(packageName);
9824        }
9825    }
9826
9827    @Override
9828    public List<IntentFilter> getAllIntentFilters(String packageName) {
9829        if (TextUtils.isEmpty(packageName)) {
9830            return Collections.<IntentFilter>emptyList();
9831        }
9832        synchronized (mPackages) {
9833            PackageParser.Package pkg = mPackages.get(packageName);
9834            if (pkg == null || pkg.activities == null) {
9835                return Collections.<IntentFilter>emptyList();
9836            }
9837            final int count = pkg.activities.size();
9838            ArrayList<IntentFilter> result = new ArrayList<>();
9839            for (int n=0; n<count; n++) {
9840                PackageParser.Activity activity = pkg.activities.get(n);
9841                if (activity.intents != null || activity.intents.size() > 0) {
9842                    result.addAll(activity.intents);
9843                }
9844            }
9845            return result;
9846        }
9847    }
9848
9849    @Override
9850    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
9851        mContext.enforceCallingOrSelfPermission(
9852                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9853
9854        synchronized (mPackages) {
9855            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
9856            if (packageName != null) {
9857                result |= updateIntentVerificationStatus(packageName,
9858                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
9859                        UserHandle.myUserId());
9860                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
9861                        packageName, userId);
9862            }
9863            return result;
9864        }
9865    }
9866
9867    @Override
9868    public String getDefaultBrowserPackageName(int userId) {
9869        synchronized (mPackages) {
9870            return mSettings.getDefaultBrowserPackageNameLPw(userId);
9871        }
9872    }
9873
9874    /**
9875     * Get the "allow unknown sources" setting.
9876     *
9877     * @return the current "allow unknown sources" setting
9878     */
9879    private int getUnknownSourcesSettings() {
9880        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9881                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
9882                -1);
9883    }
9884
9885    @Override
9886    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
9887        final int uid = Binder.getCallingUid();
9888        // writer
9889        synchronized (mPackages) {
9890            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
9891            if (targetPackageSetting == null) {
9892                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
9893            }
9894
9895            PackageSetting installerPackageSetting;
9896            if (installerPackageName != null) {
9897                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
9898                if (installerPackageSetting == null) {
9899                    throw new IllegalArgumentException("Unknown installer package: "
9900                            + installerPackageName);
9901                }
9902            } else {
9903                installerPackageSetting = null;
9904            }
9905
9906            Signature[] callerSignature;
9907            Object obj = mSettings.getUserIdLPr(uid);
9908            if (obj != null) {
9909                if (obj instanceof SharedUserSetting) {
9910                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
9911                } else if (obj instanceof PackageSetting) {
9912                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
9913                } else {
9914                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
9915                }
9916            } else {
9917                throw new SecurityException("Unknown calling uid " + uid);
9918            }
9919
9920            // Verify: can't set installerPackageName to a package that is
9921            // not signed with the same cert as the caller.
9922            if (installerPackageSetting != null) {
9923                if (compareSignatures(callerSignature,
9924                        installerPackageSetting.signatures.mSignatures)
9925                        != PackageManager.SIGNATURE_MATCH) {
9926                    throw new SecurityException(
9927                            "Caller does not have same cert as new installer package "
9928                            + installerPackageName);
9929                }
9930            }
9931
9932            // Verify: if target already has an installer package, it must
9933            // be signed with the same cert as the caller.
9934            if (targetPackageSetting.installerPackageName != null) {
9935                PackageSetting setting = mSettings.mPackages.get(
9936                        targetPackageSetting.installerPackageName);
9937                // If the currently set package isn't valid, then it's always
9938                // okay to change it.
9939                if (setting != null) {
9940                    if (compareSignatures(callerSignature,
9941                            setting.signatures.mSignatures)
9942                            != PackageManager.SIGNATURE_MATCH) {
9943                        throw new SecurityException(
9944                                "Caller does not have same cert as old installer package "
9945                                + targetPackageSetting.installerPackageName);
9946                    }
9947                }
9948            }
9949
9950            // Okay!
9951            targetPackageSetting.installerPackageName = installerPackageName;
9952            scheduleWriteSettingsLocked();
9953        }
9954    }
9955
9956    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
9957        // Queue up an async operation since the package installation may take a little while.
9958        mHandler.post(new Runnable() {
9959            public void run() {
9960                mHandler.removeCallbacks(this);
9961                 // Result object to be returned
9962                PackageInstalledInfo res = new PackageInstalledInfo();
9963                res.returnCode = currentStatus;
9964                res.uid = -1;
9965                res.pkg = null;
9966                res.removedInfo = new PackageRemovedInfo();
9967                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
9968                    args.doPreInstall(res.returnCode);
9969                    synchronized (mInstallLock) {
9970                        installPackageLI(args, res);
9971                    }
9972                    args.doPostInstall(res.returnCode, res.uid);
9973                }
9974
9975                // A restore should be performed at this point if (a) the install
9976                // succeeded, (b) the operation is not an update, and (c) the new
9977                // package has not opted out of backup participation.
9978                final boolean update = res.removedInfo.removedPackage != null;
9979                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
9980                boolean doRestore = !update
9981                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
9982
9983                // Set up the post-install work request bookkeeping.  This will be used
9984                // and cleaned up by the post-install event handling regardless of whether
9985                // there's a restore pass performed.  Token values are >= 1.
9986                int token;
9987                if (mNextInstallToken < 0) mNextInstallToken = 1;
9988                token = mNextInstallToken++;
9989
9990                PostInstallData data = new PostInstallData(args, res);
9991                mRunningInstalls.put(token, data);
9992                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
9993
9994                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
9995                    // Pass responsibility to the Backup Manager.  It will perform a
9996                    // restore if appropriate, then pass responsibility back to the
9997                    // Package Manager to run the post-install observer callbacks
9998                    // and broadcasts.
9999                    IBackupManager bm = IBackupManager.Stub.asInterface(
10000                            ServiceManager.getService(Context.BACKUP_SERVICE));
10001                    if (bm != null) {
10002                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10003                                + " to BM for possible restore");
10004                        try {
10005                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
10006                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10007                            } else {
10008                                doRestore = false;
10009                            }
10010                        } catch (RemoteException e) {
10011                            // can't happen; the backup manager is local
10012                        } catch (Exception e) {
10013                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10014                            doRestore = false;
10015                        }
10016                    } else {
10017                        Slog.e(TAG, "Backup Manager not found!");
10018                        doRestore = false;
10019                    }
10020                }
10021
10022                if (!doRestore) {
10023                    // No restore possible, or the Backup Manager was mysteriously not
10024                    // available -- just fire the post-install work request directly.
10025                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10026                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10027                    mHandler.sendMessage(msg);
10028                }
10029            }
10030        });
10031    }
10032
10033    private abstract class HandlerParams {
10034        private static final int MAX_RETRIES = 4;
10035
10036        /**
10037         * Number of times startCopy() has been attempted and had a non-fatal
10038         * error.
10039         */
10040        private int mRetries = 0;
10041
10042        /** User handle for the user requesting the information or installation. */
10043        private final UserHandle mUser;
10044
10045        HandlerParams(UserHandle user) {
10046            mUser = user;
10047        }
10048
10049        UserHandle getUser() {
10050            return mUser;
10051        }
10052
10053        final boolean startCopy() {
10054            boolean res;
10055            try {
10056                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10057
10058                if (++mRetries > MAX_RETRIES) {
10059                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10060                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10061                    handleServiceError();
10062                    return false;
10063                } else {
10064                    handleStartCopy();
10065                    res = true;
10066                }
10067            } catch (RemoteException e) {
10068                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10069                mHandler.sendEmptyMessage(MCS_RECONNECT);
10070                res = false;
10071            }
10072            handleReturnCode();
10073            return res;
10074        }
10075
10076        final void serviceError() {
10077            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10078            handleServiceError();
10079            handleReturnCode();
10080        }
10081
10082        abstract void handleStartCopy() throws RemoteException;
10083        abstract void handleServiceError();
10084        abstract void handleReturnCode();
10085    }
10086
10087    class MeasureParams extends HandlerParams {
10088        private final PackageStats mStats;
10089        private boolean mSuccess;
10090
10091        private final IPackageStatsObserver mObserver;
10092
10093        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10094            super(new UserHandle(stats.userHandle));
10095            mObserver = observer;
10096            mStats = stats;
10097        }
10098
10099        @Override
10100        public String toString() {
10101            return "MeasureParams{"
10102                + Integer.toHexString(System.identityHashCode(this))
10103                + " " + mStats.packageName + "}";
10104        }
10105
10106        @Override
10107        void handleStartCopy() throws RemoteException {
10108            synchronized (mInstallLock) {
10109                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10110            }
10111
10112            if (mSuccess) {
10113                final boolean mounted;
10114                if (Environment.isExternalStorageEmulated()) {
10115                    mounted = true;
10116                } else {
10117                    final String status = Environment.getExternalStorageState();
10118                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10119                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10120                }
10121
10122                if (mounted) {
10123                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10124
10125                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10126                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10127
10128                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10129                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10130
10131                    // Always subtract cache size, since it's a subdirectory
10132                    mStats.externalDataSize -= mStats.externalCacheSize;
10133
10134                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10135                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10136
10137                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10138                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10139                }
10140            }
10141        }
10142
10143        @Override
10144        void handleReturnCode() {
10145            if (mObserver != null) {
10146                try {
10147                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10148                } catch (RemoteException e) {
10149                    Slog.i(TAG, "Observer no longer exists.");
10150                }
10151            }
10152        }
10153
10154        @Override
10155        void handleServiceError() {
10156            Slog.e(TAG, "Could not measure application " + mStats.packageName
10157                            + " external storage");
10158        }
10159    }
10160
10161    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10162            throws RemoteException {
10163        long result = 0;
10164        for (File path : paths) {
10165            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10166        }
10167        return result;
10168    }
10169
10170    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10171        for (File path : paths) {
10172            try {
10173                mcs.clearDirectory(path.getAbsolutePath());
10174            } catch (RemoteException e) {
10175            }
10176        }
10177    }
10178
10179    static class OriginInfo {
10180        /**
10181         * Location where install is coming from, before it has been
10182         * copied/renamed into place. This could be a single monolithic APK
10183         * file, or a cluster directory. This location may be untrusted.
10184         */
10185        final File file;
10186        final String cid;
10187
10188        /**
10189         * Flag indicating that {@link #file} or {@link #cid} has already been
10190         * staged, meaning downstream users don't need to defensively copy the
10191         * contents.
10192         */
10193        final boolean staged;
10194
10195        /**
10196         * Flag indicating that {@link #file} or {@link #cid} is an already
10197         * installed app that is being moved.
10198         */
10199        final boolean existing;
10200
10201        final String resolvedPath;
10202        final File resolvedFile;
10203
10204        static OriginInfo fromNothing() {
10205            return new OriginInfo(null, null, false, false);
10206        }
10207
10208        static OriginInfo fromUntrustedFile(File file) {
10209            return new OriginInfo(file, null, false, false);
10210        }
10211
10212        static OriginInfo fromExistingFile(File file) {
10213            return new OriginInfo(file, null, false, true);
10214        }
10215
10216        static OriginInfo fromStagedFile(File file) {
10217            return new OriginInfo(file, null, true, false);
10218        }
10219
10220        static OriginInfo fromStagedContainer(String cid) {
10221            return new OriginInfo(null, cid, true, false);
10222        }
10223
10224        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10225            this.file = file;
10226            this.cid = cid;
10227            this.staged = staged;
10228            this.existing = existing;
10229
10230            if (cid != null) {
10231                resolvedPath = PackageHelper.getSdDir(cid);
10232                resolvedFile = new File(resolvedPath);
10233            } else if (file != null) {
10234                resolvedPath = file.getAbsolutePath();
10235                resolvedFile = file;
10236            } else {
10237                resolvedPath = null;
10238                resolvedFile = null;
10239            }
10240        }
10241    }
10242
10243    class MoveInfo {
10244        final int moveId;
10245        final String fromUuid;
10246        final String toUuid;
10247        final String packageName;
10248        final String dataAppName;
10249        final int appId;
10250        final String seinfo;
10251
10252        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10253                String dataAppName, int appId, String seinfo) {
10254            this.moveId = moveId;
10255            this.fromUuid = fromUuid;
10256            this.toUuid = toUuid;
10257            this.packageName = packageName;
10258            this.dataAppName = dataAppName;
10259            this.appId = appId;
10260            this.seinfo = seinfo;
10261        }
10262    }
10263
10264    class InstallParams extends HandlerParams {
10265        final OriginInfo origin;
10266        final MoveInfo move;
10267        final IPackageInstallObserver2 observer;
10268        int installFlags;
10269        final String installerPackageName;
10270        final String volumeUuid;
10271        final VerificationParams verificationParams;
10272        private InstallArgs mArgs;
10273        private int mRet;
10274        final String packageAbiOverride;
10275
10276        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10277                int installFlags, String installerPackageName, String volumeUuid,
10278                VerificationParams verificationParams, UserHandle user, String packageAbiOverride) {
10279            super(user);
10280            this.origin = origin;
10281            this.move = move;
10282            this.observer = observer;
10283            this.installFlags = installFlags;
10284            this.installerPackageName = installerPackageName;
10285            this.volumeUuid = volumeUuid;
10286            this.verificationParams = verificationParams;
10287            this.packageAbiOverride = packageAbiOverride;
10288        }
10289
10290        @Override
10291        public String toString() {
10292            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10293                    + " file=" + origin.file + " cid=" + origin.cid + "}";
10294        }
10295
10296        public ManifestDigest getManifestDigest() {
10297            if (verificationParams == null) {
10298                return null;
10299            }
10300            return verificationParams.getManifestDigest();
10301        }
10302
10303        private int installLocationPolicy(PackageInfoLite pkgLite) {
10304            String packageName = pkgLite.packageName;
10305            int installLocation = pkgLite.installLocation;
10306            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10307            // reader
10308            synchronized (mPackages) {
10309                PackageParser.Package pkg = mPackages.get(packageName);
10310                if (pkg != null) {
10311                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10312                        // Check for downgrading.
10313                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10314                            try {
10315                                checkDowngrade(pkg, pkgLite);
10316                            } catch (PackageManagerException e) {
10317                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10318                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
10319                            }
10320                        }
10321                        // Check for updated system application.
10322                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10323                            if (onSd) {
10324                                Slog.w(TAG, "Cannot install update to system app on sdcard");
10325                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
10326                            }
10327                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10328                        } else {
10329                            if (onSd) {
10330                                // Install flag overrides everything.
10331                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10332                            }
10333                            // If current upgrade specifies particular preference
10334                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
10335                                // Application explicitly specified internal.
10336                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10337                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
10338                                // App explictly prefers external. Let policy decide
10339                            } else {
10340                                // Prefer previous location
10341                                if (isExternal(pkg)) {
10342                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10343                                }
10344                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10345                            }
10346                        }
10347                    } else {
10348                        // Invalid install. Return error code
10349                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
10350                    }
10351                }
10352            }
10353            // All the special cases have been taken care of.
10354            // Return result based on recommended install location.
10355            if (onSd) {
10356                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10357            }
10358            return pkgLite.recommendedInstallLocation;
10359        }
10360
10361        /*
10362         * Invoke remote method to get package information and install
10363         * location values. Override install location based on default
10364         * policy if needed and then create install arguments based
10365         * on the install location.
10366         */
10367        public void handleStartCopy() throws RemoteException {
10368            int ret = PackageManager.INSTALL_SUCCEEDED;
10369
10370            // If we're already staged, we've firmly committed to an install location
10371            if (origin.staged) {
10372                if (origin.file != null) {
10373                    installFlags |= PackageManager.INSTALL_INTERNAL;
10374                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10375                } else if (origin.cid != null) {
10376                    installFlags |= PackageManager.INSTALL_EXTERNAL;
10377                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
10378                } else {
10379                    throw new IllegalStateException("Invalid stage location");
10380                }
10381            }
10382
10383            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10384            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
10385
10386            PackageInfoLite pkgLite = null;
10387
10388            if (onInt && onSd) {
10389                // Check if both bits are set.
10390                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
10391                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10392            } else {
10393                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
10394                        packageAbiOverride);
10395
10396                /*
10397                 * If we have too little free space, try to free cache
10398                 * before giving up.
10399                 */
10400                if (!origin.staged && pkgLite.recommendedInstallLocation
10401                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10402                    // TODO: focus freeing disk space on the target device
10403                    final StorageManager storage = StorageManager.from(mContext);
10404                    final long lowThreshold = storage.getStorageLowBytes(
10405                            Environment.getDataDirectory());
10406
10407                    final long sizeBytes = mContainerService.calculateInstalledSize(
10408                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
10409
10410                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
10411                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
10412                                installFlags, packageAbiOverride);
10413                    }
10414
10415                    /*
10416                     * The cache free must have deleted the file we
10417                     * downloaded to install.
10418                     *
10419                     * TODO: fix the "freeCache" call to not delete
10420                     *       the file we care about.
10421                     */
10422                    if (pkgLite.recommendedInstallLocation
10423                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10424                        pkgLite.recommendedInstallLocation
10425                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
10426                    }
10427                }
10428            }
10429
10430            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10431                int loc = pkgLite.recommendedInstallLocation;
10432                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
10433                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10434                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
10435                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
10436                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10437                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10438                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
10439                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
10440                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10441                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
10442                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
10443                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
10444                } else {
10445                    // Override with defaults if needed.
10446                    loc = installLocationPolicy(pkgLite);
10447                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
10448                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
10449                    } else if (!onSd && !onInt) {
10450                        // Override install location with flags
10451                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
10452                            // Set the flag to install on external media.
10453                            installFlags |= PackageManager.INSTALL_EXTERNAL;
10454                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
10455                        } else {
10456                            // Make sure the flag for installing on external
10457                            // media is unset
10458                            installFlags |= PackageManager.INSTALL_INTERNAL;
10459                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10460                        }
10461                    }
10462                }
10463            }
10464
10465            final InstallArgs args = createInstallArgs(this);
10466            mArgs = args;
10467
10468            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10469                 /*
10470                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
10471                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
10472                 */
10473                int userIdentifier = getUser().getIdentifier();
10474                if (userIdentifier == UserHandle.USER_ALL
10475                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
10476                    userIdentifier = UserHandle.USER_OWNER;
10477                }
10478
10479                /*
10480                 * Determine if we have any installed package verifiers. If we
10481                 * do, then we'll defer to them to verify the packages.
10482                 */
10483                final int requiredUid = mRequiredVerifierPackage == null ? -1
10484                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
10485                if (!origin.existing && requiredUid != -1
10486                        && isVerificationEnabled(userIdentifier, installFlags)) {
10487                    final Intent verification = new Intent(
10488                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
10489                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10490                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
10491                            PACKAGE_MIME_TYPE);
10492                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10493
10494                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
10495                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10496                            0 /* TODO: Which userId? */);
10497
10498                    if (DEBUG_VERIFY) {
10499                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10500                                + verification.toString() + " with " + pkgLite.verifiers.length
10501                                + " optional verifiers");
10502                    }
10503
10504                    final int verificationId = mPendingVerificationToken++;
10505
10506                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10507
10508                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10509                            installerPackageName);
10510
10511                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10512                            installFlags);
10513
10514                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10515                            pkgLite.packageName);
10516
10517                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10518                            pkgLite.versionCode);
10519
10520                    if (verificationParams != null) {
10521                        if (verificationParams.getVerificationURI() != null) {
10522                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10523                                 verificationParams.getVerificationURI());
10524                        }
10525                        if (verificationParams.getOriginatingURI() != null) {
10526                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10527                                  verificationParams.getOriginatingURI());
10528                        }
10529                        if (verificationParams.getReferrer() != null) {
10530                            verification.putExtra(Intent.EXTRA_REFERRER,
10531                                  verificationParams.getReferrer());
10532                        }
10533                        if (verificationParams.getOriginatingUid() >= 0) {
10534                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
10535                                  verificationParams.getOriginatingUid());
10536                        }
10537                        if (verificationParams.getInstallerUid() >= 0) {
10538                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
10539                                  verificationParams.getInstallerUid());
10540                        }
10541                    }
10542
10543                    final PackageVerificationState verificationState = new PackageVerificationState(
10544                            requiredUid, args);
10545
10546                    mPendingVerification.append(verificationId, verificationState);
10547
10548                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
10549                            receivers, verificationState);
10550
10551                    /*
10552                     * If any sufficient verifiers were listed in the package
10553                     * manifest, attempt to ask them.
10554                     */
10555                    if (sufficientVerifiers != null) {
10556                        final int N = sufficientVerifiers.size();
10557                        if (N == 0) {
10558                            Slog.i(TAG, "Additional verifiers required, but none installed.");
10559                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
10560                        } else {
10561                            for (int i = 0; i < N; i++) {
10562                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
10563
10564                                final Intent sufficientIntent = new Intent(verification);
10565                                sufficientIntent.setComponent(verifierComponent);
10566
10567                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
10568                            }
10569                        }
10570                    }
10571
10572                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
10573                            mRequiredVerifierPackage, receivers);
10574                    if (ret == PackageManager.INSTALL_SUCCEEDED
10575                            && mRequiredVerifierPackage != null) {
10576                        /*
10577                         * Send the intent to the required verification agent,
10578                         * but only start the verification timeout after the
10579                         * target BroadcastReceivers have run.
10580                         */
10581                        verification.setComponent(requiredVerifierComponent);
10582                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
10583                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10584                                new BroadcastReceiver() {
10585                                    @Override
10586                                    public void onReceive(Context context, Intent intent) {
10587                                        final Message msg = mHandler
10588                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
10589                                        msg.arg1 = verificationId;
10590                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
10591                                    }
10592                                }, null, 0, null, null);
10593
10594                        /*
10595                         * We don't want the copy to proceed until verification
10596                         * succeeds, so null out this field.
10597                         */
10598                        mArgs = null;
10599                    }
10600                } else {
10601                    /*
10602                     * No package verification is enabled, so immediately start
10603                     * the remote call to initiate copy using temporary file.
10604                     */
10605                    ret = args.copyApk(mContainerService, true);
10606                }
10607            }
10608
10609            mRet = ret;
10610        }
10611
10612        @Override
10613        void handleReturnCode() {
10614            // If mArgs is null, then MCS couldn't be reached. When it
10615            // reconnects, it will try again to install. At that point, this
10616            // will succeed.
10617            if (mArgs != null) {
10618                processPendingInstall(mArgs, mRet);
10619            }
10620        }
10621
10622        @Override
10623        void handleServiceError() {
10624            mArgs = createInstallArgs(this);
10625            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10626        }
10627
10628        public boolean isForwardLocked() {
10629            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10630        }
10631    }
10632
10633    /**
10634     * Used during creation of InstallArgs
10635     *
10636     * @param installFlags package installation flags
10637     * @return true if should be installed on external storage
10638     */
10639    private static boolean installOnExternalAsec(int installFlags) {
10640        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
10641            return false;
10642        }
10643        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
10644            return true;
10645        }
10646        return false;
10647    }
10648
10649    /**
10650     * Used during creation of InstallArgs
10651     *
10652     * @param installFlags package installation flags
10653     * @return true if should be installed as forward locked
10654     */
10655    private static boolean installForwardLocked(int installFlags) {
10656        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10657    }
10658
10659    private InstallArgs createInstallArgs(InstallParams params) {
10660        if (params.move != null) {
10661            return new MoveInstallArgs(params);
10662        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
10663            return new AsecInstallArgs(params);
10664        } else {
10665            return new FileInstallArgs(params);
10666        }
10667    }
10668
10669    /**
10670     * Create args that describe an existing installed package. Typically used
10671     * when cleaning up old installs, or used as a move source.
10672     */
10673    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
10674            String resourcePath, String[] instructionSets) {
10675        final boolean isInAsec;
10676        if (installOnExternalAsec(installFlags)) {
10677            /* Apps on SD card are always in ASEC containers. */
10678            isInAsec = true;
10679        } else if (installForwardLocked(installFlags)
10680                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
10681            /*
10682             * Forward-locked apps are only in ASEC containers if they're the
10683             * new style
10684             */
10685            isInAsec = true;
10686        } else {
10687            isInAsec = false;
10688        }
10689
10690        if (isInAsec) {
10691            return new AsecInstallArgs(codePath, instructionSets,
10692                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
10693        } else {
10694            return new FileInstallArgs(codePath, resourcePath, instructionSets);
10695        }
10696    }
10697
10698    static abstract class InstallArgs {
10699        /** @see InstallParams#origin */
10700        final OriginInfo origin;
10701        /** @see InstallParams#move */
10702        final MoveInfo move;
10703
10704        final IPackageInstallObserver2 observer;
10705        // Always refers to PackageManager flags only
10706        final int installFlags;
10707        final String installerPackageName;
10708        final String volumeUuid;
10709        final ManifestDigest manifestDigest;
10710        final UserHandle user;
10711        final String abiOverride;
10712
10713        // The list of instruction sets supported by this app. This is currently
10714        // only used during the rmdex() phase to clean up resources. We can get rid of this
10715        // if we move dex files under the common app path.
10716        /* nullable */ String[] instructionSets;
10717
10718        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10719                int installFlags, String installerPackageName, String volumeUuid,
10720                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
10721                String abiOverride) {
10722            this.origin = origin;
10723            this.move = move;
10724            this.installFlags = installFlags;
10725            this.observer = observer;
10726            this.installerPackageName = installerPackageName;
10727            this.volumeUuid = volumeUuid;
10728            this.manifestDigest = manifestDigest;
10729            this.user = user;
10730            this.instructionSets = instructionSets;
10731            this.abiOverride = abiOverride;
10732        }
10733
10734        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
10735        abstract int doPreInstall(int status);
10736
10737        /**
10738         * Rename package into final resting place. All paths on the given
10739         * scanned package should be updated to reflect the rename.
10740         */
10741        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
10742        abstract int doPostInstall(int status, int uid);
10743
10744        /** @see PackageSettingBase#codePathString */
10745        abstract String getCodePath();
10746        /** @see PackageSettingBase#resourcePathString */
10747        abstract String getResourcePath();
10748
10749        // Need installer lock especially for dex file removal.
10750        abstract void cleanUpResourcesLI();
10751        abstract boolean doPostDeleteLI(boolean delete);
10752
10753        /**
10754         * Called before the source arguments are copied. This is used mostly
10755         * for MoveParams when it needs to read the source file to put it in the
10756         * destination.
10757         */
10758        int doPreCopy() {
10759            return PackageManager.INSTALL_SUCCEEDED;
10760        }
10761
10762        /**
10763         * Called after the source arguments are copied. This is used mostly for
10764         * MoveParams when it needs to read the source file to put it in the
10765         * destination.
10766         *
10767         * @return
10768         */
10769        int doPostCopy(int uid) {
10770            return PackageManager.INSTALL_SUCCEEDED;
10771        }
10772
10773        protected boolean isFwdLocked() {
10774            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10775        }
10776
10777        protected boolean isExternalAsec() {
10778            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10779        }
10780
10781        UserHandle getUser() {
10782            return user;
10783        }
10784    }
10785
10786    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
10787        if (!allCodePaths.isEmpty()) {
10788            if (instructionSets == null) {
10789                throw new IllegalStateException("instructionSet == null");
10790            }
10791            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
10792            for (String codePath : allCodePaths) {
10793                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
10794                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
10795                    if (retCode < 0) {
10796                        Slog.w(TAG, "Couldn't remove dex file for package: "
10797                                + " at location " + codePath + ", retcode=" + retCode);
10798                        // we don't consider this to be a failure of the core package deletion
10799                    }
10800                }
10801            }
10802        }
10803    }
10804
10805    /**
10806     * Logic to handle installation of non-ASEC applications, including copying
10807     * and renaming logic.
10808     */
10809    class FileInstallArgs extends InstallArgs {
10810        private File codeFile;
10811        private File resourceFile;
10812
10813        // Example topology:
10814        // /data/app/com.example/base.apk
10815        // /data/app/com.example/split_foo.apk
10816        // /data/app/com.example/lib/arm/libfoo.so
10817        // /data/app/com.example/lib/arm64/libfoo.so
10818        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
10819
10820        /** New install */
10821        FileInstallArgs(InstallParams params) {
10822            super(params.origin, params.move, params.observer, params.installFlags,
10823                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10824                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10825            if (isFwdLocked()) {
10826                throw new IllegalArgumentException("Forward locking only supported in ASEC");
10827            }
10828        }
10829
10830        /** Existing install */
10831        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
10832            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
10833                    null);
10834            this.codeFile = (codePath != null) ? new File(codePath) : null;
10835            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
10836        }
10837
10838        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10839            if (origin.staged) {
10840                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
10841                codeFile = origin.file;
10842                resourceFile = origin.file;
10843                return PackageManager.INSTALL_SUCCEEDED;
10844            }
10845
10846            try {
10847                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
10848                codeFile = tempDir;
10849                resourceFile = tempDir;
10850            } catch (IOException e) {
10851                Slog.w(TAG, "Failed to create copy file: " + e);
10852                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10853            }
10854
10855            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
10856                @Override
10857                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
10858                    if (!FileUtils.isValidExtFilename(name)) {
10859                        throw new IllegalArgumentException("Invalid filename: " + name);
10860                    }
10861                    try {
10862                        final File file = new File(codeFile, name);
10863                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
10864                                O_RDWR | O_CREAT, 0644);
10865                        Os.chmod(file.getAbsolutePath(), 0644);
10866                        return new ParcelFileDescriptor(fd);
10867                    } catch (ErrnoException e) {
10868                        throw new RemoteException("Failed to open: " + e.getMessage());
10869                    }
10870                }
10871            };
10872
10873            int ret = PackageManager.INSTALL_SUCCEEDED;
10874            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
10875            if (ret != PackageManager.INSTALL_SUCCEEDED) {
10876                Slog.e(TAG, "Failed to copy package");
10877                return ret;
10878            }
10879
10880            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
10881            NativeLibraryHelper.Handle handle = null;
10882            try {
10883                handle = NativeLibraryHelper.Handle.create(codeFile);
10884                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
10885                        abiOverride);
10886            } catch (IOException e) {
10887                Slog.e(TAG, "Copying native libraries failed", e);
10888                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10889            } finally {
10890                IoUtils.closeQuietly(handle);
10891            }
10892
10893            return ret;
10894        }
10895
10896        int doPreInstall(int status) {
10897            if (status != PackageManager.INSTALL_SUCCEEDED) {
10898                cleanUp();
10899            }
10900            return status;
10901        }
10902
10903        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10904            if (status != PackageManager.INSTALL_SUCCEEDED) {
10905                cleanUp();
10906                return false;
10907            }
10908
10909            final File targetDir = codeFile.getParentFile();
10910            final File beforeCodeFile = codeFile;
10911            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
10912
10913            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
10914            try {
10915                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
10916            } catch (ErrnoException e) {
10917                Slog.w(TAG, "Failed to rename", e);
10918                return false;
10919            }
10920
10921            if (!SELinux.restoreconRecursive(afterCodeFile)) {
10922                Slog.w(TAG, "Failed to restorecon");
10923                return false;
10924            }
10925
10926            // Reflect the rename internally
10927            codeFile = afterCodeFile;
10928            resourceFile = afterCodeFile;
10929
10930            // Reflect the rename in scanned details
10931            pkg.codePath = afterCodeFile.getAbsolutePath();
10932            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10933                    pkg.baseCodePath);
10934            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10935                    pkg.splitCodePaths);
10936
10937            // Reflect the rename in app info
10938            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10939            pkg.applicationInfo.setCodePath(pkg.codePath);
10940            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10941            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10942            pkg.applicationInfo.setResourcePath(pkg.codePath);
10943            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10944            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10945
10946            return true;
10947        }
10948
10949        int doPostInstall(int status, int uid) {
10950            if (status != PackageManager.INSTALL_SUCCEEDED) {
10951                cleanUp();
10952            }
10953            return status;
10954        }
10955
10956        @Override
10957        String getCodePath() {
10958            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
10959        }
10960
10961        @Override
10962        String getResourcePath() {
10963            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
10964        }
10965
10966        private boolean cleanUp() {
10967            if (codeFile == null || !codeFile.exists()) {
10968                return false;
10969            }
10970
10971            if (codeFile.isDirectory()) {
10972                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
10973            } else {
10974                codeFile.delete();
10975            }
10976
10977            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
10978                resourceFile.delete();
10979            }
10980
10981            return true;
10982        }
10983
10984        void cleanUpResourcesLI() {
10985            // Try enumerating all code paths before deleting
10986            List<String> allCodePaths = Collections.EMPTY_LIST;
10987            if (codeFile != null && codeFile.exists()) {
10988                try {
10989                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
10990                    allCodePaths = pkg.getAllCodePaths();
10991                } catch (PackageParserException e) {
10992                    // Ignored; we tried our best
10993                }
10994            }
10995
10996            cleanUp();
10997            removeDexFiles(allCodePaths, instructionSets);
10998        }
10999
11000        boolean doPostDeleteLI(boolean delete) {
11001            // XXX err, shouldn't we respect the delete flag?
11002            cleanUpResourcesLI();
11003            return true;
11004        }
11005    }
11006
11007    private boolean isAsecExternal(String cid) {
11008        final String asecPath = PackageHelper.getSdFilesystem(cid);
11009        return !asecPath.startsWith(mAsecInternalPath);
11010    }
11011
11012    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11013            PackageManagerException {
11014        if (copyRet < 0) {
11015            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11016                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11017                throw new PackageManagerException(copyRet, message);
11018            }
11019        }
11020    }
11021
11022    /**
11023     * Extract the MountService "container ID" from the full code path of an
11024     * .apk.
11025     */
11026    static String cidFromCodePath(String fullCodePath) {
11027        int eidx = fullCodePath.lastIndexOf("/");
11028        String subStr1 = fullCodePath.substring(0, eidx);
11029        int sidx = subStr1.lastIndexOf("/");
11030        return subStr1.substring(sidx+1, eidx);
11031    }
11032
11033    /**
11034     * Logic to handle installation of ASEC applications, including copying and
11035     * renaming logic.
11036     */
11037    class AsecInstallArgs extends InstallArgs {
11038        static final String RES_FILE_NAME = "pkg.apk";
11039        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11040
11041        String cid;
11042        String packagePath;
11043        String resourcePath;
11044
11045        /** New install */
11046        AsecInstallArgs(InstallParams params) {
11047            super(params.origin, params.move, params.observer, params.installFlags,
11048                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11049                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
11050        }
11051
11052        /** Existing install */
11053        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11054                        boolean isExternal, boolean isForwardLocked) {
11055            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11056                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11057                    instructionSets, null);
11058            // Hackily pretend we're still looking at a full code path
11059            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11060                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11061            }
11062
11063            // Extract cid from fullCodePath
11064            int eidx = fullCodePath.lastIndexOf("/");
11065            String subStr1 = fullCodePath.substring(0, eidx);
11066            int sidx = subStr1.lastIndexOf("/");
11067            cid = subStr1.substring(sidx+1, eidx);
11068            setMountPath(subStr1);
11069        }
11070
11071        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11072            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11073                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11074                    instructionSets, null);
11075            this.cid = cid;
11076            setMountPath(PackageHelper.getSdDir(cid));
11077        }
11078
11079        void createCopyFile() {
11080            cid = mInstallerService.allocateExternalStageCidLegacy();
11081        }
11082
11083        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11084            if (origin.staged) {
11085                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11086                cid = origin.cid;
11087                setMountPath(PackageHelper.getSdDir(cid));
11088                return PackageManager.INSTALL_SUCCEEDED;
11089            }
11090
11091            if (temp) {
11092                createCopyFile();
11093            } else {
11094                /*
11095                 * Pre-emptively destroy the container since it's destroyed if
11096                 * copying fails due to it existing anyway.
11097                 */
11098                PackageHelper.destroySdDir(cid);
11099            }
11100
11101            final String newMountPath = imcs.copyPackageToContainer(
11102                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11103                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11104
11105            if (newMountPath != null) {
11106                setMountPath(newMountPath);
11107                return PackageManager.INSTALL_SUCCEEDED;
11108            } else {
11109                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11110            }
11111        }
11112
11113        @Override
11114        String getCodePath() {
11115            return packagePath;
11116        }
11117
11118        @Override
11119        String getResourcePath() {
11120            return resourcePath;
11121        }
11122
11123        int doPreInstall(int status) {
11124            if (status != PackageManager.INSTALL_SUCCEEDED) {
11125                // Destroy container
11126                PackageHelper.destroySdDir(cid);
11127            } else {
11128                boolean mounted = PackageHelper.isContainerMounted(cid);
11129                if (!mounted) {
11130                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11131                            Process.SYSTEM_UID);
11132                    if (newMountPath != null) {
11133                        setMountPath(newMountPath);
11134                    } else {
11135                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11136                    }
11137                }
11138            }
11139            return status;
11140        }
11141
11142        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11143            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11144            String newMountPath = null;
11145            if (PackageHelper.isContainerMounted(cid)) {
11146                // Unmount the container
11147                if (!PackageHelper.unMountSdDir(cid)) {
11148                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11149                    return false;
11150                }
11151            }
11152            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11153                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11154                        " which might be stale. Will try to clean up.");
11155                // Clean up the stale container and proceed to recreate.
11156                if (!PackageHelper.destroySdDir(newCacheId)) {
11157                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11158                    return false;
11159                }
11160                // Successfully cleaned up stale container. Try to rename again.
11161                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11162                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11163                            + " inspite of cleaning it up.");
11164                    return false;
11165                }
11166            }
11167            if (!PackageHelper.isContainerMounted(newCacheId)) {
11168                Slog.w(TAG, "Mounting container " + newCacheId);
11169                newMountPath = PackageHelper.mountSdDir(newCacheId,
11170                        getEncryptKey(), Process.SYSTEM_UID);
11171            } else {
11172                newMountPath = PackageHelper.getSdDir(newCacheId);
11173            }
11174            if (newMountPath == null) {
11175                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11176                return false;
11177            }
11178            Log.i(TAG, "Succesfully renamed " + cid +
11179                    " to " + newCacheId +
11180                    " at new path: " + newMountPath);
11181            cid = newCacheId;
11182
11183            final File beforeCodeFile = new File(packagePath);
11184            setMountPath(newMountPath);
11185            final File afterCodeFile = new File(packagePath);
11186
11187            // Reflect the rename in scanned details
11188            pkg.codePath = afterCodeFile.getAbsolutePath();
11189            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11190                    pkg.baseCodePath);
11191            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11192                    pkg.splitCodePaths);
11193
11194            // Reflect the rename in app info
11195            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11196            pkg.applicationInfo.setCodePath(pkg.codePath);
11197            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11198            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11199            pkg.applicationInfo.setResourcePath(pkg.codePath);
11200            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11201            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11202
11203            return true;
11204        }
11205
11206        private void setMountPath(String mountPath) {
11207            final File mountFile = new File(mountPath);
11208
11209            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11210            if (monolithicFile.exists()) {
11211                packagePath = monolithicFile.getAbsolutePath();
11212                if (isFwdLocked()) {
11213                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11214                } else {
11215                    resourcePath = packagePath;
11216                }
11217            } else {
11218                packagePath = mountFile.getAbsolutePath();
11219                resourcePath = packagePath;
11220            }
11221        }
11222
11223        int doPostInstall(int status, int uid) {
11224            if (status != PackageManager.INSTALL_SUCCEEDED) {
11225                cleanUp();
11226            } else {
11227                final int groupOwner;
11228                final String protectedFile;
11229                if (isFwdLocked()) {
11230                    groupOwner = UserHandle.getSharedAppGid(uid);
11231                    protectedFile = RES_FILE_NAME;
11232                } else {
11233                    groupOwner = -1;
11234                    protectedFile = null;
11235                }
11236
11237                if (uid < Process.FIRST_APPLICATION_UID
11238                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11239                    Slog.e(TAG, "Failed to finalize " + cid);
11240                    PackageHelper.destroySdDir(cid);
11241                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11242                }
11243
11244                boolean mounted = PackageHelper.isContainerMounted(cid);
11245                if (!mounted) {
11246                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11247                }
11248            }
11249            return status;
11250        }
11251
11252        private void cleanUp() {
11253            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11254
11255            // Destroy secure container
11256            PackageHelper.destroySdDir(cid);
11257        }
11258
11259        private List<String> getAllCodePaths() {
11260            final File codeFile = new File(getCodePath());
11261            if (codeFile != null && codeFile.exists()) {
11262                try {
11263                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11264                    return pkg.getAllCodePaths();
11265                } catch (PackageParserException e) {
11266                    // Ignored; we tried our best
11267                }
11268            }
11269            return Collections.EMPTY_LIST;
11270        }
11271
11272        void cleanUpResourcesLI() {
11273            // Enumerate all code paths before deleting
11274            cleanUpResourcesLI(getAllCodePaths());
11275        }
11276
11277        private void cleanUpResourcesLI(List<String> allCodePaths) {
11278            cleanUp();
11279            removeDexFiles(allCodePaths, instructionSets);
11280        }
11281
11282        String getPackageName() {
11283            return getAsecPackageName(cid);
11284        }
11285
11286        boolean doPostDeleteLI(boolean delete) {
11287            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
11288            final List<String> allCodePaths = getAllCodePaths();
11289            boolean mounted = PackageHelper.isContainerMounted(cid);
11290            if (mounted) {
11291                // Unmount first
11292                if (PackageHelper.unMountSdDir(cid)) {
11293                    mounted = false;
11294                }
11295            }
11296            if (!mounted && delete) {
11297                cleanUpResourcesLI(allCodePaths);
11298            }
11299            return !mounted;
11300        }
11301
11302        @Override
11303        int doPreCopy() {
11304            if (isFwdLocked()) {
11305                if (!PackageHelper.fixSdPermissions(cid,
11306                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
11307                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11308                }
11309            }
11310
11311            return PackageManager.INSTALL_SUCCEEDED;
11312        }
11313
11314        @Override
11315        int doPostCopy(int uid) {
11316            if (isFwdLocked()) {
11317                if (uid < Process.FIRST_APPLICATION_UID
11318                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
11319                                RES_FILE_NAME)) {
11320                    Slog.e(TAG, "Failed to finalize " + cid);
11321                    PackageHelper.destroySdDir(cid);
11322                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11323                }
11324            }
11325
11326            return PackageManager.INSTALL_SUCCEEDED;
11327        }
11328    }
11329
11330    /**
11331     * Logic to handle movement of existing installed applications.
11332     */
11333    class MoveInstallArgs extends InstallArgs {
11334        private File codeFile;
11335        private File resourceFile;
11336
11337        /** New install */
11338        MoveInstallArgs(InstallParams params) {
11339            super(params.origin, params.move, params.observer, params.installFlags,
11340                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11341                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
11342        }
11343
11344        int copyApk(IMediaContainerService imcs, boolean temp) {
11345            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
11346                    + move.fromUuid + " to " + move.toUuid);
11347            synchronized (mInstaller) {
11348                if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName,
11349                        move.dataAppName, move.appId, move.seinfo) != 0) {
11350                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11351                }
11352            }
11353
11354            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
11355            resourceFile = codeFile;
11356            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
11357
11358            return PackageManager.INSTALL_SUCCEEDED;
11359        }
11360
11361        int doPreInstall(int status) {
11362            if (status != PackageManager.INSTALL_SUCCEEDED) {
11363                cleanUp(move.toUuid);
11364            }
11365            return status;
11366        }
11367
11368        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11369            if (status != PackageManager.INSTALL_SUCCEEDED) {
11370                cleanUp(move.toUuid);
11371                return false;
11372            }
11373
11374            // Reflect the move in app info
11375            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11376            pkg.applicationInfo.setCodePath(pkg.codePath);
11377            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11378            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11379            pkg.applicationInfo.setResourcePath(pkg.codePath);
11380            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11381            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11382
11383            return true;
11384        }
11385
11386        int doPostInstall(int status, int uid) {
11387            if (status == PackageManager.INSTALL_SUCCEEDED) {
11388                cleanUp(move.fromUuid);
11389            } else {
11390                cleanUp(move.toUuid);
11391            }
11392            return status;
11393        }
11394
11395        @Override
11396        String getCodePath() {
11397            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11398        }
11399
11400        @Override
11401        String getResourcePath() {
11402            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11403        }
11404
11405        private boolean cleanUp(String volumeUuid) {
11406            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
11407                    move.dataAppName);
11408            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
11409            synchronized (mInstallLock) {
11410                // Clean up both app data and code
11411                removeDataDirsLI(volumeUuid, move.packageName);
11412                if (codeFile.isDirectory()) {
11413                    mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11414                } else {
11415                    codeFile.delete();
11416                }
11417            }
11418            return true;
11419        }
11420
11421        void cleanUpResourcesLI() {
11422            throw new UnsupportedOperationException();
11423        }
11424
11425        boolean doPostDeleteLI(boolean delete) {
11426            throw new UnsupportedOperationException();
11427        }
11428    }
11429
11430    static String getAsecPackageName(String packageCid) {
11431        int idx = packageCid.lastIndexOf("-");
11432        if (idx == -1) {
11433            return packageCid;
11434        }
11435        return packageCid.substring(0, idx);
11436    }
11437
11438    // Utility method used to create code paths based on package name and available index.
11439    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
11440        String idxStr = "";
11441        int idx = 1;
11442        // Fall back to default value of idx=1 if prefix is not
11443        // part of oldCodePath
11444        if (oldCodePath != null) {
11445            String subStr = oldCodePath;
11446            // Drop the suffix right away
11447            if (suffix != null && subStr.endsWith(suffix)) {
11448                subStr = subStr.substring(0, subStr.length() - suffix.length());
11449            }
11450            // If oldCodePath already contains prefix find out the
11451            // ending index to either increment or decrement.
11452            int sidx = subStr.lastIndexOf(prefix);
11453            if (sidx != -1) {
11454                subStr = subStr.substring(sidx + prefix.length());
11455                if (subStr != null) {
11456                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
11457                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
11458                    }
11459                    try {
11460                        idx = Integer.parseInt(subStr);
11461                        if (idx <= 1) {
11462                            idx++;
11463                        } else {
11464                            idx--;
11465                        }
11466                    } catch(NumberFormatException e) {
11467                    }
11468                }
11469            }
11470        }
11471        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
11472        return prefix + idxStr;
11473    }
11474
11475    private File getNextCodePath(File targetDir, String packageName) {
11476        int suffix = 1;
11477        File result;
11478        do {
11479            result = new File(targetDir, packageName + "-" + suffix);
11480            suffix++;
11481        } while (result.exists());
11482        return result;
11483    }
11484
11485    // Utility method that returns the relative package path with respect
11486    // to the installation directory. Like say for /data/data/com.test-1.apk
11487    // string com.test-1 is returned.
11488    static String deriveCodePathName(String codePath) {
11489        if (codePath == null) {
11490            return null;
11491        }
11492        final File codeFile = new File(codePath);
11493        final String name = codeFile.getName();
11494        if (codeFile.isDirectory()) {
11495            return name;
11496        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
11497            final int lastDot = name.lastIndexOf('.');
11498            return name.substring(0, lastDot);
11499        } else {
11500            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11501            return null;
11502        }
11503    }
11504
11505    class PackageInstalledInfo {
11506        String name;
11507        int uid;
11508        // The set of users that originally had this package installed.
11509        int[] origUsers;
11510        // The set of users that now have this package installed.
11511        int[] newUsers;
11512        PackageParser.Package pkg;
11513        int returnCode;
11514        String returnMsg;
11515        PackageRemovedInfo removedInfo;
11516
11517        public void setError(int code, String msg) {
11518            returnCode = code;
11519            returnMsg = msg;
11520            Slog.w(TAG, msg);
11521        }
11522
11523        public void setError(String msg, PackageParserException e) {
11524            returnCode = e.error;
11525            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11526            Slog.w(TAG, msg, e);
11527        }
11528
11529        public void setError(String msg, PackageManagerException e) {
11530            returnCode = e.error;
11531            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11532            Slog.w(TAG, msg, e);
11533        }
11534
11535        // In some error cases we want to convey more info back to the observer
11536        String origPackage;
11537        String origPermission;
11538    }
11539
11540    /*
11541     * Install a non-existing package.
11542     */
11543    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11544            UserHandle user, String installerPackageName, String volumeUuid,
11545            PackageInstalledInfo res) {
11546        // Remember this for later, in case we need to rollback this install
11547        String pkgName = pkg.packageName;
11548
11549        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
11550        final boolean dataDirExists = Environment
11551                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists();
11552        synchronized(mPackages) {
11553            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
11554                // A package with the same name is already installed, though
11555                // it has been renamed to an older name.  The package we
11556                // are trying to install should be installed as an update to
11557                // the existing one, but that has not been requested, so bail.
11558                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11559                        + " without first uninstalling package running as "
11560                        + mSettings.mRenamedPackages.get(pkgName));
11561                return;
11562            }
11563            if (mPackages.containsKey(pkgName)) {
11564                // Don't allow installation over an existing package with the same name.
11565                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11566                        + " without first uninstalling.");
11567                return;
11568            }
11569        }
11570
11571        try {
11572            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
11573                    System.currentTimeMillis(), user);
11574
11575            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
11576            // delete the partially installed application. the data directory will have to be
11577            // restored if it was already existing
11578            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11579                // remove package from internal structures.  Note that we want deletePackageX to
11580                // delete the package data and cache directories that it created in
11581                // scanPackageLocked, unless those directories existed before we even tried to
11582                // install.
11583                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
11584                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
11585                                res.removedInfo, true);
11586            }
11587
11588        } catch (PackageManagerException e) {
11589            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11590        }
11591    }
11592
11593    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
11594        // Can't rotate keys during boot or if sharedUser.
11595        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
11596                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
11597            return false;
11598        }
11599        // app is using upgradeKeySets; make sure all are valid
11600        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11601        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
11602        for (int i = 0; i < upgradeKeySets.length; i++) {
11603            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
11604                Slog.wtf(TAG, "Package "
11605                         + (oldPs.name != null ? oldPs.name : "<null>")
11606                         + " contains upgrade-key-set reference to unknown key-set: "
11607                         + upgradeKeySets[i]
11608                         + " reverting to signatures check.");
11609                return false;
11610            }
11611        }
11612        return true;
11613    }
11614
11615    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
11616        // Upgrade keysets are being used.  Determine if new package has a superset of the
11617        // required keys.
11618        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
11619        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11620        for (int i = 0; i < upgradeKeySets.length; i++) {
11621            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
11622            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
11623                return true;
11624            }
11625        }
11626        return false;
11627    }
11628
11629    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11630            UserHandle user, String installerPackageName, String volumeUuid,
11631            PackageInstalledInfo res) {
11632        final PackageParser.Package oldPackage;
11633        final String pkgName = pkg.packageName;
11634        final int[] allUsers;
11635        final boolean[] perUserInstalled;
11636        final boolean weFroze;
11637
11638        // First find the old package info and check signatures
11639        synchronized(mPackages) {
11640            oldPackage = mPackages.get(pkgName);
11641            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
11642            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11643            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11644                if(!checkUpgradeKeySetLP(ps, pkg)) {
11645                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11646                            "New package not signed by keys specified by upgrade-keysets: "
11647                            + pkgName);
11648                    return;
11649                }
11650            } else {
11651                // default to original signature matching
11652                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
11653                    != PackageManager.SIGNATURE_MATCH) {
11654                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11655                            "New package has a different signature: " + pkgName);
11656                    return;
11657                }
11658            }
11659
11660            // In case of rollback, remember per-user/profile install state
11661            allUsers = sUserManager.getUserIds();
11662            perUserInstalled = new boolean[allUsers.length];
11663            for (int i = 0; i < allUsers.length; i++) {
11664                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11665            }
11666
11667            // Mark the app as frozen to prevent launching during the upgrade
11668            // process, and then kill all running instances
11669            if (!ps.frozen) {
11670                ps.frozen = true;
11671                weFroze = true;
11672            } else {
11673                weFroze = false;
11674            }
11675        }
11676
11677        // Now that we're guarded by frozen state, kill app during upgrade
11678        killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg");
11679
11680        try {
11681            boolean sysPkg = (isSystemApp(oldPackage));
11682            if (sysPkg) {
11683                replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11684                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11685            } else {
11686                replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11687                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11688            }
11689        } finally {
11690            // Regardless of success or failure of upgrade steps above, always
11691            // unfreeze the package if we froze it
11692            if (weFroze) {
11693                unfreezePackage(pkgName);
11694            }
11695        }
11696    }
11697
11698    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
11699            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11700            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11701            String volumeUuid, PackageInstalledInfo res) {
11702        String pkgName = deletedPackage.packageName;
11703        boolean deletedPkg = true;
11704        boolean updatedSettings = false;
11705
11706        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
11707                + deletedPackage);
11708        long origUpdateTime;
11709        if (pkg.mExtras != null) {
11710            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
11711        } else {
11712            origUpdateTime = 0;
11713        }
11714
11715        // First delete the existing package while retaining the data directory
11716        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
11717                res.removedInfo, true)) {
11718            // If the existing package wasn't successfully deleted
11719            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
11720            deletedPkg = false;
11721        } else {
11722            // Successfully deleted the old package; proceed with replace.
11723
11724            // If deleted package lived in a container, give users a chance to
11725            // relinquish resources before killing.
11726            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
11727                if (DEBUG_INSTALL) {
11728                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
11729                }
11730                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
11731                final ArrayList<String> pkgList = new ArrayList<String>(1);
11732                pkgList.add(deletedPackage.applicationInfo.packageName);
11733                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
11734            }
11735
11736            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
11737            try {
11738                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
11739                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
11740                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11741                        perUserInstalled, res, user);
11742                updatedSettings = true;
11743            } catch (PackageManagerException e) {
11744                res.setError("Package couldn't be installed in " + pkg.codePath, e);
11745            }
11746        }
11747
11748        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11749            // remove package from internal structures.  Note that we want deletePackageX to
11750            // delete the package data and cache directories that it created in
11751            // scanPackageLocked, unless those directories existed before we even tried to
11752            // install.
11753            if(updatedSettings) {
11754                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
11755                deletePackageLI(
11756                        pkgName, null, true, allUsers, perUserInstalled,
11757                        PackageManager.DELETE_KEEP_DATA,
11758                                res.removedInfo, true);
11759            }
11760            // Since we failed to install the new package we need to restore the old
11761            // package that we deleted.
11762            if (deletedPkg) {
11763                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
11764                File restoreFile = new File(deletedPackage.codePath);
11765                // Parse old package
11766                boolean oldExternal = isExternal(deletedPackage);
11767                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
11768                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
11769                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11770                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
11771                try {
11772                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
11773                } catch (PackageManagerException e) {
11774                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
11775                            + e.getMessage());
11776                    return;
11777                }
11778                // Restore of old package succeeded. Update permissions.
11779                // writer
11780                synchronized (mPackages) {
11781                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
11782                            UPDATE_PERMISSIONS_ALL);
11783                    // can downgrade to reader
11784                    mSettings.writeLPr();
11785                }
11786                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
11787            }
11788        }
11789    }
11790
11791    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
11792            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11793            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11794            String volumeUuid, PackageInstalledInfo res) {
11795        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
11796                + ", old=" + deletedPackage);
11797        boolean disabledSystem = false;
11798        boolean updatedSettings = false;
11799        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
11800        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
11801                != 0) {
11802            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11803        }
11804        String packageName = deletedPackage.packageName;
11805        if (packageName == null) {
11806            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11807                    "Attempt to delete null packageName.");
11808            return;
11809        }
11810        PackageParser.Package oldPkg;
11811        PackageSetting oldPkgSetting;
11812        // reader
11813        synchronized (mPackages) {
11814            oldPkg = mPackages.get(packageName);
11815            oldPkgSetting = mSettings.mPackages.get(packageName);
11816            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
11817                    (oldPkgSetting == null)) {
11818                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11819                        "Couldn't find package:" + packageName + " information");
11820                return;
11821            }
11822        }
11823
11824        res.removedInfo.uid = oldPkg.applicationInfo.uid;
11825        res.removedInfo.removedPackage = packageName;
11826        // Remove existing system package
11827        removePackageLI(oldPkgSetting, true);
11828        // writer
11829        synchronized (mPackages) {
11830            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
11831            if (!disabledSystem && deletedPackage != null) {
11832                // We didn't need to disable the .apk as a current system package,
11833                // which means we are replacing another update that is already
11834                // installed.  We need to make sure to delete the older one's .apk.
11835                res.removedInfo.args = createInstallArgsForExisting(0,
11836                        deletedPackage.applicationInfo.getCodePath(),
11837                        deletedPackage.applicationInfo.getResourcePath(),
11838                        getAppDexInstructionSets(deletedPackage.applicationInfo));
11839            } else {
11840                res.removedInfo.args = null;
11841            }
11842        }
11843
11844        // Successfully disabled the old package. Now proceed with re-installation
11845        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
11846
11847        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11848        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
11849
11850        PackageParser.Package newPackage = null;
11851        try {
11852            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
11853            if (newPackage.mExtras != null) {
11854                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
11855                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
11856                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
11857
11858                // is the update attempting to change shared user? that isn't going to work...
11859                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
11860                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
11861                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
11862                            + " to " + newPkgSetting.sharedUser);
11863                    updatedSettings = true;
11864                }
11865            }
11866
11867            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11868                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11869                        perUserInstalled, res, user);
11870                updatedSettings = true;
11871            }
11872
11873        } catch (PackageManagerException e) {
11874            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11875        }
11876
11877        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11878            // Re installation failed. Restore old information
11879            // Remove new pkg information
11880            if (newPackage != null) {
11881                removeInstalledPackageLI(newPackage, true);
11882            }
11883            // Add back the old system package
11884            try {
11885                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
11886            } catch (PackageManagerException e) {
11887                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
11888            }
11889            // Restore the old system information in Settings
11890            synchronized (mPackages) {
11891                if (disabledSystem) {
11892                    mSettings.enableSystemPackageLPw(packageName);
11893                }
11894                if (updatedSettings) {
11895                    mSettings.setInstallerPackageName(packageName,
11896                            oldPkgSetting.installerPackageName);
11897                }
11898                mSettings.writeLPr();
11899            }
11900        }
11901    }
11902
11903    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
11904            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
11905            UserHandle user) {
11906        String pkgName = newPackage.packageName;
11907        synchronized (mPackages) {
11908            //write settings. the installStatus will be incomplete at this stage.
11909            //note that the new package setting would have already been
11910            //added to mPackages. It hasn't been persisted yet.
11911            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
11912            mSettings.writeLPr();
11913        }
11914
11915        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
11916
11917        synchronized (mPackages) {
11918            updatePermissionsLPw(newPackage.packageName, newPackage,
11919                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
11920                            ? UPDATE_PERMISSIONS_ALL : 0));
11921            // For system-bundled packages, we assume that installing an upgraded version
11922            // of the package implies that the user actually wants to run that new code,
11923            // so we enable the package.
11924            PackageSetting ps = mSettings.mPackages.get(pkgName);
11925            if (ps != null) {
11926                if (isSystemApp(newPackage)) {
11927                    // NB: implicit assumption that system package upgrades apply to all users
11928                    if (DEBUG_INSTALL) {
11929                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
11930                    }
11931                    if (res.origUsers != null) {
11932                        for (int userHandle : res.origUsers) {
11933                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
11934                                    userHandle, installerPackageName);
11935                        }
11936                    }
11937                    // Also convey the prior install/uninstall state
11938                    if (allUsers != null && perUserInstalled != null) {
11939                        for (int i = 0; i < allUsers.length; i++) {
11940                            if (DEBUG_INSTALL) {
11941                                Slog.d(TAG, "    user " + allUsers[i]
11942                                        + " => " + perUserInstalled[i]);
11943                            }
11944                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
11945                        }
11946                        // these install state changes will be persisted in the
11947                        // upcoming call to mSettings.writeLPr().
11948                    }
11949                }
11950                // It's implied that when a user requests installation, they want the app to be
11951                // installed and enabled.
11952                int userId = user.getIdentifier();
11953                if (userId != UserHandle.USER_ALL) {
11954                    ps.setInstalled(true, userId);
11955                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
11956                }
11957            }
11958            res.name = pkgName;
11959            res.uid = newPackage.applicationInfo.uid;
11960            res.pkg = newPackage;
11961            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
11962            mSettings.setInstallerPackageName(pkgName, installerPackageName);
11963            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11964            //to update install status
11965            mSettings.writeLPr();
11966        }
11967    }
11968
11969    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
11970        final int installFlags = args.installFlags;
11971        final String installerPackageName = args.installerPackageName;
11972        final String volumeUuid = args.volumeUuid;
11973        final File tmpPackageFile = new File(args.getCodePath());
11974        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
11975        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
11976                || (args.volumeUuid != null));
11977        boolean replace = false;
11978        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
11979        if (args.move != null) {
11980            // moving a complete application; perfom an initial scan on the new install location
11981            scanFlags |= SCAN_INITIAL;
11982        }
11983        // Result object to be returned
11984        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11985
11986        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
11987        // Retrieve PackageSettings and parse package
11988        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
11989                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
11990                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11991        PackageParser pp = new PackageParser();
11992        pp.setSeparateProcesses(mSeparateProcesses);
11993        pp.setDisplayMetrics(mMetrics);
11994
11995        final PackageParser.Package pkg;
11996        try {
11997            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
11998        } catch (PackageParserException e) {
11999            res.setError("Failed parse during installPackageLI", e);
12000            return;
12001        }
12002
12003        // Mark that we have an install time CPU ABI override.
12004        pkg.cpuAbiOverride = args.abiOverride;
12005
12006        String pkgName = res.name = pkg.packageName;
12007        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12008            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12009                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12010                return;
12011            }
12012        }
12013
12014        try {
12015            pp.collectCertificates(pkg, parseFlags);
12016            pp.collectManifestDigest(pkg);
12017        } catch (PackageParserException e) {
12018            res.setError("Failed collect during installPackageLI", e);
12019            return;
12020        }
12021
12022        /* If the installer passed in a manifest digest, compare it now. */
12023        if (args.manifestDigest != null) {
12024            if (DEBUG_INSTALL) {
12025                final String parsedManifest = pkg.manifestDigest == null ? "null"
12026                        : pkg.manifestDigest.toString();
12027                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
12028                        + parsedManifest);
12029            }
12030
12031            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
12032                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
12033                return;
12034            }
12035        } else if (DEBUG_INSTALL) {
12036            final String parsedManifest = pkg.manifestDigest == null
12037                    ? "null" : pkg.manifestDigest.toString();
12038            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
12039        }
12040
12041        // Get rid of all references to package scan path via parser.
12042        pp = null;
12043        String oldCodePath = null;
12044        boolean systemApp = false;
12045        synchronized (mPackages) {
12046            // Check if installing already existing package
12047            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12048                String oldName = mSettings.mRenamedPackages.get(pkgName);
12049                if (pkg.mOriginalPackages != null
12050                        && pkg.mOriginalPackages.contains(oldName)
12051                        && mPackages.containsKey(oldName)) {
12052                    // This package is derived from an original package,
12053                    // and this device has been updating from that original
12054                    // name.  We must continue using the original name, so
12055                    // rename the new package here.
12056                    pkg.setPackageName(oldName);
12057                    pkgName = pkg.packageName;
12058                    replace = true;
12059                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12060                            + oldName + " pkgName=" + pkgName);
12061                } else if (mPackages.containsKey(pkgName)) {
12062                    // This package, under its official name, already exists
12063                    // on the device; we should replace it.
12064                    replace = true;
12065                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12066                }
12067
12068                // Prevent apps opting out from runtime permissions
12069                if (replace) {
12070                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12071                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12072                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12073                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12074                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12075                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12076                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12077                                        + " doesn't support runtime permissions but the old"
12078                                        + " target SDK " + oldTargetSdk + " does.");
12079                        return;
12080                    }
12081                }
12082            }
12083
12084            PackageSetting ps = mSettings.mPackages.get(pkgName);
12085            if (ps != null) {
12086                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12087
12088                // Quick sanity check that we're signed correctly if updating;
12089                // we'll check this again later when scanning, but we want to
12090                // bail early here before tripping over redefined permissions.
12091                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12092                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12093                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12094                                + pkg.packageName + " upgrade keys do not match the "
12095                                + "previously installed version");
12096                        return;
12097                    }
12098                } else {
12099                    try {
12100                        verifySignaturesLP(ps, pkg);
12101                    } catch (PackageManagerException e) {
12102                        res.setError(e.error, e.getMessage());
12103                        return;
12104                    }
12105                }
12106
12107                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12108                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12109                    systemApp = (ps.pkg.applicationInfo.flags &
12110                            ApplicationInfo.FLAG_SYSTEM) != 0;
12111                }
12112                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12113            }
12114
12115            // Check whether the newly-scanned package wants to define an already-defined perm
12116            int N = pkg.permissions.size();
12117            for (int i = N-1; i >= 0; i--) {
12118                PackageParser.Permission perm = pkg.permissions.get(i);
12119                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12120                if (bp != null) {
12121                    // If the defining package is signed with our cert, it's okay.  This
12122                    // also includes the "updating the same package" case, of course.
12123                    // "updating same package" could also involve key-rotation.
12124                    final boolean sigsOk;
12125                    if (bp.sourcePackage.equals(pkg.packageName)
12126                            && (bp.packageSetting instanceof PackageSetting)
12127                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12128                                    scanFlags))) {
12129                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12130                    } else {
12131                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12132                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12133                    }
12134                    if (!sigsOk) {
12135                        // If the owning package is the system itself, we log but allow
12136                        // install to proceed; we fail the install on all other permission
12137                        // redefinitions.
12138                        if (!bp.sourcePackage.equals("android")) {
12139                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12140                                    + pkg.packageName + " attempting to redeclare permission "
12141                                    + perm.info.name + " already owned by " + bp.sourcePackage);
12142                            res.origPermission = perm.info.name;
12143                            res.origPackage = bp.sourcePackage;
12144                            return;
12145                        } else {
12146                            Slog.w(TAG, "Package " + pkg.packageName
12147                                    + " attempting to redeclare system permission "
12148                                    + perm.info.name + "; ignoring new declaration");
12149                            pkg.permissions.remove(i);
12150                        }
12151                    }
12152                }
12153            }
12154
12155        }
12156
12157        if (systemApp && onExternal) {
12158            // Disable updates to system apps on sdcard
12159            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12160                    "Cannot install updates to system apps on sdcard");
12161            return;
12162        }
12163
12164        if (args.move != null) {
12165            // We did an in-place move, so dex is ready to roll
12166            scanFlags |= SCAN_NO_DEX;
12167            scanFlags |= SCAN_MOVE;
12168        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
12169            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
12170            scanFlags |= SCAN_NO_DEX;
12171
12172            try {
12173                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
12174                        true /* extract libs */);
12175            } catch (PackageManagerException pme) {
12176                Slog.e(TAG, "Error deriving application ABI", pme);
12177                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
12178                return;
12179            }
12180
12181            // Run dexopt before old package gets removed, to minimize time when app is unavailable
12182            int result = mPackageDexOptimizer
12183                    .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */,
12184                            false /* defer */, false /* inclDependencies */);
12185            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
12186                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
12187                return;
12188            }
12189        }
12190
12191        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
12192            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
12193            return;
12194        }
12195
12196        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
12197
12198        if (replace) {
12199            replacePackageLI(pkg, parseFlags, scanFlags, args.user,
12200                    installerPackageName, volumeUuid, res);
12201        } else {
12202            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
12203                    args.user, installerPackageName, volumeUuid, res);
12204        }
12205        synchronized (mPackages) {
12206            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12207            if (ps != null) {
12208                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12209            }
12210        }
12211    }
12212
12213    private void startIntentFilterVerifications(int userId, boolean replacing,
12214            PackageParser.Package pkg) {
12215        if (mIntentFilterVerifierComponent == null) {
12216            Slog.w(TAG, "No IntentFilter verification will not be done as "
12217                    + "there is no IntentFilterVerifier available!");
12218            return;
12219        }
12220
12221        final int verifierUid = getPackageUid(
12222                mIntentFilterVerifierComponent.getPackageName(),
12223                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
12224
12225        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
12226        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
12227        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
12228        mHandler.sendMessage(msg);
12229    }
12230
12231    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
12232            PackageParser.Package pkg) {
12233        int size = pkg.activities.size();
12234        if (size == 0) {
12235            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12236                    "No activity, so no need to verify any IntentFilter!");
12237            return;
12238        }
12239
12240        final boolean hasDomainURLs = hasDomainURLs(pkg);
12241        if (!hasDomainURLs) {
12242            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12243                    "No domain URLs, so no need to verify any IntentFilter!");
12244            return;
12245        }
12246
12247        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
12248                + " if any IntentFilter from the " + size
12249                + " Activities needs verification ...");
12250
12251        int count = 0;
12252        final String packageName = pkg.packageName;
12253
12254        synchronized (mPackages) {
12255            // If this is a new install and we see that we've already run verification for this
12256            // package, we have nothing to do: it means the state was restored from backup.
12257            if (!replacing) {
12258                IntentFilterVerificationInfo ivi =
12259                        mSettings.getIntentFilterVerificationLPr(packageName);
12260                if (ivi != null) {
12261                    if (DEBUG_DOMAIN_VERIFICATION) {
12262                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
12263                                + ivi.getStatusString());
12264                    }
12265                    return;
12266                }
12267            }
12268
12269            // If any filters need to be verified, then all need to be.
12270            boolean needToVerify = false;
12271            for (PackageParser.Activity a : pkg.activities) {
12272                for (ActivityIntentInfo filter : a.intents) {
12273                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
12274                        if (DEBUG_DOMAIN_VERIFICATION) {
12275                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
12276                        }
12277                        needToVerify = true;
12278                        break;
12279                    }
12280                }
12281            }
12282
12283            if (needToVerify) {
12284                final int verificationId = mIntentFilterVerificationToken++;
12285                for (PackageParser.Activity a : pkg.activities) {
12286                    for (ActivityIntentInfo filter : a.intents) {
12287                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
12288                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12289                                    "Verification needed for IntentFilter:" + filter.toString());
12290                            mIntentFilterVerifier.addOneIntentFilterVerification(
12291                                    verifierUid, userId, verificationId, filter, packageName);
12292                            count++;
12293                        }
12294                    }
12295                }
12296            }
12297        }
12298
12299        if (count > 0) {
12300            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
12301                    + " IntentFilter verification" + (count > 1 ? "s" : "")
12302                    +  " for userId:" + userId);
12303            mIntentFilterVerifier.startVerifications(userId);
12304        } else {
12305            if (DEBUG_DOMAIN_VERIFICATION) {
12306                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
12307            }
12308        }
12309    }
12310
12311    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
12312        final ComponentName cn  = filter.activity.getComponentName();
12313        final String packageName = cn.getPackageName();
12314
12315        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
12316                packageName);
12317        if (ivi == null) {
12318            return true;
12319        }
12320        int status = ivi.getStatus();
12321        switch (status) {
12322            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
12323            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
12324                return true;
12325
12326            default:
12327                // Nothing to do
12328                return false;
12329        }
12330    }
12331
12332    private static boolean isMultiArch(PackageSetting ps) {
12333        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12334    }
12335
12336    private static boolean isMultiArch(ApplicationInfo info) {
12337        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12338    }
12339
12340    private static boolean isExternal(PackageParser.Package pkg) {
12341        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12342    }
12343
12344    private static boolean isExternal(PackageSetting ps) {
12345        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12346    }
12347
12348    private static boolean isExternal(ApplicationInfo info) {
12349        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12350    }
12351
12352    private static boolean isSystemApp(PackageParser.Package pkg) {
12353        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
12354    }
12355
12356    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
12357        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
12358    }
12359
12360    private static boolean hasDomainURLs(PackageParser.Package pkg) {
12361        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
12362    }
12363
12364    private static boolean isSystemApp(PackageSetting ps) {
12365        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
12366    }
12367
12368    private static boolean isUpdatedSystemApp(PackageSetting ps) {
12369        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
12370    }
12371
12372    private int packageFlagsToInstallFlags(PackageSetting ps) {
12373        int installFlags = 0;
12374        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
12375            // This existing package was an external ASEC install when we have
12376            // the external flag without a UUID
12377            installFlags |= PackageManager.INSTALL_EXTERNAL;
12378        }
12379        if (ps.isForwardLocked()) {
12380            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12381        }
12382        return installFlags;
12383    }
12384
12385    private void deleteTempPackageFiles() {
12386        final FilenameFilter filter = new FilenameFilter() {
12387            public boolean accept(File dir, String name) {
12388                return name.startsWith("vmdl") && name.endsWith(".tmp");
12389            }
12390        };
12391        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
12392            file.delete();
12393        }
12394    }
12395
12396    @Override
12397    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
12398            int flags) {
12399        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
12400                flags);
12401    }
12402
12403    @Override
12404    public void deletePackage(final String packageName,
12405            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
12406        mContext.enforceCallingOrSelfPermission(
12407                android.Manifest.permission.DELETE_PACKAGES, null);
12408        Preconditions.checkNotNull(packageName);
12409        Preconditions.checkNotNull(observer);
12410        final int uid = Binder.getCallingUid();
12411        if (UserHandle.getUserId(uid) != userId) {
12412            mContext.enforceCallingPermission(
12413                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
12414                    "deletePackage for user " + userId);
12415        }
12416        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
12417            try {
12418                observer.onPackageDeleted(packageName,
12419                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
12420            } catch (RemoteException re) {
12421            }
12422            return;
12423        }
12424
12425        boolean uninstallBlocked = false;
12426        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
12427            int[] users = sUserManager.getUserIds();
12428            for (int i = 0; i < users.length; ++i) {
12429                if (getBlockUninstallForUser(packageName, users[i])) {
12430                    uninstallBlocked = true;
12431                    break;
12432                }
12433            }
12434        } else {
12435            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
12436        }
12437        if (uninstallBlocked) {
12438            try {
12439                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
12440                        null);
12441            } catch (RemoteException re) {
12442            }
12443            return;
12444        }
12445
12446        if (DEBUG_REMOVE) {
12447            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
12448        }
12449        // Queue up an async operation since the package deletion may take a little while.
12450        mHandler.post(new Runnable() {
12451            public void run() {
12452                mHandler.removeCallbacks(this);
12453                final int returnCode = deletePackageX(packageName, userId, flags);
12454                if (observer != null) {
12455                    try {
12456                        observer.onPackageDeleted(packageName, returnCode, null);
12457                    } catch (RemoteException e) {
12458                        Log.i(TAG, "Observer no longer exists.");
12459                    } //end catch
12460                } //end if
12461            } //end run
12462        });
12463    }
12464
12465    private boolean isPackageDeviceAdmin(String packageName, int userId) {
12466        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12467                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12468        try {
12469            if (dpm != null) {
12470                if (dpm.isDeviceOwner(packageName)) {
12471                    return true;
12472                }
12473                int[] users;
12474                if (userId == UserHandle.USER_ALL) {
12475                    users = sUserManager.getUserIds();
12476                } else {
12477                    users = new int[]{userId};
12478                }
12479                for (int i = 0; i < users.length; ++i) {
12480                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
12481                        return true;
12482                    }
12483                }
12484            }
12485        } catch (RemoteException e) {
12486        }
12487        return false;
12488    }
12489
12490    /**
12491     *  This method is an internal method that could be get invoked either
12492     *  to delete an installed package or to clean up a failed installation.
12493     *  After deleting an installed package, a broadcast is sent to notify any
12494     *  listeners that the package has been installed. For cleaning up a failed
12495     *  installation, the broadcast is not necessary since the package's
12496     *  installation wouldn't have sent the initial broadcast either
12497     *  The key steps in deleting a package are
12498     *  deleting the package information in internal structures like mPackages,
12499     *  deleting the packages base directories through installd
12500     *  updating mSettings to reflect current status
12501     *  persisting settings for later use
12502     *  sending a broadcast if necessary
12503     */
12504    private int deletePackageX(String packageName, int userId, int flags) {
12505        final PackageRemovedInfo info = new PackageRemovedInfo();
12506        final boolean res;
12507
12508        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
12509                ? UserHandle.ALL : new UserHandle(userId);
12510
12511        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
12512            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
12513            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
12514        }
12515
12516        boolean removedForAllUsers = false;
12517        boolean systemUpdate = false;
12518
12519        // for the uninstall-updates case and restricted profiles, remember the per-
12520        // userhandle installed state
12521        int[] allUsers;
12522        boolean[] perUserInstalled;
12523        synchronized (mPackages) {
12524            PackageSetting ps = mSettings.mPackages.get(packageName);
12525            allUsers = sUserManager.getUserIds();
12526            perUserInstalled = new boolean[allUsers.length];
12527            for (int i = 0; i < allUsers.length; i++) {
12528                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12529            }
12530        }
12531
12532        synchronized (mInstallLock) {
12533            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
12534            res = deletePackageLI(packageName, removeForUser,
12535                    true, allUsers, perUserInstalled,
12536                    flags | REMOVE_CHATTY, info, true);
12537            systemUpdate = info.isRemovedPackageSystemUpdate;
12538            if (res && !systemUpdate && mPackages.get(packageName) == null) {
12539                removedForAllUsers = true;
12540            }
12541            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
12542                    + " removedForAllUsers=" + removedForAllUsers);
12543        }
12544
12545        if (res) {
12546            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
12547
12548            // If the removed package was a system update, the old system package
12549            // was re-enabled; we need to broadcast this information
12550            if (systemUpdate) {
12551                Bundle extras = new Bundle(1);
12552                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
12553                        ? info.removedAppId : info.uid);
12554                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12555
12556                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
12557                        extras, null, null, null);
12558                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
12559                        extras, null, null, null);
12560                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
12561                        null, packageName, null, null);
12562            }
12563        }
12564        // Force a gc here.
12565        Runtime.getRuntime().gc();
12566        // Delete the resources here after sending the broadcast to let
12567        // other processes clean up before deleting resources.
12568        if (info.args != null) {
12569            synchronized (mInstallLock) {
12570                info.args.doPostDeleteLI(true);
12571            }
12572        }
12573
12574        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
12575    }
12576
12577    class PackageRemovedInfo {
12578        String removedPackage;
12579        int uid = -1;
12580        int removedAppId = -1;
12581        int[] removedUsers = null;
12582        boolean isRemovedPackageSystemUpdate = false;
12583        // Clean up resources deleted packages.
12584        InstallArgs args = null;
12585
12586        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
12587            Bundle extras = new Bundle(1);
12588            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
12589            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
12590            if (replacing) {
12591                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12592            }
12593            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
12594            if (removedPackage != null) {
12595                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
12596                        extras, null, null, removedUsers);
12597                if (fullRemove && !replacing) {
12598                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
12599                            extras, null, null, removedUsers);
12600                }
12601            }
12602            if (removedAppId >= 0) {
12603                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
12604                        removedUsers);
12605            }
12606        }
12607    }
12608
12609    /*
12610     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
12611     * flag is not set, the data directory is removed as well.
12612     * make sure this flag is set for partially installed apps. If not its meaningless to
12613     * delete a partially installed application.
12614     */
12615    private void removePackageDataLI(PackageSetting ps,
12616            int[] allUserHandles, boolean[] perUserInstalled,
12617            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
12618        String packageName = ps.name;
12619        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
12620        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
12621        // Retrieve object to delete permissions for shared user later on
12622        final PackageSetting deletedPs;
12623        // reader
12624        synchronized (mPackages) {
12625            deletedPs = mSettings.mPackages.get(packageName);
12626            if (outInfo != null) {
12627                outInfo.removedPackage = packageName;
12628                outInfo.removedUsers = deletedPs != null
12629                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
12630                        : null;
12631            }
12632        }
12633        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12634            removeDataDirsLI(ps.volumeUuid, packageName);
12635            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
12636        }
12637        // writer
12638        synchronized (mPackages) {
12639            if (deletedPs != null) {
12640                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12641                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
12642                    clearDefaultBrowserIfNeeded(packageName);
12643                    if (outInfo != null) {
12644                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
12645                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
12646                    }
12647                    updatePermissionsLPw(deletedPs.name, null, 0);
12648                    if (deletedPs.sharedUser != null) {
12649                        // Remove permissions associated with package. Since runtime
12650                        // permissions are per user we have to kill the removed package
12651                        // or packages running under the shared user of the removed
12652                        // package if revoking the permissions requested only by the removed
12653                        // package is successful and this causes a change in gids.
12654                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12655                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
12656                                    userId);
12657                            if (userIdToKill == UserHandle.USER_ALL
12658                                    || userIdToKill >= UserHandle.USER_OWNER) {
12659                                // If gids changed for this user, kill all affected packages.
12660                                mHandler.post(new Runnable() {
12661                                    @Override
12662                                    public void run() {
12663                                        // This has to happen with no lock held.
12664                                        killSettingPackagesForUser(deletedPs, userIdToKill,
12665                                                KILL_APP_REASON_GIDS_CHANGED);
12666                                    }
12667                                });
12668                            break;
12669                            }
12670                        }
12671                    }
12672                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
12673                }
12674                // make sure to preserve per-user disabled state if this removal was just
12675                // a downgrade of a system app to the factory package
12676                if (allUserHandles != null && perUserInstalled != null) {
12677                    if (DEBUG_REMOVE) {
12678                        Slog.d(TAG, "Propagating install state across downgrade");
12679                    }
12680                    for (int i = 0; i < allUserHandles.length; i++) {
12681                        if (DEBUG_REMOVE) {
12682                            Slog.d(TAG, "    user " + allUserHandles[i]
12683                                    + " => " + perUserInstalled[i]);
12684                        }
12685                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12686                    }
12687                }
12688            }
12689            // can downgrade to reader
12690            if (writeSettings) {
12691                // Save settings now
12692                mSettings.writeLPr();
12693            }
12694        }
12695        if (outInfo != null) {
12696            // A user ID was deleted here. Go through all users and remove it
12697            // from KeyStore.
12698            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
12699        }
12700    }
12701
12702    static boolean locationIsPrivileged(File path) {
12703        try {
12704            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
12705                    .getCanonicalPath();
12706            return path.getCanonicalPath().startsWith(privilegedAppDir);
12707        } catch (IOException e) {
12708            Slog.e(TAG, "Unable to access code path " + path);
12709        }
12710        return false;
12711    }
12712
12713    /*
12714     * Tries to delete system package.
12715     */
12716    private boolean deleteSystemPackageLI(PackageSetting newPs,
12717            int[] allUserHandles, boolean[] perUserInstalled,
12718            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
12719        final boolean applyUserRestrictions
12720                = (allUserHandles != null) && (perUserInstalled != null);
12721        PackageSetting disabledPs = null;
12722        // Confirm if the system package has been updated
12723        // An updated system app can be deleted. This will also have to restore
12724        // the system pkg from system partition
12725        // reader
12726        synchronized (mPackages) {
12727            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
12728        }
12729        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
12730                + " disabledPs=" + disabledPs);
12731        if (disabledPs == null) {
12732            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
12733            return false;
12734        } else if (DEBUG_REMOVE) {
12735            Slog.d(TAG, "Deleting system pkg from data partition");
12736        }
12737        if (DEBUG_REMOVE) {
12738            if (applyUserRestrictions) {
12739                Slog.d(TAG, "Remembering install states:");
12740                for (int i = 0; i < allUserHandles.length; i++) {
12741                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
12742                }
12743            }
12744        }
12745        // Delete the updated package
12746        outInfo.isRemovedPackageSystemUpdate = true;
12747        if (disabledPs.versionCode < newPs.versionCode) {
12748            // Delete data for downgrades
12749            flags &= ~PackageManager.DELETE_KEEP_DATA;
12750        } else {
12751            // Preserve data by setting flag
12752            flags |= PackageManager.DELETE_KEEP_DATA;
12753        }
12754        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
12755                allUserHandles, perUserInstalled, outInfo, writeSettings);
12756        if (!ret) {
12757            return false;
12758        }
12759        // writer
12760        synchronized (mPackages) {
12761            // Reinstate the old system package
12762            mSettings.enableSystemPackageLPw(newPs.name);
12763            // Remove any native libraries from the upgraded package.
12764            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
12765        }
12766        // Install the system package
12767        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
12768        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
12769        if (locationIsPrivileged(disabledPs.codePath)) {
12770            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12771        }
12772
12773        final PackageParser.Package newPkg;
12774        try {
12775            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
12776        } catch (PackageManagerException e) {
12777            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
12778            return false;
12779        }
12780
12781        // writer
12782        synchronized (mPackages) {
12783            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
12784            updatePermissionsLPw(newPkg.packageName, newPkg,
12785                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
12786            if (applyUserRestrictions) {
12787                if (DEBUG_REMOVE) {
12788                    Slog.d(TAG, "Propagating install state across reinstall");
12789                }
12790                for (int i = 0; i < allUserHandles.length; i++) {
12791                    if (DEBUG_REMOVE) {
12792                        Slog.d(TAG, "    user " + allUserHandles[i]
12793                                + " => " + perUserInstalled[i]);
12794                    }
12795                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12796                }
12797                // Regardless of writeSettings we need to ensure that this restriction
12798                // state propagation is persisted
12799                mSettings.writeAllUsersPackageRestrictionsLPr();
12800            }
12801            // can downgrade to reader here
12802            if (writeSettings) {
12803                mSettings.writeLPr();
12804            }
12805        }
12806        return true;
12807    }
12808
12809    private boolean deleteInstalledPackageLI(PackageSetting ps,
12810            boolean deleteCodeAndResources, int flags,
12811            int[] allUserHandles, boolean[] perUserInstalled,
12812            PackageRemovedInfo outInfo, boolean writeSettings) {
12813        if (outInfo != null) {
12814            outInfo.uid = ps.appId;
12815        }
12816
12817        // Delete package data from internal structures and also remove data if flag is set
12818        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
12819
12820        // Delete application code and resources
12821        if (deleteCodeAndResources && (outInfo != null)) {
12822            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
12823                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
12824            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
12825        }
12826        return true;
12827    }
12828
12829    @Override
12830    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
12831            int userId) {
12832        mContext.enforceCallingOrSelfPermission(
12833                android.Manifest.permission.DELETE_PACKAGES, null);
12834        synchronized (mPackages) {
12835            PackageSetting ps = mSettings.mPackages.get(packageName);
12836            if (ps == null) {
12837                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
12838                return false;
12839            }
12840            if (!ps.getInstalled(userId)) {
12841                // Can't block uninstall for an app that is not installed or enabled.
12842                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
12843                return false;
12844            }
12845            ps.setBlockUninstall(blockUninstall, userId);
12846            mSettings.writePackageRestrictionsLPr(userId);
12847        }
12848        return true;
12849    }
12850
12851    @Override
12852    public boolean getBlockUninstallForUser(String packageName, int userId) {
12853        synchronized (mPackages) {
12854            PackageSetting ps = mSettings.mPackages.get(packageName);
12855            if (ps == null) {
12856                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
12857                return false;
12858            }
12859            return ps.getBlockUninstall(userId);
12860        }
12861    }
12862
12863    /*
12864     * This method handles package deletion in general
12865     */
12866    private boolean deletePackageLI(String packageName, UserHandle user,
12867            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
12868            int flags, PackageRemovedInfo outInfo,
12869            boolean writeSettings) {
12870        if (packageName == null) {
12871            Slog.w(TAG, "Attempt to delete null packageName.");
12872            return false;
12873        }
12874        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
12875        PackageSetting ps;
12876        boolean dataOnly = false;
12877        int removeUser = -1;
12878        int appId = -1;
12879        synchronized (mPackages) {
12880            ps = mSettings.mPackages.get(packageName);
12881            if (ps == null) {
12882                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12883                return false;
12884            }
12885            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
12886                    && user.getIdentifier() != UserHandle.USER_ALL) {
12887                // The caller is asking that the package only be deleted for a single
12888                // user.  To do this, we just mark its uninstalled state and delete
12889                // its data.  If this is a system app, we only allow this to happen if
12890                // they have set the special DELETE_SYSTEM_APP which requests different
12891                // semantics than normal for uninstalling system apps.
12892                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
12893                ps.setUserState(user.getIdentifier(),
12894                        COMPONENT_ENABLED_STATE_DEFAULT,
12895                        false, //installed
12896                        true,  //stopped
12897                        true,  //notLaunched
12898                        false, //hidden
12899                        null, null, null,
12900                        false, // blockUninstall
12901                        INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
12902                if (!isSystemApp(ps)) {
12903                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
12904                        // Other user still have this package installed, so all
12905                        // we need to do is clear this user's data and save that
12906                        // it is uninstalled.
12907                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
12908                        removeUser = user.getIdentifier();
12909                        appId = ps.appId;
12910                        scheduleWritePackageRestrictionsLocked(removeUser);
12911                    } else {
12912                        // We need to set it back to 'installed' so the uninstall
12913                        // broadcasts will be sent correctly.
12914                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
12915                        ps.setInstalled(true, user.getIdentifier());
12916                    }
12917                } else {
12918                    // This is a system app, so we assume that the
12919                    // other users still have this package installed, so all
12920                    // we need to do is clear this user's data and save that
12921                    // it is uninstalled.
12922                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
12923                    removeUser = user.getIdentifier();
12924                    appId = ps.appId;
12925                    scheduleWritePackageRestrictionsLocked(removeUser);
12926                }
12927            }
12928        }
12929
12930        if (removeUser >= 0) {
12931            // From above, we determined that we are deleting this only
12932            // for a single user.  Continue the work here.
12933            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
12934            if (outInfo != null) {
12935                outInfo.removedPackage = packageName;
12936                outInfo.removedAppId = appId;
12937                outInfo.removedUsers = new int[] {removeUser};
12938            }
12939            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
12940            removeKeystoreDataIfNeeded(removeUser, appId);
12941            schedulePackageCleaning(packageName, removeUser, false);
12942            synchronized (mPackages) {
12943                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
12944                    scheduleWritePackageRestrictionsLocked(removeUser);
12945                }
12946                revokeRuntimePermissionsAndClearAllFlagsLocked(ps.getPermissionsState(),
12947                        removeUser);
12948            }
12949            return true;
12950        }
12951
12952        if (dataOnly) {
12953            // Delete application data first
12954            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
12955            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
12956            return true;
12957        }
12958
12959        boolean ret = false;
12960        if (isSystemApp(ps)) {
12961            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
12962            // When an updated system application is deleted we delete the existing resources as well and
12963            // fall back to existing code in system partition
12964            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
12965                    flags, outInfo, writeSettings);
12966        } else {
12967            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
12968            // Kill application pre-emptively especially for apps on sd.
12969            killApplication(packageName, ps.appId, "uninstall pkg");
12970            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
12971                    allUserHandles, perUserInstalled,
12972                    outInfo, writeSettings);
12973        }
12974
12975        return ret;
12976    }
12977
12978    private final class ClearStorageConnection implements ServiceConnection {
12979        IMediaContainerService mContainerService;
12980
12981        @Override
12982        public void onServiceConnected(ComponentName name, IBinder service) {
12983            synchronized (this) {
12984                mContainerService = IMediaContainerService.Stub.asInterface(service);
12985                notifyAll();
12986            }
12987        }
12988
12989        @Override
12990        public void onServiceDisconnected(ComponentName name) {
12991        }
12992    }
12993
12994    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
12995        final boolean mounted;
12996        if (Environment.isExternalStorageEmulated()) {
12997            mounted = true;
12998        } else {
12999            final String status = Environment.getExternalStorageState();
13000
13001            mounted = status.equals(Environment.MEDIA_MOUNTED)
13002                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13003        }
13004
13005        if (!mounted) {
13006            return;
13007        }
13008
13009        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13010        int[] users;
13011        if (userId == UserHandle.USER_ALL) {
13012            users = sUserManager.getUserIds();
13013        } else {
13014            users = new int[] { userId };
13015        }
13016        final ClearStorageConnection conn = new ClearStorageConnection();
13017        if (mContext.bindServiceAsUser(
13018                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
13019            try {
13020                for (int curUser : users) {
13021                    long timeout = SystemClock.uptimeMillis() + 5000;
13022                    synchronized (conn) {
13023                        long now = SystemClock.uptimeMillis();
13024                        while (conn.mContainerService == null && now < timeout) {
13025                            try {
13026                                conn.wait(timeout - now);
13027                            } catch (InterruptedException e) {
13028                            }
13029                        }
13030                    }
13031                    if (conn.mContainerService == null) {
13032                        return;
13033                    }
13034
13035                    final UserEnvironment userEnv = new UserEnvironment(curUser);
13036                    clearDirectory(conn.mContainerService,
13037                            userEnv.buildExternalStorageAppCacheDirs(packageName));
13038                    if (allData) {
13039                        clearDirectory(conn.mContainerService,
13040                                userEnv.buildExternalStorageAppDataDirs(packageName));
13041                        clearDirectory(conn.mContainerService,
13042                                userEnv.buildExternalStorageAppMediaDirs(packageName));
13043                    }
13044                }
13045            } finally {
13046                mContext.unbindService(conn);
13047            }
13048        }
13049    }
13050
13051    @Override
13052    public void clearApplicationUserData(final String packageName,
13053            final IPackageDataObserver observer, final int userId) {
13054        mContext.enforceCallingOrSelfPermission(
13055                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
13056        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
13057        // Queue up an async operation since the package deletion may take a little while.
13058        mHandler.post(new Runnable() {
13059            public void run() {
13060                mHandler.removeCallbacks(this);
13061                final boolean succeeded;
13062                synchronized (mInstallLock) {
13063                    succeeded = clearApplicationUserDataLI(packageName, userId);
13064                }
13065                clearExternalStorageDataSync(packageName, userId, true);
13066                if (succeeded) {
13067                    // invoke DeviceStorageMonitor's update method to clear any notifications
13068                    DeviceStorageMonitorInternal
13069                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13070                    if (dsm != null) {
13071                        dsm.checkMemory();
13072                    }
13073                }
13074                if(observer != null) {
13075                    try {
13076                        observer.onRemoveCompleted(packageName, succeeded);
13077                    } catch (RemoteException e) {
13078                        Log.i(TAG, "Observer no longer exists.");
13079                    }
13080                } //end if observer
13081            } //end run
13082        });
13083    }
13084
13085    private boolean clearApplicationUserDataLI(String packageName, int userId) {
13086        if (packageName == null) {
13087            Slog.w(TAG, "Attempt to delete null packageName.");
13088            return false;
13089        }
13090
13091        // Try finding details about the requested package
13092        PackageParser.Package pkg;
13093        synchronized (mPackages) {
13094            pkg = mPackages.get(packageName);
13095            if (pkg == null) {
13096                final PackageSetting ps = mSettings.mPackages.get(packageName);
13097                if (ps != null) {
13098                    pkg = ps.pkg;
13099                }
13100            }
13101
13102            if (pkg == null) {
13103                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13104                return false;
13105            }
13106
13107            PackageSetting ps = (PackageSetting) pkg.mExtras;
13108            PermissionsState permissionsState = ps.getPermissionsState();
13109            revokeRuntimePermissionsAndClearUserSetFlagsLocked(permissionsState, userId);
13110        }
13111
13112        // Always delete data directories for package, even if we found no other
13113        // record of app. This helps users recover from UID mismatches without
13114        // resorting to a full data wipe.
13115        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
13116        if (retCode < 0) {
13117            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
13118            return false;
13119        }
13120
13121        final int appId = pkg.applicationInfo.uid;
13122        removeKeystoreDataIfNeeded(userId, appId);
13123
13124        // Create a native library symlink only if we have native libraries
13125        // and if the native libraries are 32 bit libraries. We do not provide
13126        // this symlink for 64 bit libraries.
13127        if (pkg.applicationInfo.primaryCpuAbi != null &&
13128                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
13129            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
13130            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
13131                    nativeLibPath, userId) < 0) {
13132                Slog.w(TAG, "Failed linking native library dir");
13133                return false;
13134            }
13135        }
13136
13137        return true;
13138    }
13139
13140
13141    /**
13142     * Revokes granted runtime permissions and clears resettable flags
13143     * which are flags that can be set by a user interaction.
13144     *
13145     * @param permissionsState The permission state to reset.
13146     * @param userId The device user for which to do a reset.
13147     */
13148    private void revokeRuntimePermissionsAndClearUserSetFlagsLocked(
13149            PermissionsState permissionsState, int userId) {
13150        final int userSetFlags = PackageManager.FLAG_PERMISSION_USER_SET
13151                | PackageManager.FLAG_PERMISSION_USER_FIXED
13152                | PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13153
13154        revokeRuntimePermissionsAndClearFlagsLocked(permissionsState, userId, userSetFlags);
13155    }
13156
13157    /**
13158     * Revokes granted runtime permissions and clears all flags.
13159     *
13160     * @param permissionsState The permission state to reset.
13161     * @param userId The device user for which to do a reset.
13162     */
13163    private void revokeRuntimePermissionsAndClearAllFlagsLocked(
13164            PermissionsState permissionsState, int userId) {
13165        revokeRuntimePermissionsAndClearFlagsLocked(permissionsState, userId,
13166                PackageManager.MASK_PERMISSION_FLAGS);
13167    }
13168
13169    /**
13170     * Revokes granted runtime permissions and clears certain flags.
13171     *
13172     * @param permissionsState The permission state to reset.
13173     * @param userId The device user for which to do a reset.
13174     * @param flags The flags that is going to be reset.
13175     */
13176    private void revokeRuntimePermissionsAndClearFlagsLocked(
13177            PermissionsState permissionsState, final int userId, int flags) {
13178        boolean needsWrite = false;
13179
13180        for (PermissionState state : permissionsState.getRuntimePermissionStates(userId)) {
13181            BasePermission bp = mSettings.mPermissions.get(state.getName());
13182            if (bp != null) {
13183                permissionsState.revokeRuntimePermission(bp, userId);
13184                permissionsState.updatePermissionFlags(bp, userId, flags, 0);
13185                needsWrite = true;
13186            }
13187        }
13188
13189        // Ensure default permissions are never cleared.
13190        mHandler.post(new Runnable() {
13191            @Override
13192            public void run() {
13193                mDefaultPermissionPolicy.grantDefaultPermissions(userId);
13194            }
13195        });
13196
13197        if (needsWrite) {
13198            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
13199        }
13200    }
13201
13202    /**
13203     * Remove entries from the keystore daemon. Will only remove it if the
13204     * {@code appId} is valid.
13205     */
13206    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
13207        if (appId < 0) {
13208            return;
13209        }
13210
13211        final KeyStore keyStore = KeyStore.getInstance();
13212        if (keyStore != null) {
13213            if (userId == UserHandle.USER_ALL) {
13214                for (final int individual : sUserManager.getUserIds()) {
13215                    keyStore.clearUid(UserHandle.getUid(individual, appId));
13216                }
13217            } else {
13218                keyStore.clearUid(UserHandle.getUid(userId, appId));
13219            }
13220        } else {
13221            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
13222        }
13223    }
13224
13225    @Override
13226    public void deleteApplicationCacheFiles(final String packageName,
13227            final IPackageDataObserver observer) {
13228        mContext.enforceCallingOrSelfPermission(
13229                android.Manifest.permission.DELETE_CACHE_FILES, null);
13230        // Queue up an async operation since the package deletion may take a little while.
13231        final int userId = UserHandle.getCallingUserId();
13232        mHandler.post(new Runnable() {
13233            public void run() {
13234                mHandler.removeCallbacks(this);
13235                final boolean succeded;
13236                synchronized (mInstallLock) {
13237                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
13238                }
13239                clearExternalStorageDataSync(packageName, userId, false);
13240                if (observer != null) {
13241                    try {
13242                        observer.onRemoveCompleted(packageName, succeded);
13243                    } catch (RemoteException e) {
13244                        Log.i(TAG, "Observer no longer exists.");
13245                    }
13246                } //end if observer
13247            } //end run
13248        });
13249    }
13250
13251    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
13252        if (packageName == null) {
13253            Slog.w(TAG, "Attempt to delete null packageName.");
13254            return false;
13255        }
13256        PackageParser.Package p;
13257        synchronized (mPackages) {
13258            p = mPackages.get(packageName);
13259        }
13260        if (p == null) {
13261            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13262            return false;
13263        }
13264        final ApplicationInfo applicationInfo = p.applicationInfo;
13265        if (applicationInfo == null) {
13266            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13267            return false;
13268        }
13269        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
13270        if (retCode < 0) {
13271            Slog.w(TAG, "Couldn't remove cache files for package: "
13272                       + packageName + " u" + userId);
13273            return false;
13274        }
13275        return true;
13276    }
13277
13278    @Override
13279    public void getPackageSizeInfo(final String packageName, int userHandle,
13280            final IPackageStatsObserver observer) {
13281        mContext.enforceCallingOrSelfPermission(
13282                android.Manifest.permission.GET_PACKAGE_SIZE, null);
13283        if (packageName == null) {
13284            throw new IllegalArgumentException("Attempt to get size of null packageName");
13285        }
13286
13287        PackageStats stats = new PackageStats(packageName, userHandle);
13288
13289        /*
13290         * Queue up an async operation since the package measurement may take a
13291         * little while.
13292         */
13293        Message msg = mHandler.obtainMessage(INIT_COPY);
13294        msg.obj = new MeasureParams(stats, observer);
13295        mHandler.sendMessage(msg);
13296    }
13297
13298    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
13299            PackageStats pStats) {
13300        if (packageName == null) {
13301            Slog.w(TAG, "Attempt to get size of null packageName.");
13302            return false;
13303        }
13304        PackageParser.Package p;
13305        boolean dataOnly = false;
13306        String libDirRoot = null;
13307        String asecPath = null;
13308        PackageSetting ps = null;
13309        synchronized (mPackages) {
13310            p = mPackages.get(packageName);
13311            ps = mSettings.mPackages.get(packageName);
13312            if(p == null) {
13313                dataOnly = true;
13314                if((ps == null) || (ps.pkg == null)) {
13315                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13316                    return false;
13317                }
13318                p = ps.pkg;
13319            }
13320            if (ps != null) {
13321                libDirRoot = ps.legacyNativeLibraryPathString;
13322            }
13323            if (p != null && (isExternal(p) || p.isForwardLocked())) {
13324                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
13325                if (secureContainerId != null) {
13326                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
13327                }
13328            }
13329        }
13330        String publicSrcDir = null;
13331        if(!dataOnly) {
13332            final ApplicationInfo applicationInfo = p.applicationInfo;
13333            if (applicationInfo == null) {
13334                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13335                return false;
13336            }
13337            if (p.isForwardLocked()) {
13338                publicSrcDir = applicationInfo.getBaseResourcePath();
13339            }
13340        }
13341        // TODO: extend to measure size of split APKs
13342        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
13343        // not just the first level.
13344        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
13345        // just the primary.
13346        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
13347        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath,
13348                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
13349        if (res < 0) {
13350            return false;
13351        }
13352
13353        // Fix-up for forward-locked applications in ASEC containers.
13354        if (!isExternal(p)) {
13355            pStats.codeSize += pStats.externalCodeSize;
13356            pStats.externalCodeSize = 0L;
13357        }
13358
13359        return true;
13360    }
13361
13362
13363    @Override
13364    public void addPackageToPreferred(String packageName) {
13365        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
13366    }
13367
13368    @Override
13369    public void removePackageFromPreferred(String packageName) {
13370        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
13371    }
13372
13373    @Override
13374    public List<PackageInfo> getPreferredPackages(int flags) {
13375        return new ArrayList<PackageInfo>();
13376    }
13377
13378    private int getUidTargetSdkVersionLockedLPr(int uid) {
13379        Object obj = mSettings.getUserIdLPr(uid);
13380        if (obj instanceof SharedUserSetting) {
13381            final SharedUserSetting sus = (SharedUserSetting) obj;
13382            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
13383            final Iterator<PackageSetting> it = sus.packages.iterator();
13384            while (it.hasNext()) {
13385                final PackageSetting ps = it.next();
13386                if (ps.pkg != null) {
13387                    int v = ps.pkg.applicationInfo.targetSdkVersion;
13388                    if (v < vers) vers = v;
13389                }
13390            }
13391            return vers;
13392        } else if (obj instanceof PackageSetting) {
13393            final PackageSetting ps = (PackageSetting) obj;
13394            if (ps.pkg != null) {
13395                return ps.pkg.applicationInfo.targetSdkVersion;
13396            }
13397        }
13398        return Build.VERSION_CODES.CUR_DEVELOPMENT;
13399    }
13400
13401    @Override
13402    public void addPreferredActivity(IntentFilter filter, int match,
13403            ComponentName[] set, ComponentName activity, int userId) {
13404        addPreferredActivityInternal(filter, match, set, activity, true, userId,
13405                "Adding preferred");
13406    }
13407
13408    private void addPreferredActivityInternal(IntentFilter filter, int match,
13409            ComponentName[] set, ComponentName activity, boolean always, int userId,
13410            String opname) {
13411        // writer
13412        int callingUid = Binder.getCallingUid();
13413        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
13414        if (filter.countActions() == 0) {
13415            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13416            return;
13417        }
13418        synchronized (mPackages) {
13419            if (mContext.checkCallingOrSelfPermission(
13420                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13421                    != PackageManager.PERMISSION_GRANTED) {
13422                if (getUidTargetSdkVersionLockedLPr(callingUid)
13423                        < Build.VERSION_CODES.FROYO) {
13424                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
13425                            + callingUid);
13426                    return;
13427                }
13428                mContext.enforceCallingOrSelfPermission(
13429                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13430            }
13431
13432            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
13433            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
13434                    + userId + ":");
13435            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13436            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
13437            scheduleWritePackageRestrictionsLocked(userId);
13438        }
13439    }
13440
13441    @Override
13442    public void replacePreferredActivity(IntentFilter filter, int match,
13443            ComponentName[] set, ComponentName activity, int userId) {
13444        if (filter.countActions() != 1) {
13445            throw new IllegalArgumentException(
13446                    "replacePreferredActivity expects filter to have only 1 action.");
13447        }
13448        if (filter.countDataAuthorities() != 0
13449                || filter.countDataPaths() != 0
13450                || filter.countDataSchemes() > 1
13451                || filter.countDataTypes() != 0) {
13452            throw new IllegalArgumentException(
13453                    "replacePreferredActivity expects filter to have no data authorities, " +
13454                    "paths, or types; and at most one scheme.");
13455        }
13456
13457        final int callingUid = Binder.getCallingUid();
13458        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
13459        synchronized (mPackages) {
13460            if (mContext.checkCallingOrSelfPermission(
13461                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13462                    != PackageManager.PERMISSION_GRANTED) {
13463                if (getUidTargetSdkVersionLockedLPr(callingUid)
13464                        < Build.VERSION_CODES.FROYO) {
13465                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
13466                            + Binder.getCallingUid());
13467                    return;
13468                }
13469                mContext.enforceCallingOrSelfPermission(
13470                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13471            }
13472
13473            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13474            if (pir != null) {
13475                // Get all of the existing entries that exactly match this filter.
13476                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
13477                if (existing != null && existing.size() == 1) {
13478                    PreferredActivity cur = existing.get(0);
13479                    if (DEBUG_PREFERRED) {
13480                        Slog.i(TAG, "Checking replace of preferred:");
13481                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13482                        if (!cur.mPref.mAlways) {
13483                            Slog.i(TAG, "  -- CUR; not mAlways!");
13484                        } else {
13485                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
13486                            Slog.i(TAG, "  -- CUR: mSet="
13487                                    + Arrays.toString(cur.mPref.mSetComponents));
13488                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
13489                            Slog.i(TAG, "  -- NEW: mMatch="
13490                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
13491                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
13492                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
13493                        }
13494                    }
13495                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
13496                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
13497                            && cur.mPref.sameSet(set)) {
13498                        // Setting the preferred activity to what it happens to be already
13499                        if (DEBUG_PREFERRED) {
13500                            Slog.i(TAG, "Replacing with same preferred activity "
13501                                    + cur.mPref.mShortComponent + " for user "
13502                                    + userId + ":");
13503                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13504                        }
13505                        return;
13506                    }
13507                }
13508
13509                if (existing != null) {
13510                    if (DEBUG_PREFERRED) {
13511                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
13512                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13513                    }
13514                    for (int i = 0; i < existing.size(); i++) {
13515                        PreferredActivity pa = existing.get(i);
13516                        if (DEBUG_PREFERRED) {
13517                            Slog.i(TAG, "Removing existing preferred activity "
13518                                    + pa.mPref.mComponent + ":");
13519                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
13520                        }
13521                        pir.removeFilter(pa);
13522                    }
13523                }
13524            }
13525            addPreferredActivityInternal(filter, match, set, activity, true, userId,
13526                    "Replacing preferred");
13527        }
13528    }
13529
13530    @Override
13531    public void clearPackagePreferredActivities(String packageName) {
13532        final int uid = Binder.getCallingUid();
13533        // writer
13534        synchronized (mPackages) {
13535            PackageParser.Package pkg = mPackages.get(packageName);
13536            if (pkg == null || pkg.applicationInfo.uid != uid) {
13537                if (mContext.checkCallingOrSelfPermission(
13538                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13539                        != PackageManager.PERMISSION_GRANTED) {
13540                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
13541                            < Build.VERSION_CODES.FROYO) {
13542                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
13543                                + Binder.getCallingUid());
13544                        return;
13545                    }
13546                    mContext.enforceCallingOrSelfPermission(
13547                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13548                }
13549            }
13550
13551            int user = UserHandle.getCallingUserId();
13552            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
13553                scheduleWritePackageRestrictionsLocked(user);
13554            }
13555        }
13556    }
13557
13558    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13559    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
13560        ArrayList<PreferredActivity> removed = null;
13561        boolean changed = false;
13562        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13563            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
13564            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13565            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
13566                continue;
13567            }
13568            Iterator<PreferredActivity> it = pir.filterIterator();
13569            while (it.hasNext()) {
13570                PreferredActivity pa = it.next();
13571                // Mark entry for removal only if it matches the package name
13572                // and the entry is of type "always".
13573                if (packageName == null ||
13574                        (pa.mPref.mComponent.getPackageName().equals(packageName)
13575                                && pa.mPref.mAlways)) {
13576                    if (removed == null) {
13577                        removed = new ArrayList<PreferredActivity>();
13578                    }
13579                    removed.add(pa);
13580                }
13581            }
13582            if (removed != null) {
13583                for (int j=0; j<removed.size(); j++) {
13584                    PreferredActivity pa = removed.get(j);
13585                    pir.removeFilter(pa);
13586                }
13587                changed = true;
13588            }
13589        }
13590        return changed;
13591    }
13592
13593    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13594    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
13595        if (userId == UserHandle.USER_ALL) {
13596            if (mSettings.removeIntentFilterVerificationLPw(packageName,
13597                    sUserManager.getUserIds())) {
13598                for (int oneUserId : sUserManager.getUserIds()) {
13599                    scheduleWritePackageRestrictionsLocked(oneUserId);
13600                }
13601            }
13602        } else {
13603            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
13604                scheduleWritePackageRestrictionsLocked(userId);
13605            }
13606        }
13607    }
13608
13609
13610    void clearDefaultBrowserIfNeeded(String packageName) {
13611        for (int oneUserId : sUserManager.getUserIds()) {
13612            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
13613            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
13614            if (packageName.equals(defaultBrowserPackageName)) {
13615                setDefaultBrowserPackageName(null, oneUserId);
13616            }
13617        }
13618    }
13619
13620    @Override
13621    public void resetPreferredActivities(int userId) {
13622        mContext.enforceCallingOrSelfPermission(
13623                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13624        // writer
13625        synchronized (mPackages) {
13626            clearPackagePreferredActivitiesLPw(null, userId);
13627            mSettings.applyDefaultPreferredAppsLPw(this, userId);
13628            applyFactoryDefaultBrowserLPw(userId);
13629
13630            scheduleWritePackageRestrictionsLocked(userId);
13631        }
13632    }
13633
13634    @Override
13635    public int getPreferredActivities(List<IntentFilter> outFilters,
13636            List<ComponentName> outActivities, String packageName) {
13637
13638        int num = 0;
13639        final int userId = UserHandle.getCallingUserId();
13640        // reader
13641        synchronized (mPackages) {
13642            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13643            if (pir != null) {
13644                final Iterator<PreferredActivity> it = pir.filterIterator();
13645                while (it.hasNext()) {
13646                    final PreferredActivity pa = it.next();
13647                    if (packageName == null
13648                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
13649                                    && pa.mPref.mAlways)) {
13650                        if (outFilters != null) {
13651                            outFilters.add(new IntentFilter(pa));
13652                        }
13653                        if (outActivities != null) {
13654                            outActivities.add(pa.mPref.mComponent);
13655                        }
13656                    }
13657                }
13658            }
13659        }
13660
13661        return num;
13662    }
13663
13664    @Override
13665    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
13666            int userId) {
13667        int callingUid = Binder.getCallingUid();
13668        if (callingUid != Process.SYSTEM_UID) {
13669            throw new SecurityException(
13670                    "addPersistentPreferredActivity can only be run by the system");
13671        }
13672        if (filter.countActions() == 0) {
13673            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13674            return;
13675        }
13676        synchronized (mPackages) {
13677            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
13678                    " :");
13679            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13680            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
13681                    new PersistentPreferredActivity(filter, activity));
13682            scheduleWritePackageRestrictionsLocked(userId);
13683        }
13684    }
13685
13686    @Override
13687    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
13688        int callingUid = Binder.getCallingUid();
13689        if (callingUid != Process.SYSTEM_UID) {
13690            throw new SecurityException(
13691                    "clearPackagePersistentPreferredActivities can only be run by the system");
13692        }
13693        ArrayList<PersistentPreferredActivity> removed = null;
13694        boolean changed = false;
13695        synchronized (mPackages) {
13696            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
13697                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
13698                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
13699                        .valueAt(i);
13700                if (userId != thisUserId) {
13701                    continue;
13702                }
13703                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
13704                while (it.hasNext()) {
13705                    PersistentPreferredActivity ppa = it.next();
13706                    // Mark entry for removal only if it matches the package name.
13707                    if (ppa.mComponent.getPackageName().equals(packageName)) {
13708                        if (removed == null) {
13709                            removed = new ArrayList<PersistentPreferredActivity>();
13710                        }
13711                        removed.add(ppa);
13712                    }
13713                }
13714                if (removed != null) {
13715                    for (int j=0; j<removed.size(); j++) {
13716                        PersistentPreferredActivity ppa = removed.get(j);
13717                        ppir.removeFilter(ppa);
13718                    }
13719                    changed = true;
13720                }
13721            }
13722
13723            if (changed) {
13724                scheduleWritePackageRestrictionsLocked(userId);
13725            }
13726        }
13727    }
13728
13729    /**
13730     * Common machinery for picking apart a restored XML blob and passing
13731     * it to a caller-supplied functor to be applied to the running system.
13732     */
13733    private void restoreFromXml(XmlPullParser parser, int userId,
13734            String expectedStartTag, BlobXmlRestorer functor)
13735            throws IOException, XmlPullParserException {
13736        int type;
13737        while ((type = parser.next()) != XmlPullParser.START_TAG
13738                && type != XmlPullParser.END_DOCUMENT) {
13739        }
13740        if (type != XmlPullParser.START_TAG) {
13741            // oops didn't find a start tag?!
13742            if (DEBUG_BACKUP) {
13743                Slog.e(TAG, "Didn't find start tag during restore");
13744            }
13745            return;
13746        }
13747
13748        // this is supposed to be TAG_PREFERRED_BACKUP
13749        if (!expectedStartTag.equals(parser.getName())) {
13750            if (DEBUG_BACKUP) {
13751                Slog.e(TAG, "Found unexpected tag " + parser.getName());
13752            }
13753            return;
13754        }
13755
13756        // skip interfering stuff, then we're aligned with the backing implementation
13757        while ((type = parser.next()) == XmlPullParser.TEXT) { }
13758        functor.apply(parser, userId);
13759    }
13760
13761    private interface BlobXmlRestorer {
13762        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
13763    }
13764
13765    /**
13766     * Non-Binder method, support for the backup/restore mechanism: write the
13767     * full set of preferred activities in its canonical XML format.  Returns the
13768     * XML output as a byte array, or null if there is none.
13769     */
13770    @Override
13771    public byte[] getPreferredActivityBackup(int userId) {
13772        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13773            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
13774        }
13775
13776        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13777        try {
13778            final XmlSerializer serializer = new FastXmlSerializer();
13779            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13780            serializer.startDocument(null, true);
13781            serializer.startTag(null, TAG_PREFERRED_BACKUP);
13782
13783            synchronized (mPackages) {
13784                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
13785            }
13786
13787            serializer.endTag(null, TAG_PREFERRED_BACKUP);
13788            serializer.endDocument();
13789            serializer.flush();
13790        } catch (Exception e) {
13791            if (DEBUG_BACKUP) {
13792                Slog.e(TAG, "Unable to write preferred activities for backup", e);
13793            }
13794            return null;
13795        }
13796
13797        return dataStream.toByteArray();
13798    }
13799
13800    @Override
13801    public void restorePreferredActivities(byte[] backup, int userId) {
13802        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13803            throw new SecurityException("Only the system may call restorePreferredActivities()");
13804        }
13805
13806        try {
13807            final XmlPullParser parser = Xml.newPullParser();
13808            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13809            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
13810                    new BlobXmlRestorer() {
13811                        @Override
13812                        public void apply(XmlPullParser parser, int userId)
13813                                throws XmlPullParserException, IOException {
13814                            synchronized (mPackages) {
13815                                mSettings.readPreferredActivitiesLPw(parser, userId);
13816                            }
13817                        }
13818                    } );
13819        } catch (Exception e) {
13820            if (DEBUG_BACKUP) {
13821                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
13822            }
13823        }
13824    }
13825
13826    /**
13827     * Non-Binder method, support for the backup/restore mechanism: write the
13828     * default browser (etc) settings in its canonical XML format.  Returns the default
13829     * browser XML representation as a byte array, or null if there is none.
13830     */
13831    @Override
13832    public byte[] getDefaultAppsBackup(int userId) {
13833        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13834            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
13835        }
13836
13837        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13838        try {
13839            final XmlSerializer serializer = new FastXmlSerializer();
13840            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13841            serializer.startDocument(null, true);
13842            serializer.startTag(null, TAG_DEFAULT_APPS);
13843
13844            synchronized (mPackages) {
13845                mSettings.writeDefaultAppsLPr(serializer, userId);
13846            }
13847
13848            serializer.endTag(null, TAG_DEFAULT_APPS);
13849            serializer.endDocument();
13850            serializer.flush();
13851        } catch (Exception e) {
13852            if (DEBUG_BACKUP) {
13853                Slog.e(TAG, "Unable to write default apps for backup", e);
13854            }
13855            return null;
13856        }
13857
13858        return dataStream.toByteArray();
13859    }
13860
13861    @Override
13862    public void restoreDefaultApps(byte[] backup, int userId) {
13863        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13864            throw new SecurityException("Only the system may call restoreDefaultApps()");
13865        }
13866
13867        try {
13868            final XmlPullParser parser = Xml.newPullParser();
13869            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13870            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
13871                    new BlobXmlRestorer() {
13872                        @Override
13873                        public void apply(XmlPullParser parser, int userId)
13874                                throws XmlPullParserException, IOException {
13875                            synchronized (mPackages) {
13876                                mSettings.readDefaultAppsLPw(parser, userId);
13877                            }
13878                        }
13879                    } );
13880        } catch (Exception e) {
13881            if (DEBUG_BACKUP) {
13882                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
13883            }
13884        }
13885    }
13886
13887    @Override
13888    public byte[] getIntentFilterVerificationBackup(int userId) {
13889        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13890            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
13891        }
13892
13893        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13894        try {
13895            final XmlSerializer serializer = new FastXmlSerializer();
13896            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13897            serializer.startDocument(null, true);
13898            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
13899
13900            synchronized (mPackages) {
13901                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
13902            }
13903
13904            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
13905            serializer.endDocument();
13906            serializer.flush();
13907        } catch (Exception e) {
13908            if (DEBUG_BACKUP) {
13909                Slog.e(TAG, "Unable to write default apps for backup", e);
13910            }
13911            return null;
13912        }
13913
13914        return dataStream.toByteArray();
13915    }
13916
13917    @Override
13918    public void restoreIntentFilterVerification(byte[] backup, int userId) {
13919        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13920            throw new SecurityException("Only the system may call restorePreferredActivities()");
13921        }
13922
13923        try {
13924            final XmlPullParser parser = Xml.newPullParser();
13925            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13926            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
13927                    new BlobXmlRestorer() {
13928                        @Override
13929                        public void apply(XmlPullParser parser, int userId)
13930                                throws XmlPullParserException, IOException {
13931                            synchronized (mPackages) {
13932                                mSettings.readAllDomainVerificationsLPr(parser, userId);
13933                                mSettings.writeLPr();
13934                            }
13935                        }
13936                    } );
13937        } catch (Exception e) {
13938            if (DEBUG_BACKUP) {
13939                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
13940            }
13941        }
13942    }
13943
13944    @Override
13945    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
13946            int sourceUserId, int targetUserId, int flags) {
13947        mContext.enforceCallingOrSelfPermission(
13948                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
13949        int callingUid = Binder.getCallingUid();
13950        enforceOwnerRights(ownerPackage, callingUid);
13951        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
13952        if (intentFilter.countActions() == 0) {
13953            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
13954            return;
13955        }
13956        synchronized (mPackages) {
13957            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
13958                    ownerPackage, targetUserId, flags);
13959            CrossProfileIntentResolver resolver =
13960                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
13961            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
13962            // We have all those whose filter is equal. Now checking if the rest is equal as well.
13963            if (existing != null) {
13964                int size = existing.size();
13965                for (int i = 0; i < size; i++) {
13966                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
13967                        return;
13968                    }
13969                }
13970            }
13971            resolver.addFilter(newFilter);
13972            scheduleWritePackageRestrictionsLocked(sourceUserId);
13973        }
13974    }
13975
13976    @Override
13977    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
13978        mContext.enforceCallingOrSelfPermission(
13979                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
13980        int callingUid = Binder.getCallingUid();
13981        enforceOwnerRights(ownerPackage, callingUid);
13982        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
13983        synchronized (mPackages) {
13984            CrossProfileIntentResolver resolver =
13985                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
13986            ArraySet<CrossProfileIntentFilter> set =
13987                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
13988            for (CrossProfileIntentFilter filter : set) {
13989                if (filter.getOwnerPackage().equals(ownerPackage)) {
13990                    resolver.removeFilter(filter);
13991                }
13992            }
13993            scheduleWritePackageRestrictionsLocked(sourceUserId);
13994        }
13995    }
13996
13997    // Enforcing that callingUid is owning pkg on userId
13998    private void enforceOwnerRights(String pkg, int callingUid) {
13999        // The system owns everything.
14000        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
14001            return;
14002        }
14003        int callingUserId = UserHandle.getUserId(callingUid);
14004        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
14005        if (pi == null) {
14006            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
14007                    + callingUserId);
14008        }
14009        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
14010            throw new SecurityException("Calling uid " + callingUid
14011                    + " does not own package " + pkg);
14012        }
14013    }
14014
14015    @Override
14016    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
14017        Intent intent = new Intent(Intent.ACTION_MAIN);
14018        intent.addCategory(Intent.CATEGORY_HOME);
14019
14020        final int callingUserId = UserHandle.getCallingUserId();
14021        List<ResolveInfo> list = queryIntentActivities(intent, null,
14022                PackageManager.GET_META_DATA, callingUserId);
14023        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
14024                true, false, false, callingUserId);
14025
14026        allHomeCandidates.clear();
14027        if (list != null) {
14028            for (ResolveInfo ri : list) {
14029                allHomeCandidates.add(ri);
14030            }
14031        }
14032        return (preferred == null || preferred.activityInfo == null)
14033                ? null
14034                : new ComponentName(preferred.activityInfo.packageName,
14035                        preferred.activityInfo.name);
14036    }
14037
14038    @Override
14039    public void setApplicationEnabledSetting(String appPackageName,
14040            int newState, int flags, int userId, String callingPackage) {
14041        if (!sUserManager.exists(userId)) return;
14042        if (callingPackage == null) {
14043            callingPackage = Integer.toString(Binder.getCallingUid());
14044        }
14045        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
14046    }
14047
14048    @Override
14049    public void setComponentEnabledSetting(ComponentName componentName,
14050            int newState, int flags, int userId) {
14051        if (!sUserManager.exists(userId)) return;
14052        setEnabledSetting(componentName.getPackageName(),
14053                componentName.getClassName(), newState, flags, userId, null);
14054    }
14055
14056    private void setEnabledSetting(final String packageName, String className, int newState,
14057            final int flags, int userId, String callingPackage) {
14058        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
14059              || newState == COMPONENT_ENABLED_STATE_ENABLED
14060              || newState == COMPONENT_ENABLED_STATE_DISABLED
14061              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
14062              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
14063            throw new IllegalArgumentException("Invalid new component state: "
14064                    + newState);
14065        }
14066        PackageSetting pkgSetting;
14067        final int uid = Binder.getCallingUid();
14068        final int permission = mContext.checkCallingOrSelfPermission(
14069                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14070        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
14071        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14072        boolean sendNow = false;
14073        boolean isApp = (className == null);
14074        String componentName = isApp ? packageName : className;
14075        int packageUid = -1;
14076        ArrayList<String> components;
14077
14078        // writer
14079        synchronized (mPackages) {
14080            pkgSetting = mSettings.mPackages.get(packageName);
14081            if (pkgSetting == null) {
14082                if (className == null) {
14083                    throw new IllegalArgumentException(
14084                            "Unknown package: " + packageName);
14085                }
14086                throw new IllegalArgumentException(
14087                        "Unknown component: " + packageName
14088                        + "/" + className);
14089            }
14090            // Allow root and verify that userId is not being specified by a different user
14091            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
14092                throw new SecurityException(
14093                        "Permission Denial: attempt to change component state from pid="
14094                        + Binder.getCallingPid()
14095                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
14096            }
14097            if (className == null) {
14098                // We're dealing with an application/package level state change
14099                if (pkgSetting.getEnabled(userId) == newState) {
14100                    // Nothing to do
14101                    return;
14102                }
14103                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
14104                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
14105                    // Don't care about who enables an app.
14106                    callingPackage = null;
14107                }
14108                pkgSetting.setEnabled(newState, userId, callingPackage);
14109                // pkgSetting.pkg.mSetEnabled = newState;
14110            } else {
14111                // We're dealing with a component level state change
14112                // First, verify that this is a valid class name.
14113                PackageParser.Package pkg = pkgSetting.pkg;
14114                if (pkg == null || !pkg.hasComponentClassName(className)) {
14115                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
14116                        throw new IllegalArgumentException("Component class " + className
14117                                + " does not exist in " + packageName);
14118                    } else {
14119                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
14120                                + className + " does not exist in " + packageName);
14121                    }
14122                }
14123                switch (newState) {
14124                case COMPONENT_ENABLED_STATE_ENABLED:
14125                    if (!pkgSetting.enableComponentLPw(className, userId)) {
14126                        return;
14127                    }
14128                    break;
14129                case COMPONENT_ENABLED_STATE_DISABLED:
14130                    if (!pkgSetting.disableComponentLPw(className, userId)) {
14131                        return;
14132                    }
14133                    break;
14134                case COMPONENT_ENABLED_STATE_DEFAULT:
14135                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
14136                        return;
14137                    }
14138                    break;
14139                default:
14140                    Slog.e(TAG, "Invalid new component state: " + newState);
14141                    return;
14142                }
14143            }
14144            scheduleWritePackageRestrictionsLocked(userId);
14145            components = mPendingBroadcasts.get(userId, packageName);
14146            final boolean newPackage = components == null;
14147            if (newPackage) {
14148                components = new ArrayList<String>();
14149            }
14150            if (!components.contains(componentName)) {
14151                components.add(componentName);
14152            }
14153            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
14154                sendNow = true;
14155                // Purge entry from pending broadcast list if another one exists already
14156                // since we are sending one right away.
14157                mPendingBroadcasts.remove(userId, packageName);
14158            } else {
14159                if (newPackage) {
14160                    mPendingBroadcasts.put(userId, packageName, components);
14161                }
14162                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
14163                    // Schedule a message
14164                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
14165                }
14166            }
14167        }
14168
14169        long callingId = Binder.clearCallingIdentity();
14170        try {
14171            if (sendNow) {
14172                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
14173                sendPackageChangedBroadcast(packageName,
14174                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
14175            }
14176        } finally {
14177            Binder.restoreCallingIdentity(callingId);
14178        }
14179    }
14180
14181    private void sendPackageChangedBroadcast(String packageName,
14182            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
14183        if (DEBUG_INSTALL)
14184            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
14185                    + componentNames);
14186        Bundle extras = new Bundle(4);
14187        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
14188        String nameList[] = new String[componentNames.size()];
14189        componentNames.toArray(nameList);
14190        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
14191        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
14192        extras.putInt(Intent.EXTRA_UID, packageUid);
14193        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
14194                new int[] {UserHandle.getUserId(packageUid)});
14195    }
14196
14197    @Override
14198    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
14199        if (!sUserManager.exists(userId)) return;
14200        final int uid = Binder.getCallingUid();
14201        final int permission = mContext.checkCallingOrSelfPermission(
14202                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14203        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14204        enforceCrossUserPermission(uid, userId, true, true, "stop package");
14205        // writer
14206        synchronized (mPackages) {
14207            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
14208                    allowedByPermission, uid, userId)) {
14209                scheduleWritePackageRestrictionsLocked(userId);
14210            }
14211        }
14212    }
14213
14214    @Override
14215    public String getInstallerPackageName(String packageName) {
14216        // reader
14217        synchronized (mPackages) {
14218            return mSettings.getInstallerPackageNameLPr(packageName);
14219        }
14220    }
14221
14222    @Override
14223    public int getApplicationEnabledSetting(String packageName, int userId) {
14224        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14225        int uid = Binder.getCallingUid();
14226        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
14227        // reader
14228        synchronized (mPackages) {
14229            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
14230        }
14231    }
14232
14233    @Override
14234    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
14235        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14236        int uid = Binder.getCallingUid();
14237        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
14238        // reader
14239        synchronized (mPackages) {
14240            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
14241        }
14242    }
14243
14244    @Override
14245    public void enterSafeMode() {
14246        enforceSystemOrRoot("Only the system can request entering safe mode");
14247
14248        if (!mSystemReady) {
14249            mSafeMode = true;
14250        }
14251    }
14252
14253    @Override
14254    public void systemReady() {
14255        mSystemReady = true;
14256
14257        // Read the compatibilty setting when the system is ready.
14258        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
14259                mContext.getContentResolver(),
14260                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
14261        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
14262        if (DEBUG_SETTINGS) {
14263            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
14264        }
14265
14266        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
14267
14268        synchronized (mPackages) {
14269            // Verify that all of the preferred activity components actually
14270            // exist.  It is possible for applications to be updated and at
14271            // that point remove a previously declared activity component that
14272            // had been set as a preferred activity.  We try to clean this up
14273            // the next time we encounter that preferred activity, but it is
14274            // possible for the user flow to never be able to return to that
14275            // situation so here we do a sanity check to make sure we haven't
14276            // left any junk around.
14277            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
14278            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14279                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14280                removed.clear();
14281                for (PreferredActivity pa : pir.filterSet()) {
14282                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
14283                        removed.add(pa);
14284                    }
14285                }
14286                if (removed.size() > 0) {
14287                    for (int r=0; r<removed.size(); r++) {
14288                        PreferredActivity pa = removed.get(r);
14289                        Slog.w(TAG, "Removing dangling preferred activity: "
14290                                + pa.mPref.mComponent);
14291                        pir.removeFilter(pa);
14292                    }
14293                    mSettings.writePackageRestrictionsLPr(
14294                            mSettings.mPreferredActivities.keyAt(i));
14295                }
14296            }
14297
14298            for (int userId : UserManagerService.getInstance().getUserIds()) {
14299                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
14300                    grantPermissionsUserIds = ArrayUtils.appendInt(
14301                            grantPermissionsUserIds, userId);
14302                }
14303            }
14304        }
14305        sUserManager.systemReady();
14306
14307        // If we upgraded grant all default permissions before kicking off.
14308        for (int userId : grantPermissionsUserIds) {
14309            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
14310        }
14311
14312        // Kick off any messages waiting for system ready
14313        if (mPostSystemReadyMessages != null) {
14314            for (Message msg : mPostSystemReadyMessages) {
14315                msg.sendToTarget();
14316            }
14317            mPostSystemReadyMessages = null;
14318        }
14319
14320        // Watch for external volumes that come and go over time
14321        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14322        storage.registerListener(mStorageListener);
14323
14324        mInstallerService.systemReady();
14325        mPackageDexOptimizer.systemReady();
14326    }
14327
14328    @Override
14329    public boolean isSafeMode() {
14330        return mSafeMode;
14331    }
14332
14333    @Override
14334    public boolean hasSystemUidErrors() {
14335        return mHasSystemUidErrors;
14336    }
14337
14338    static String arrayToString(int[] array) {
14339        StringBuffer buf = new StringBuffer(128);
14340        buf.append('[');
14341        if (array != null) {
14342            for (int i=0; i<array.length; i++) {
14343                if (i > 0) buf.append(", ");
14344                buf.append(array[i]);
14345            }
14346        }
14347        buf.append(']');
14348        return buf.toString();
14349    }
14350
14351    static class DumpState {
14352        public static final int DUMP_LIBS = 1 << 0;
14353        public static final int DUMP_FEATURES = 1 << 1;
14354        public static final int DUMP_RESOLVERS = 1 << 2;
14355        public static final int DUMP_PERMISSIONS = 1 << 3;
14356        public static final int DUMP_PACKAGES = 1 << 4;
14357        public static final int DUMP_SHARED_USERS = 1 << 5;
14358        public static final int DUMP_MESSAGES = 1 << 6;
14359        public static final int DUMP_PROVIDERS = 1 << 7;
14360        public static final int DUMP_VERIFIERS = 1 << 8;
14361        public static final int DUMP_PREFERRED = 1 << 9;
14362        public static final int DUMP_PREFERRED_XML = 1 << 10;
14363        public static final int DUMP_KEYSETS = 1 << 11;
14364        public static final int DUMP_VERSION = 1 << 12;
14365        public static final int DUMP_INSTALLS = 1 << 13;
14366        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
14367        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
14368
14369        public static final int OPTION_SHOW_FILTERS = 1 << 0;
14370
14371        private int mTypes;
14372
14373        private int mOptions;
14374
14375        private boolean mTitlePrinted;
14376
14377        private SharedUserSetting mSharedUser;
14378
14379        public boolean isDumping(int type) {
14380            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
14381                return true;
14382            }
14383
14384            return (mTypes & type) != 0;
14385        }
14386
14387        public void setDump(int type) {
14388            mTypes |= type;
14389        }
14390
14391        public boolean isOptionEnabled(int option) {
14392            return (mOptions & option) != 0;
14393        }
14394
14395        public void setOptionEnabled(int option) {
14396            mOptions |= option;
14397        }
14398
14399        public boolean onTitlePrinted() {
14400            final boolean printed = mTitlePrinted;
14401            mTitlePrinted = true;
14402            return printed;
14403        }
14404
14405        public boolean getTitlePrinted() {
14406            return mTitlePrinted;
14407        }
14408
14409        public void setTitlePrinted(boolean enabled) {
14410            mTitlePrinted = enabled;
14411        }
14412
14413        public SharedUserSetting getSharedUser() {
14414            return mSharedUser;
14415        }
14416
14417        public void setSharedUser(SharedUserSetting user) {
14418            mSharedUser = user;
14419        }
14420    }
14421
14422    @Override
14423    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
14424        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
14425                != PackageManager.PERMISSION_GRANTED) {
14426            pw.println("Permission Denial: can't dump ActivityManager from from pid="
14427                    + Binder.getCallingPid()
14428                    + ", uid=" + Binder.getCallingUid()
14429                    + " without permission "
14430                    + android.Manifest.permission.DUMP);
14431            return;
14432        }
14433
14434        DumpState dumpState = new DumpState();
14435        boolean fullPreferred = false;
14436        boolean checkin = false;
14437
14438        String packageName = null;
14439        ArraySet<String> permissionNames = null;
14440
14441        int opti = 0;
14442        while (opti < args.length) {
14443            String opt = args[opti];
14444            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
14445                break;
14446            }
14447            opti++;
14448
14449            if ("-a".equals(opt)) {
14450                // Right now we only know how to print all.
14451            } else if ("-h".equals(opt)) {
14452                pw.println("Package manager dump options:");
14453                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
14454                pw.println("    --checkin: dump for a checkin");
14455                pw.println("    -f: print details of intent filters");
14456                pw.println("    -h: print this help");
14457                pw.println("  cmd may be one of:");
14458                pw.println("    l[ibraries]: list known shared libraries");
14459                pw.println("    f[ibraries]: list device features");
14460                pw.println("    k[eysets]: print known keysets");
14461                pw.println("    r[esolvers]: dump intent resolvers");
14462                pw.println("    perm[issions]: dump permissions");
14463                pw.println("    permission [name ...]: dump declaration and use of given permission");
14464                pw.println("    pref[erred]: print preferred package settings");
14465                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
14466                pw.println("    prov[iders]: dump content providers");
14467                pw.println("    p[ackages]: dump installed packages");
14468                pw.println("    s[hared-users]: dump shared user IDs");
14469                pw.println("    m[essages]: print collected runtime messages");
14470                pw.println("    v[erifiers]: print package verifier info");
14471                pw.println("    version: print database version info");
14472                pw.println("    write: write current settings now");
14473                pw.println("    <package.name>: info about given package");
14474                pw.println("    installs: details about install sessions");
14475                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
14476                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
14477                return;
14478            } else if ("--checkin".equals(opt)) {
14479                checkin = true;
14480            } else if ("-f".equals(opt)) {
14481                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14482            } else {
14483                pw.println("Unknown argument: " + opt + "; use -h for help");
14484            }
14485        }
14486
14487        // Is the caller requesting to dump a particular piece of data?
14488        if (opti < args.length) {
14489            String cmd = args[opti];
14490            opti++;
14491            // Is this a package name?
14492            if ("android".equals(cmd) || cmd.contains(".")) {
14493                packageName = cmd;
14494                // When dumping a single package, we always dump all of its
14495                // filter information since the amount of data will be reasonable.
14496                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14497            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
14498                dumpState.setDump(DumpState.DUMP_LIBS);
14499            } else if ("f".equals(cmd) || "features".equals(cmd)) {
14500                dumpState.setDump(DumpState.DUMP_FEATURES);
14501            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
14502                dumpState.setDump(DumpState.DUMP_RESOLVERS);
14503            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
14504                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
14505            } else if ("permission".equals(cmd)) {
14506                if (opti >= args.length) {
14507                    pw.println("Error: permission requires permission name");
14508                    return;
14509                }
14510                permissionNames = new ArraySet<>();
14511                while (opti < args.length) {
14512                    permissionNames.add(args[opti]);
14513                    opti++;
14514                }
14515                dumpState.setDump(DumpState.DUMP_PERMISSIONS
14516                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
14517            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
14518                dumpState.setDump(DumpState.DUMP_PREFERRED);
14519            } else if ("preferred-xml".equals(cmd)) {
14520                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
14521                if (opti < args.length && "--full".equals(args[opti])) {
14522                    fullPreferred = true;
14523                    opti++;
14524                }
14525            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
14526                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
14527            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
14528                dumpState.setDump(DumpState.DUMP_PACKAGES);
14529            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
14530                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
14531            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
14532                dumpState.setDump(DumpState.DUMP_PROVIDERS);
14533            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
14534                dumpState.setDump(DumpState.DUMP_MESSAGES);
14535            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
14536                dumpState.setDump(DumpState.DUMP_VERIFIERS);
14537            } else if ("i".equals(cmd) || "ifv".equals(cmd)
14538                    || "intent-filter-verifiers".equals(cmd)) {
14539                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
14540            } else if ("version".equals(cmd)) {
14541                dumpState.setDump(DumpState.DUMP_VERSION);
14542            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
14543                dumpState.setDump(DumpState.DUMP_KEYSETS);
14544            } else if ("installs".equals(cmd)) {
14545                dumpState.setDump(DumpState.DUMP_INSTALLS);
14546            } else if ("write".equals(cmd)) {
14547                synchronized (mPackages) {
14548                    mSettings.writeLPr();
14549                    pw.println("Settings written.");
14550                    return;
14551                }
14552            }
14553        }
14554
14555        if (checkin) {
14556            pw.println("vers,1");
14557        }
14558
14559        // reader
14560        synchronized (mPackages) {
14561            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
14562                if (!checkin) {
14563                    if (dumpState.onTitlePrinted())
14564                        pw.println();
14565                    pw.println("Database versions:");
14566                    pw.print("  SDK Version:");
14567                    pw.print(" internal=");
14568                    pw.print(mSettings.mInternalSdkPlatform);
14569                    pw.print(" external=");
14570                    pw.println(mSettings.mExternalSdkPlatform);
14571                    pw.print("  DB Version:");
14572                    pw.print(" internal=");
14573                    pw.print(mSettings.mInternalDatabaseVersion);
14574                    pw.print(" external=");
14575                    pw.println(mSettings.mExternalDatabaseVersion);
14576                }
14577            }
14578
14579            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
14580                if (!checkin) {
14581                    if (dumpState.onTitlePrinted())
14582                        pw.println();
14583                    pw.println("Verifiers:");
14584                    pw.print("  Required: ");
14585                    pw.print(mRequiredVerifierPackage);
14586                    pw.print(" (uid=");
14587                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
14588                    pw.println(")");
14589                } else if (mRequiredVerifierPackage != null) {
14590                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
14591                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
14592                }
14593            }
14594
14595            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
14596                    packageName == null) {
14597                if (mIntentFilterVerifierComponent != null) {
14598                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
14599                    if (!checkin) {
14600                        if (dumpState.onTitlePrinted())
14601                            pw.println();
14602                        pw.println("Intent Filter Verifier:");
14603                        pw.print("  Using: ");
14604                        pw.print(verifierPackageName);
14605                        pw.print(" (uid=");
14606                        pw.print(getPackageUid(verifierPackageName, 0));
14607                        pw.println(")");
14608                    } else if (verifierPackageName != null) {
14609                        pw.print("ifv,"); pw.print(verifierPackageName);
14610                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
14611                    }
14612                } else {
14613                    pw.println();
14614                    pw.println("No Intent Filter Verifier available!");
14615                }
14616            }
14617
14618            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
14619                boolean printedHeader = false;
14620                final Iterator<String> it = mSharedLibraries.keySet().iterator();
14621                while (it.hasNext()) {
14622                    String name = it.next();
14623                    SharedLibraryEntry ent = mSharedLibraries.get(name);
14624                    if (!checkin) {
14625                        if (!printedHeader) {
14626                            if (dumpState.onTitlePrinted())
14627                                pw.println();
14628                            pw.println("Libraries:");
14629                            printedHeader = true;
14630                        }
14631                        pw.print("  ");
14632                    } else {
14633                        pw.print("lib,");
14634                    }
14635                    pw.print(name);
14636                    if (!checkin) {
14637                        pw.print(" -> ");
14638                    }
14639                    if (ent.path != null) {
14640                        if (!checkin) {
14641                            pw.print("(jar) ");
14642                            pw.print(ent.path);
14643                        } else {
14644                            pw.print(",jar,");
14645                            pw.print(ent.path);
14646                        }
14647                    } else {
14648                        if (!checkin) {
14649                            pw.print("(apk) ");
14650                            pw.print(ent.apk);
14651                        } else {
14652                            pw.print(",apk,");
14653                            pw.print(ent.apk);
14654                        }
14655                    }
14656                    pw.println();
14657                }
14658            }
14659
14660            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
14661                if (dumpState.onTitlePrinted())
14662                    pw.println();
14663                if (!checkin) {
14664                    pw.println("Features:");
14665                }
14666                Iterator<String> it = mAvailableFeatures.keySet().iterator();
14667                while (it.hasNext()) {
14668                    String name = it.next();
14669                    if (!checkin) {
14670                        pw.print("  ");
14671                    } else {
14672                        pw.print("feat,");
14673                    }
14674                    pw.println(name);
14675                }
14676            }
14677
14678            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
14679                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
14680                        : "Activity Resolver Table:", "  ", packageName,
14681                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14682                    dumpState.setTitlePrinted(true);
14683                }
14684                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
14685                        : "Receiver Resolver Table:", "  ", packageName,
14686                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14687                    dumpState.setTitlePrinted(true);
14688                }
14689                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
14690                        : "Service Resolver Table:", "  ", packageName,
14691                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14692                    dumpState.setTitlePrinted(true);
14693                }
14694                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
14695                        : "Provider Resolver Table:", "  ", packageName,
14696                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14697                    dumpState.setTitlePrinted(true);
14698                }
14699            }
14700
14701            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
14702                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14703                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14704                    int user = mSettings.mPreferredActivities.keyAt(i);
14705                    if (pir.dump(pw,
14706                            dumpState.getTitlePrinted()
14707                                ? "\nPreferred Activities User " + user + ":"
14708                                : "Preferred Activities User " + user + ":", "  ",
14709                            packageName, true, false)) {
14710                        dumpState.setTitlePrinted(true);
14711                    }
14712                }
14713            }
14714
14715            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
14716                pw.flush();
14717                FileOutputStream fout = new FileOutputStream(fd);
14718                BufferedOutputStream str = new BufferedOutputStream(fout);
14719                XmlSerializer serializer = new FastXmlSerializer();
14720                try {
14721                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
14722                    serializer.startDocument(null, true);
14723                    serializer.setFeature(
14724                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
14725                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
14726                    serializer.endDocument();
14727                    serializer.flush();
14728                } catch (IllegalArgumentException e) {
14729                    pw.println("Failed writing: " + e);
14730                } catch (IllegalStateException e) {
14731                    pw.println("Failed writing: " + e);
14732                } catch (IOException e) {
14733                    pw.println("Failed writing: " + e);
14734                }
14735            }
14736
14737            if (!checkin
14738                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
14739                    && packageName == null) {
14740                pw.println();
14741                int count = mSettings.mPackages.size();
14742                if (count == 0) {
14743                    pw.println("No domain preferred apps!");
14744                    pw.println();
14745                } else {
14746                    final String prefix = "  ";
14747                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
14748                    if (allPackageSettings.size() == 0) {
14749                        pw.println("No domain preferred apps!");
14750                        pw.println();
14751                    } else {
14752                        pw.println("Domain preferred apps status:");
14753                        pw.println();
14754                        count = 0;
14755                        for (PackageSetting ps : allPackageSettings) {
14756                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
14757                            if (ivi == null || ivi.getPackageName() == null) continue;
14758                            pw.println(prefix + "Package Name: " + ivi.getPackageName());
14759                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
14760                            pw.println(prefix + "Status: " + ivi.getStatusString());
14761                            pw.println();
14762                            count++;
14763                        }
14764                        if (count == 0) {
14765                            pw.println(prefix + "No domain preferred app status!");
14766                            pw.println();
14767                        }
14768                        for (int userId : sUserManager.getUserIds()) {
14769                            pw.println("Domain preferred apps for User " + userId + ":");
14770                            pw.println();
14771                            count = 0;
14772                            for (PackageSetting ps : allPackageSettings) {
14773                                IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
14774                                if (ivi == null || ivi.getPackageName() == null) {
14775                                    continue;
14776                                }
14777                                final int status = ps.getDomainVerificationStatusForUser(userId);
14778                                if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
14779                                    continue;
14780                                }
14781                                pw.println(prefix + "Package Name: " + ivi.getPackageName());
14782                                pw.println(prefix + "Domains: " + ivi.getDomainsString());
14783                                String statusStr = IntentFilterVerificationInfo.
14784                                        getStatusStringFromValue(status);
14785                                pw.println(prefix + "Status: " + statusStr);
14786                                pw.println();
14787                                count++;
14788                            }
14789                            if (count == 0) {
14790                                pw.println(prefix + "No domain preferred apps!");
14791                                pw.println();
14792                            }
14793                        }
14794                    }
14795                }
14796            }
14797
14798            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
14799                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
14800                if (packageName == null && permissionNames == null) {
14801                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
14802                        if (iperm == 0) {
14803                            if (dumpState.onTitlePrinted())
14804                                pw.println();
14805                            pw.println("AppOp Permissions:");
14806                        }
14807                        pw.print("  AppOp Permission ");
14808                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
14809                        pw.println(":");
14810                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
14811                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
14812                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
14813                        }
14814                    }
14815                }
14816            }
14817
14818            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
14819                boolean printedSomething = false;
14820                for (PackageParser.Provider p : mProviders.mProviders.values()) {
14821                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14822                        continue;
14823                    }
14824                    if (!printedSomething) {
14825                        if (dumpState.onTitlePrinted())
14826                            pw.println();
14827                        pw.println("Registered ContentProviders:");
14828                        printedSomething = true;
14829                    }
14830                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
14831                    pw.print("    "); pw.println(p.toString());
14832                }
14833                printedSomething = false;
14834                for (Map.Entry<String, PackageParser.Provider> entry :
14835                        mProvidersByAuthority.entrySet()) {
14836                    PackageParser.Provider p = entry.getValue();
14837                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14838                        continue;
14839                    }
14840                    if (!printedSomething) {
14841                        if (dumpState.onTitlePrinted())
14842                            pw.println();
14843                        pw.println("ContentProvider Authorities:");
14844                        printedSomething = true;
14845                    }
14846                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
14847                    pw.print("    "); pw.println(p.toString());
14848                    if (p.info != null && p.info.applicationInfo != null) {
14849                        final String appInfo = p.info.applicationInfo.toString();
14850                        pw.print("      applicationInfo="); pw.println(appInfo);
14851                    }
14852                }
14853            }
14854
14855            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
14856                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
14857            }
14858
14859            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
14860                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
14861            }
14862
14863            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
14864                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
14865            }
14866
14867            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
14868                // XXX should handle packageName != null by dumping only install data that
14869                // the given package is involved with.
14870                if (dumpState.onTitlePrinted()) pw.println();
14871                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
14872            }
14873
14874            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
14875                if (dumpState.onTitlePrinted()) pw.println();
14876                mSettings.dumpReadMessagesLPr(pw, dumpState);
14877
14878                pw.println();
14879                pw.println("Package warning messages:");
14880                BufferedReader in = null;
14881                String line = null;
14882                try {
14883                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
14884                    while ((line = in.readLine()) != null) {
14885                        if (line.contains("ignored: updated version")) continue;
14886                        pw.println(line);
14887                    }
14888                } catch (IOException ignored) {
14889                } finally {
14890                    IoUtils.closeQuietly(in);
14891                }
14892            }
14893
14894            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
14895                BufferedReader in = null;
14896                String line = null;
14897                try {
14898                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
14899                    while ((line = in.readLine()) != null) {
14900                        if (line.contains("ignored: updated version")) continue;
14901                        pw.print("msg,");
14902                        pw.println(line);
14903                    }
14904                } catch (IOException ignored) {
14905                } finally {
14906                    IoUtils.closeQuietly(in);
14907                }
14908            }
14909        }
14910    }
14911
14912    // ------- apps on sdcard specific code -------
14913    static final boolean DEBUG_SD_INSTALL = false;
14914
14915    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
14916
14917    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
14918
14919    private boolean mMediaMounted = false;
14920
14921    static String getEncryptKey() {
14922        try {
14923            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
14924                    SD_ENCRYPTION_KEYSTORE_NAME);
14925            if (sdEncKey == null) {
14926                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
14927                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
14928                if (sdEncKey == null) {
14929                    Slog.e(TAG, "Failed to create encryption keys");
14930                    return null;
14931                }
14932            }
14933            return sdEncKey;
14934        } catch (NoSuchAlgorithmException nsae) {
14935            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
14936            return null;
14937        } catch (IOException ioe) {
14938            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
14939            return null;
14940        }
14941    }
14942
14943    /*
14944     * Update media status on PackageManager.
14945     */
14946    @Override
14947    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
14948        int callingUid = Binder.getCallingUid();
14949        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
14950            throw new SecurityException("Media status can only be updated by the system");
14951        }
14952        // reader; this apparently protects mMediaMounted, but should probably
14953        // be a different lock in that case.
14954        synchronized (mPackages) {
14955            Log.i(TAG, "Updating external media status from "
14956                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
14957                    + (mediaStatus ? "mounted" : "unmounted"));
14958            if (DEBUG_SD_INSTALL)
14959                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
14960                        + ", mMediaMounted=" + mMediaMounted);
14961            if (mediaStatus == mMediaMounted) {
14962                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
14963                        : 0, -1);
14964                mHandler.sendMessage(msg);
14965                return;
14966            }
14967            mMediaMounted = mediaStatus;
14968        }
14969        // Queue up an async operation since the package installation may take a
14970        // little while.
14971        mHandler.post(new Runnable() {
14972            public void run() {
14973                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
14974            }
14975        });
14976    }
14977
14978    /**
14979     * Called by MountService when the initial ASECs to scan are available.
14980     * Should block until all the ASEC containers are finished being scanned.
14981     */
14982    public void scanAvailableAsecs() {
14983        updateExternalMediaStatusInner(true, false, false);
14984        if (mShouldRestoreconData) {
14985            SELinuxMMAC.setRestoreconDone();
14986            mShouldRestoreconData = false;
14987        }
14988    }
14989
14990    /*
14991     * Collect information of applications on external media, map them against
14992     * existing containers and update information based on current mount status.
14993     * Please note that we always have to report status if reportStatus has been
14994     * set to true especially when unloading packages.
14995     */
14996    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
14997            boolean externalStorage) {
14998        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
14999        int[] uidArr = EmptyArray.INT;
15000
15001        final String[] list = PackageHelper.getSecureContainerList();
15002        if (ArrayUtils.isEmpty(list)) {
15003            Log.i(TAG, "No secure containers found");
15004        } else {
15005            // Process list of secure containers and categorize them
15006            // as active or stale based on their package internal state.
15007
15008            // reader
15009            synchronized (mPackages) {
15010                for (String cid : list) {
15011                    // Leave stages untouched for now; installer service owns them
15012                    if (PackageInstallerService.isStageName(cid)) continue;
15013
15014                    if (DEBUG_SD_INSTALL)
15015                        Log.i(TAG, "Processing container " + cid);
15016                    String pkgName = getAsecPackageName(cid);
15017                    if (pkgName == null) {
15018                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
15019                        continue;
15020                    }
15021                    if (DEBUG_SD_INSTALL)
15022                        Log.i(TAG, "Looking for pkg : " + pkgName);
15023
15024                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
15025                    if (ps == null) {
15026                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
15027                        continue;
15028                    }
15029
15030                    /*
15031                     * Skip packages that are not external if we're unmounting
15032                     * external storage.
15033                     */
15034                    if (externalStorage && !isMounted && !isExternal(ps)) {
15035                        continue;
15036                    }
15037
15038                    final AsecInstallArgs args = new AsecInstallArgs(cid,
15039                            getAppDexInstructionSets(ps), ps.isForwardLocked());
15040                    // The package status is changed only if the code path
15041                    // matches between settings and the container id.
15042                    if (ps.codePathString != null
15043                            && ps.codePathString.startsWith(args.getCodePath())) {
15044                        if (DEBUG_SD_INSTALL) {
15045                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
15046                                    + " at code path: " + ps.codePathString);
15047                        }
15048
15049                        // We do have a valid package installed on sdcard
15050                        processCids.put(args, ps.codePathString);
15051                        final int uid = ps.appId;
15052                        if (uid != -1) {
15053                            uidArr = ArrayUtils.appendInt(uidArr, uid);
15054                        }
15055                    } else {
15056                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
15057                                + ps.codePathString);
15058                    }
15059                }
15060            }
15061
15062            Arrays.sort(uidArr);
15063        }
15064
15065        // Process packages with valid entries.
15066        if (isMounted) {
15067            if (DEBUG_SD_INSTALL)
15068                Log.i(TAG, "Loading packages");
15069            loadMediaPackages(processCids, uidArr);
15070            startCleaningPackages();
15071            mInstallerService.onSecureContainersAvailable();
15072        } else {
15073            if (DEBUG_SD_INSTALL)
15074                Log.i(TAG, "Unloading packages");
15075            unloadMediaPackages(processCids, uidArr, reportStatus);
15076        }
15077    }
15078
15079    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15080            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
15081        final int size = infos.size();
15082        final String[] packageNames = new String[size];
15083        final int[] packageUids = new int[size];
15084        for (int i = 0; i < size; i++) {
15085            final ApplicationInfo info = infos.get(i);
15086            packageNames[i] = info.packageName;
15087            packageUids[i] = info.uid;
15088        }
15089        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
15090                finishedReceiver);
15091    }
15092
15093    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15094            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15095        sendResourcesChangedBroadcast(mediaStatus, replacing,
15096                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
15097    }
15098
15099    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15100            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15101        int size = pkgList.length;
15102        if (size > 0) {
15103            // Send broadcasts here
15104            Bundle extras = new Bundle();
15105            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
15106            if (uidArr != null) {
15107                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
15108            }
15109            if (replacing) {
15110                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
15111            }
15112            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
15113                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
15114            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
15115        }
15116    }
15117
15118   /*
15119     * Look at potentially valid container ids from processCids If package
15120     * information doesn't match the one on record or package scanning fails,
15121     * the cid is added to list of removeCids. We currently don't delete stale
15122     * containers.
15123     */
15124    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
15125        ArrayList<String> pkgList = new ArrayList<String>();
15126        Set<AsecInstallArgs> keys = processCids.keySet();
15127
15128        for (AsecInstallArgs args : keys) {
15129            String codePath = processCids.get(args);
15130            if (DEBUG_SD_INSTALL)
15131                Log.i(TAG, "Loading container : " + args.cid);
15132            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15133            try {
15134                // Make sure there are no container errors first.
15135                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
15136                    Slog.e(TAG, "Failed to mount cid : " + args.cid
15137                            + " when installing from sdcard");
15138                    continue;
15139                }
15140                // Check code path here.
15141                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
15142                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
15143                            + " does not match one in settings " + codePath);
15144                    continue;
15145                }
15146                // Parse package
15147                int parseFlags = mDefParseFlags;
15148                if (args.isExternalAsec()) {
15149                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
15150                }
15151                if (args.isFwdLocked()) {
15152                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
15153                }
15154
15155                synchronized (mInstallLock) {
15156                    PackageParser.Package pkg = null;
15157                    try {
15158                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
15159                    } catch (PackageManagerException e) {
15160                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
15161                    }
15162                    // Scan the package
15163                    if (pkg != null) {
15164                        /*
15165                         * TODO why is the lock being held? doPostInstall is
15166                         * called in other places without the lock. This needs
15167                         * to be straightened out.
15168                         */
15169                        // writer
15170                        synchronized (mPackages) {
15171                            retCode = PackageManager.INSTALL_SUCCEEDED;
15172                            pkgList.add(pkg.packageName);
15173                            // Post process args
15174                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
15175                                    pkg.applicationInfo.uid);
15176                        }
15177                    } else {
15178                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
15179                    }
15180                }
15181
15182            } finally {
15183                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
15184                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
15185                }
15186            }
15187        }
15188        // writer
15189        synchronized (mPackages) {
15190            // If the platform SDK has changed since the last time we booted,
15191            // we need to re-grant app permission to catch any new ones that
15192            // appear. This is really a hack, and means that apps can in some
15193            // cases get permissions that the user didn't initially explicitly
15194            // allow... it would be nice to have some better way to handle
15195            // this situation.
15196            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
15197            if (regrantPermissions)
15198                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
15199                        + mSdkVersion + "; regranting permissions for external storage");
15200            mSettings.mExternalSdkPlatform = mSdkVersion;
15201
15202            // Make sure group IDs have been assigned, and any permission
15203            // changes in other apps are accounted for
15204            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
15205                    | (regrantPermissions
15206                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
15207                            : 0));
15208
15209            mSettings.updateExternalDatabaseVersion();
15210
15211            // can downgrade to reader
15212            // Persist settings
15213            mSettings.writeLPr();
15214        }
15215        // Send a broadcast to let everyone know we are done processing
15216        if (pkgList.size() > 0) {
15217            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
15218        }
15219    }
15220
15221   /*
15222     * Utility method to unload a list of specified containers
15223     */
15224    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
15225        // Just unmount all valid containers.
15226        for (AsecInstallArgs arg : cidArgs) {
15227            synchronized (mInstallLock) {
15228                arg.doPostDeleteLI(false);
15229           }
15230       }
15231   }
15232
15233    /*
15234     * Unload packages mounted on external media. This involves deleting package
15235     * data from internal structures, sending broadcasts about diabled packages,
15236     * gc'ing to free up references, unmounting all secure containers
15237     * corresponding to packages on external media, and posting a
15238     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
15239     * that we always have to post this message if status has been requested no
15240     * matter what.
15241     */
15242    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
15243            final boolean reportStatus) {
15244        if (DEBUG_SD_INSTALL)
15245            Log.i(TAG, "unloading media packages");
15246        ArrayList<String> pkgList = new ArrayList<String>();
15247        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
15248        final Set<AsecInstallArgs> keys = processCids.keySet();
15249        for (AsecInstallArgs args : keys) {
15250            String pkgName = args.getPackageName();
15251            if (DEBUG_SD_INSTALL)
15252                Log.i(TAG, "Trying to unload pkg : " + pkgName);
15253            // Delete package internally
15254            PackageRemovedInfo outInfo = new PackageRemovedInfo();
15255            synchronized (mInstallLock) {
15256                boolean res = deletePackageLI(pkgName, null, false, null, null,
15257                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
15258                if (res) {
15259                    pkgList.add(pkgName);
15260                } else {
15261                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
15262                    failedList.add(args);
15263                }
15264            }
15265        }
15266
15267        // reader
15268        synchronized (mPackages) {
15269            // We didn't update the settings after removing each package;
15270            // write them now for all packages.
15271            mSettings.writeLPr();
15272        }
15273
15274        // We have to absolutely send UPDATED_MEDIA_STATUS only
15275        // after confirming that all the receivers processed the ordered
15276        // broadcast when packages get disabled, force a gc to clean things up.
15277        // and unload all the containers.
15278        if (pkgList.size() > 0) {
15279            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
15280                    new IIntentReceiver.Stub() {
15281                public void performReceive(Intent intent, int resultCode, String data,
15282                        Bundle extras, boolean ordered, boolean sticky,
15283                        int sendingUser) throws RemoteException {
15284                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
15285                            reportStatus ? 1 : 0, 1, keys);
15286                    mHandler.sendMessage(msg);
15287                }
15288            });
15289        } else {
15290            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
15291                    keys);
15292            mHandler.sendMessage(msg);
15293        }
15294    }
15295
15296    private void loadPrivatePackages(VolumeInfo vol) {
15297        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
15298        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
15299        synchronized (mInstallLock) {
15300        synchronized (mPackages) {
15301            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15302            for (PackageSetting ps : packages) {
15303                final PackageParser.Package pkg;
15304                try {
15305                    pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null);
15306                    loaded.add(pkg.applicationInfo);
15307                } catch (PackageManagerException e) {
15308                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
15309                }
15310            }
15311
15312            // TODO: regrant any permissions that changed based since original install
15313
15314            mSettings.writeLPr();
15315        }
15316        }
15317
15318        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
15319        sendResourcesChangedBroadcast(true, false, loaded, null);
15320    }
15321
15322    private void unloadPrivatePackages(VolumeInfo vol) {
15323        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
15324        synchronized (mInstallLock) {
15325        synchronized (mPackages) {
15326            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15327            for (PackageSetting ps : packages) {
15328                if (ps.pkg == null) continue;
15329
15330                final ApplicationInfo info = ps.pkg.applicationInfo;
15331                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
15332                if (deletePackageLI(ps.name, null, false, null, null,
15333                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
15334                    unloaded.add(info);
15335                } else {
15336                    Slog.w(TAG, "Failed to unload " + ps.codePath);
15337                }
15338            }
15339
15340            mSettings.writeLPr();
15341        }
15342        }
15343
15344        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
15345        sendResourcesChangedBroadcast(false, false, unloaded, null);
15346    }
15347
15348    /**
15349     * Examine all users present on given mounted volume, and destroy data
15350     * belonging to users that are no longer valid, or whose user ID has been
15351     * recycled.
15352     */
15353    private void reconcileUsers(String volumeUuid) {
15354        final File[] files = Environment.getDataUserDirectory(volumeUuid).listFiles();
15355        if (ArrayUtils.isEmpty(files)) {
15356            Slog.d(TAG, "No users found on " + volumeUuid);
15357            return;
15358        }
15359
15360        for (File file : files) {
15361            if (!file.isDirectory()) continue;
15362
15363            final int userId;
15364            final UserInfo info;
15365            try {
15366                userId = Integer.parseInt(file.getName());
15367                info = sUserManager.getUserInfo(userId);
15368            } catch (NumberFormatException e) {
15369                Slog.w(TAG, "Invalid user directory " + file);
15370                continue;
15371            }
15372
15373            boolean destroyUser = false;
15374            if (info == null) {
15375                logCriticalInfo(Log.WARN, "Destroying user directory " + file
15376                        + " because no matching user was found");
15377                destroyUser = true;
15378            } else {
15379                try {
15380                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
15381                } catch (IOException e) {
15382                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
15383                            + " because we failed to enforce serial number: " + e);
15384                    destroyUser = true;
15385                }
15386            }
15387
15388            if (destroyUser) {
15389                synchronized (mInstallLock) {
15390                    mInstaller.removeUserDataDirs(volumeUuid, userId);
15391                }
15392            }
15393        }
15394
15395        final UserManager um = mContext.getSystemService(UserManager.class);
15396        for (UserInfo user : um.getUsers()) {
15397            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
15398            if (userDir.exists()) continue;
15399
15400            try {
15401                UserManagerService.prepareUserDirectory(mContext, volumeUuid, user.id);
15402                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
15403            } catch (IOException e) {
15404                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
15405            }
15406        }
15407    }
15408
15409    /**
15410     * Examine all apps present on given mounted volume, and destroy apps that
15411     * aren't expected, either due to uninstallation or reinstallation on
15412     * another volume.
15413     */
15414    private void reconcileApps(String volumeUuid) {
15415        final File[] files = Environment.getDataAppDirectory(volumeUuid).listFiles();
15416        if (ArrayUtils.isEmpty(files)) {
15417            Slog.d(TAG, "No apps found on " + volumeUuid);
15418            return;
15419        }
15420
15421        for (File file : files) {
15422            final boolean isPackage = (isApkFile(file) || file.isDirectory())
15423                    && !PackageInstallerService.isStageName(file.getName());
15424            if (!isPackage) {
15425                // Ignore entries which are not packages
15426                continue;
15427            }
15428
15429            boolean destroyApp = false;
15430            String packageName = null;
15431            try {
15432                final PackageLite pkg = PackageParser.parsePackageLite(file,
15433                        PackageParser.PARSE_MUST_BE_APK);
15434                packageName = pkg.packageName;
15435
15436                synchronized (mPackages) {
15437                    final PackageSetting ps = mSettings.mPackages.get(packageName);
15438                    if (ps == null) {
15439                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
15440                                + volumeUuid + " because we found no install record");
15441                        destroyApp = true;
15442                    } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
15443                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
15444                                + volumeUuid + " because we expected it on " + ps.volumeUuid);
15445                        destroyApp = true;
15446                    }
15447                }
15448
15449            } catch (PackageParserException e) {
15450                logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
15451                destroyApp = true;
15452            }
15453
15454            if (destroyApp) {
15455                synchronized (mInstallLock) {
15456                    if (packageName != null) {
15457                        removeDataDirsLI(volumeUuid, packageName);
15458                    }
15459                    if (file.isDirectory()) {
15460                        mInstaller.rmPackageDir(file.getAbsolutePath());
15461                    } else {
15462                        file.delete();
15463                    }
15464                }
15465            }
15466        }
15467    }
15468
15469    private void unfreezePackage(String packageName) {
15470        synchronized (mPackages) {
15471            final PackageSetting ps = mSettings.mPackages.get(packageName);
15472            if (ps != null) {
15473                ps.frozen = false;
15474            }
15475        }
15476    }
15477
15478    @Override
15479    public int movePackage(final String packageName, final String volumeUuid) {
15480        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15481
15482        final int moveId = mNextMoveId.getAndIncrement();
15483        try {
15484            movePackageInternal(packageName, volumeUuid, moveId);
15485        } catch (PackageManagerException e) {
15486            Slog.w(TAG, "Failed to move " + packageName, e);
15487            mMoveCallbacks.notifyStatusChanged(moveId,
15488                    PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15489        }
15490        return moveId;
15491    }
15492
15493    private void movePackageInternal(final String packageName, final String volumeUuid,
15494            final int moveId) throws PackageManagerException {
15495        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
15496        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15497        final PackageManager pm = mContext.getPackageManager();
15498
15499        final boolean currentAsec;
15500        final String currentVolumeUuid;
15501        final File codeFile;
15502        final String installerPackageName;
15503        final String packageAbiOverride;
15504        final int appId;
15505        final String seinfo;
15506        final String label;
15507
15508        // reader
15509        synchronized (mPackages) {
15510            final PackageParser.Package pkg = mPackages.get(packageName);
15511            final PackageSetting ps = mSettings.mPackages.get(packageName);
15512            if (pkg == null || ps == null) {
15513                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
15514            }
15515
15516            if (pkg.applicationInfo.isSystemApp()) {
15517                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
15518                        "Cannot move system application");
15519            }
15520
15521            if (Objects.equals(ps.volumeUuid, volumeUuid)) {
15522                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15523                        "Package already moved to " + volumeUuid);
15524            }
15525
15526            final File probe = new File(pkg.codePath);
15527            final File probeOat = new File(probe, "oat");
15528            if (!probe.isDirectory() || !probeOat.isDirectory()) {
15529                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15530                        "Move only supported for modern cluster style installs");
15531            }
15532
15533            if (ps.frozen) {
15534                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
15535                        "Failed to move already frozen package");
15536            }
15537            ps.frozen = true;
15538
15539            currentAsec = pkg.applicationInfo.isForwardLocked()
15540                    || pkg.applicationInfo.isExternalAsec();
15541            currentVolumeUuid = ps.volumeUuid;
15542            codeFile = new File(pkg.codePath);
15543            installerPackageName = ps.installerPackageName;
15544            packageAbiOverride = ps.cpuAbiOverrideString;
15545            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
15546            seinfo = pkg.applicationInfo.seinfo;
15547            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
15548        }
15549
15550        // Now that we're guarded by frozen state, kill app during move
15551        killApplication(packageName, appId, "move pkg");
15552
15553        final Bundle extras = new Bundle();
15554        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
15555        extras.putString(Intent.EXTRA_TITLE, label);
15556        mMoveCallbacks.notifyCreated(moveId, extras);
15557
15558        int installFlags;
15559        final boolean moveCompleteApp;
15560        final File measurePath;
15561
15562        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
15563            installFlags = INSTALL_INTERNAL;
15564            moveCompleteApp = !currentAsec;
15565            measurePath = Environment.getDataAppDirectory(volumeUuid);
15566        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
15567            installFlags = INSTALL_EXTERNAL;
15568            moveCompleteApp = false;
15569            measurePath = storage.getPrimaryPhysicalVolume().getPath();
15570        } else {
15571            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
15572            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
15573                    || !volume.isMountedWritable()) {
15574                unfreezePackage(packageName);
15575                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15576                        "Move location not mounted private volume");
15577            }
15578
15579            Preconditions.checkState(!currentAsec);
15580
15581            installFlags = INSTALL_INTERNAL;
15582            moveCompleteApp = true;
15583            measurePath = Environment.getDataAppDirectory(volumeUuid);
15584        }
15585
15586        final PackageStats stats = new PackageStats(null, -1);
15587        synchronized (mInstaller) {
15588            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
15589                unfreezePackage(packageName);
15590                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15591                        "Failed to measure package size");
15592            }
15593        }
15594
15595        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
15596                + stats.dataSize);
15597
15598        final long startFreeBytes = measurePath.getFreeSpace();
15599        final long sizeBytes;
15600        if (moveCompleteApp) {
15601            sizeBytes = stats.codeSize + stats.dataSize;
15602        } else {
15603            sizeBytes = stats.codeSize;
15604        }
15605
15606        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
15607            unfreezePackage(packageName);
15608            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15609                    "Not enough free space to move");
15610        }
15611
15612        mMoveCallbacks.notifyStatusChanged(moveId, 10);
15613
15614        final CountDownLatch installedLatch = new CountDownLatch(1);
15615        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
15616            @Override
15617            public void onUserActionRequired(Intent intent) throws RemoteException {
15618                throw new IllegalStateException();
15619            }
15620
15621            @Override
15622            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
15623                    Bundle extras) throws RemoteException {
15624                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
15625                        + PackageManager.installStatusToString(returnCode, msg));
15626
15627                installedLatch.countDown();
15628
15629                // Regardless of success or failure of the move operation,
15630                // always unfreeze the package
15631                unfreezePackage(packageName);
15632
15633                final int status = PackageManager.installStatusToPublicStatus(returnCode);
15634                switch (status) {
15635                    case PackageInstaller.STATUS_SUCCESS:
15636                        mMoveCallbacks.notifyStatusChanged(moveId,
15637                                PackageManager.MOVE_SUCCEEDED);
15638                        break;
15639                    case PackageInstaller.STATUS_FAILURE_STORAGE:
15640                        mMoveCallbacks.notifyStatusChanged(moveId,
15641                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
15642                        break;
15643                    default:
15644                        mMoveCallbacks.notifyStatusChanged(moveId,
15645                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15646                        break;
15647                }
15648            }
15649        };
15650
15651        final MoveInfo move;
15652        if (moveCompleteApp) {
15653            // Kick off a thread to report progress estimates
15654            new Thread() {
15655                @Override
15656                public void run() {
15657                    while (true) {
15658                        try {
15659                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
15660                                break;
15661                            }
15662                        } catch (InterruptedException ignored) {
15663                        }
15664
15665                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
15666                        final int progress = 10 + (int) MathUtils.constrain(
15667                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
15668                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
15669                    }
15670                }
15671            }.start();
15672
15673            final String dataAppName = codeFile.getName();
15674            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
15675                    dataAppName, appId, seinfo);
15676        } else {
15677            move = null;
15678        }
15679
15680        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
15681
15682        final Message msg = mHandler.obtainMessage(INIT_COPY);
15683        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
15684        msg.obj = new InstallParams(origin, move, installObserver, installFlags,
15685                installerPackageName, volumeUuid, null, user, packageAbiOverride);
15686        mHandler.sendMessage(msg);
15687    }
15688
15689    @Override
15690    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
15691        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15692
15693        final int realMoveId = mNextMoveId.getAndIncrement();
15694        final Bundle extras = new Bundle();
15695        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
15696        mMoveCallbacks.notifyCreated(realMoveId, extras);
15697
15698        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
15699            @Override
15700            public void onCreated(int moveId, Bundle extras) {
15701                // Ignored
15702            }
15703
15704            @Override
15705            public void onStatusChanged(int moveId, int status, long estMillis) {
15706                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
15707            }
15708        };
15709
15710        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15711        storage.setPrimaryStorageUuid(volumeUuid, callback);
15712        return realMoveId;
15713    }
15714
15715    @Override
15716    public int getMoveStatus(int moveId) {
15717        mContext.enforceCallingOrSelfPermission(
15718                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15719        return mMoveCallbacks.mLastStatus.get(moveId);
15720    }
15721
15722    @Override
15723    public void registerMoveCallback(IPackageMoveObserver callback) {
15724        mContext.enforceCallingOrSelfPermission(
15725                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15726        mMoveCallbacks.register(callback);
15727    }
15728
15729    @Override
15730    public void unregisterMoveCallback(IPackageMoveObserver callback) {
15731        mContext.enforceCallingOrSelfPermission(
15732                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15733        mMoveCallbacks.unregister(callback);
15734    }
15735
15736    @Override
15737    public boolean setInstallLocation(int loc) {
15738        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
15739                null);
15740        if (getInstallLocation() == loc) {
15741            return true;
15742        }
15743        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
15744                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
15745            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
15746                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
15747            return true;
15748        }
15749        return false;
15750   }
15751
15752    @Override
15753    public int getInstallLocation() {
15754        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15755                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
15756                PackageHelper.APP_INSTALL_AUTO);
15757    }
15758
15759    /** Called by UserManagerService */
15760    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
15761        mDirtyUsers.remove(userHandle);
15762        mSettings.removeUserLPw(userHandle);
15763        mPendingBroadcasts.remove(userHandle);
15764        if (mInstaller != null) {
15765            // Technically, we shouldn't be doing this with the package lock
15766            // held.  However, this is very rare, and there is already so much
15767            // other disk I/O going on, that we'll let it slide for now.
15768            final StorageManager storage = mContext.getSystemService(StorageManager.class);
15769            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
15770                final String volumeUuid = vol.getFsUuid();
15771                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
15772                mInstaller.removeUserDataDirs(volumeUuid, userHandle);
15773            }
15774        }
15775        mUserNeedsBadging.delete(userHandle);
15776        removeUnusedPackagesLILPw(userManager, userHandle);
15777    }
15778
15779    /**
15780     * We're removing userHandle and would like to remove any downloaded packages
15781     * that are no longer in use by any other user.
15782     * @param userHandle the user being removed
15783     */
15784    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
15785        final boolean DEBUG_CLEAN_APKS = false;
15786        int [] users = userManager.getUserIdsLPr();
15787        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
15788        while (psit.hasNext()) {
15789            PackageSetting ps = psit.next();
15790            if (ps.pkg == null) {
15791                continue;
15792            }
15793            final String packageName = ps.pkg.packageName;
15794            // Skip over if system app
15795            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15796                continue;
15797            }
15798            if (DEBUG_CLEAN_APKS) {
15799                Slog.i(TAG, "Checking package " + packageName);
15800            }
15801            boolean keep = false;
15802            for (int i = 0; i < users.length; i++) {
15803                if (users[i] != userHandle && ps.getInstalled(users[i])) {
15804                    keep = true;
15805                    if (DEBUG_CLEAN_APKS) {
15806                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
15807                                + users[i]);
15808                    }
15809                    break;
15810                }
15811            }
15812            if (!keep) {
15813                if (DEBUG_CLEAN_APKS) {
15814                    Slog.i(TAG, "  Removing package " + packageName);
15815                }
15816                mHandler.post(new Runnable() {
15817                    public void run() {
15818                        deletePackageX(packageName, userHandle, 0);
15819                    } //end run
15820                });
15821            }
15822        }
15823    }
15824
15825    /** Called by UserManagerService */
15826    void createNewUserLILPw(int userHandle) {
15827        if (mInstaller != null) {
15828            mInstaller.createUserConfig(userHandle);
15829            mSettings.createNewUserLILPw(this, mInstaller, userHandle);
15830            applyFactoryDefaultBrowserLPw(userHandle);
15831        }
15832    }
15833
15834    void newUserCreatedLILPw(final int userHandle) {
15835        // We cannot grant the default permissions with a lock held as
15836        // we query providers from other components for default handlers
15837        // such as enabled IMEs, etc.
15838        mHandler.post(new Runnable() {
15839            @Override
15840            public void run() {
15841                mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
15842            }
15843        });
15844    }
15845
15846    @Override
15847    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
15848        mContext.enforceCallingOrSelfPermission(
15849                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15850                "Only package verification agents can read the verifier device identity");
15851
15852        synchronized (mPackages) {
15853            return mSettings.getVerifierDeviceIdentityLPw();
15854        }
15855    }
15856
15857    @Override
15858    public void setPermissionEnforced(String permission, boolean enforced) {
15859        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
15860        if (READ_EXTERNAL_STORAGE.equals(permission)) {
15861            synchronized (mPackages) {
15862                if (mSettings.mReadExternalStorageEnforced == null
15863                        || mSettings.mReadExternalStorageEnforced != enforced) {
15864                    mSettings.mReadExternalStorageEnforced = enforced;
15865                    mSettings.writeLPr();
15866                }
15867            }
15868            // kill any non-foreground processes so we restart them and
15869            // grant/revoke the GID.
15870            final IActivityManager am = ActivityManagerNative.getDefault();
15871            if (am != null) {
15872                final long token = Binder.clearCallingIdentity();
15873                try {
15874                    am.killProcessesBelowForeground("setPermissionEnforcement");
15875                } catch (RemoteException e) {
15876                } finally {
15877                    Binder.restoreCallingIdentity(token);
15878                }
15879            }
15880        } else {
15881            throw new IllegalArgumentException("No selective enforcement for " + permission);
15882        }
15883    }
15884
15885    @Override
15886    @Deprecated
15887    public boolean isPermissionEnforced(String permission) {
15888        return true;
15889    }
15890
15891    @Override
15892    public boolean isStorageLow() {
15893        final long token = Binder.clearCallingIdentity();
15894        try {
15895            final DeviceStorageMonitorInternal
15896                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
15897            if (dsm != null) {
15898                return dsm.isMemoryLow();
15899            } else {
15900                return false;
15901            }
15902        } finally {
15903            Binder.restoreCallingIdentity(token);
15904        }
15905    }
15906
15907    @Override
15908    public IPackageInstaller getPackageInstaller() {
15909        return mInstallerService;
15910    }
15911
15912    private boolean userNeedsBadging(int userId) {
15913        int index = mUserNeedsBadging.indexOfKey(userId);
15914        if (index < 0) {
15915            final UserInfo userInfo;
15916            final long token = Binder.clearCallingIdentity();
15917            try {
15918                userInfo = sUserManager.getUserInfo(userId);
15919            } finally {
15920                Binder.restoreCallingIdentity(token);
15921            }
15922            final boolean b;
15923            if (userInfo != null && userInfo.isManagedProfile()) {
15924                b = true;
15925            } else {
15926                b = false;
15927            }
15928            mUserNeedsBadging.put(userId, b);
15929            return b;
15930        }
15931        return mUserNeedsBadging.valueAt(index);
15932    }
15933
15934    @Override
15935    public KeySet getKeySetByAlias(String packageName, String alias) {
15936        if (packageName == null || alias == null) {
15937            return null;
15938        }
15939        synchronized(mPackages) {
15940            final PackageParser.Package pkg = mPackages.get(packageName);
15941            if (pkg == null) {
15942                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15943                throw new IllegalArgumentException("Unknown package: " + packageName);
15944            }
15945            KeySetManagerService ksms = mSettings.mKeySetManagerService;
15946            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
15947        }
15948    }
15949
15950    @Override
15951    public KeySet getSigningKeySet(String packageName) {
15952        if (packageName == null) {
15953            return null;
15954        }
15955        synchronized(mPackages) {
15956            final PackageParser.Package pkg = mPackages.get(packageName);
15957            if (pkg == null) {
15958                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15959                throw new IllegalArgumentException("Unknown package: " + packageName);
15960            }
15961            if (pkg.applicationInfo.uid != Binder.getCallingUid()
15962                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
15963                throw new SecurityException("May not access signing KeySet of other apps.");
15964            }
15965            KeySetManagerService ksms = mSettings.mKeySetManagerService;
15966            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
15967        }
15968    }
15969
15970    @Override
15971    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
15972        if (packageName == null || ks == null) {
15973            return false;
15974        }
15975        synchronized(mPackages) {
15976            final PackageParser.Package pkg = mPackages.get(packageName);
15977            if (pkg == null) {
15978                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15979                throw new IllegalArgumentException("Unknown package: " + packageName);
15980            }
15981            IBinder ksh = ks.getToken();
15982            if (ksh instanceof KeySetHandle) {
15983                KeySetManagerService ksms = mSettings.mKeySetManagerService;
15984                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
15985            }
15986            return false;
15987        }
15988    }
15989
15990    @Override
15991    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
15992        if (packageName == null || ks == null) {
15993            return false;
15994        }
15995        synchronized(mPackages) {
15996            final PackageParser.Package pkg = mPackages.get(packageName);
15997            if (pkg == null) {
15998                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15999                throw new IllegalArgumentException("Unknown package: " + packageName);
16000            }
16001            IBinder ksh = ks.getToken();
16002            if (ksh instanceof KeySetHandle) {
16003                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16004                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
16005            }
16006            return false;
16007        }
16008    }
16009
16010    public void getUsageStatsIfNoPackageUsageInfo() {
16011        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
16012            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
16013            if (usm == null) {
16014                throw new IllegalStateException("UsageStatsManager must be initialized");
16015            }
16016            long now = System.currentTimeMillis();
16017            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
16018            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
16019                String packageName = entry.getKey();
16020                PackageParser.Package pkg = mPackages.get(packageName);
16021                if (pkg == null) {
16022                    continue;
16023                }
16024                UsageStats usage = entry.getValue();
16025                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
16026                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
16027            }
16028        }
16029    }
16030
16031    /**
16032     * Check and throw if the given before/after packages would be considered a
16033     * downgrade.
16034     */
16035    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
16036            throws PackageManagerException {
16037        if (after.versionCode < before.mVersionCode) {
16038            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16039                    "Update version code " + after.versionCode + " is older than current "
16040                    + before.mVersionCode);
16041        } else if (after.versionCode == before.mVersionCode) {
16042            if (after.baseRevisionCode < before.baseRevisionCode) {
16043                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16044                        "Update base revision code " + after.baseRevisionCode
16045                        + " is older than current " + before.baseRevisionCode);
16046            }
16047
16048            if (!ArrayUtils.isEmpty(after.splitNames)) {
16049                for (int i = 0; i < after.splitNames.length; i++) {
16050                    final String splitName = after.splitNames[i];
16051                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
16052                    if (j != -1) {
16053                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
16054                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16055                                    "Update split " + splitName + " revision code "
16056                                    + after.splitRevisionCodes[i] + " is older than current "
16057                                    + before.splitRevisionCodes[j]);
16058                        }
16059                    }
16060                }
16061            }
16062        }
16063    }
16064
16065    private static class MoveCallbacks extends Handler {
16066        private static final int MSG_CREATED = 1;
16067        private static final int MSG_STATUS_CHANGED = 2;
16068
16069        private final RemoteCallbackList<IPackageMoveObserver>
16070                mCallbacks = new RemoteCallbackList<>();
16071
16072        private final SparseIntArray mLastStatus = new SparseIntArray();
16073
16074        public MoveCallbacks(Looper looper) {
16075            super(looper);
16076        }
16077
16078        public void register(IPackageMoveObserver callback) {
16079            mCallbacks.register(callback);
16080        }
16081
16082        public void unregister(IPackageMoveObserver callback) {
16083            mCallbacks.unregister(callback);
16084        }
16085
16086        @Override
16087        public void handleMessage(Message msg) {
16088            final SomeArgs args = (SomeArgs) msg.obj;
16089            final int n = mCallbacks.beginBroadcast();
16090            for (int i = 0; i < n; i++) {
16091                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
16092                try {
16093                    invokeCallback(callback, msg.what, args);
16094                } catch (RemoteException ignored) {
16095                }
16096            }
16097            mCallbacks.finishBroadcast();
16098            args.recycle();
16099        }
16100
16101        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
16102                throws RemoteException {
16103            switch (what) {
16104                case MSG_CREATED: {
16105                    callback.onCreated(args.argi1, (Bundle) args.arg2);
16106                    break;
16107                }
16108                case MSG_STATUS_CHANGED: {
16109                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
16110                    break;
16111                }
16112            }
16113        }
16114
16115        private void notifyCreated(int moveId, Bundle extras) {
16116            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
16117
16118            final SomeArgs args = SomeArgs.obtain();
16119            args.argi1 = moveId;
16120            args.arg2 = extras;
16121            obtainMessage(MSG_CREATED, args).sendToTarget();
16122        }
16123
16124        private void notifyStatusChanged(int moveId, int status) {
16125            notifyStatusChanged(moveId, status, -1);
16126        }
16127
16128        private void notifyStatusChanged(int moveId, int status, long estMillis) {
16129            Slog.v(TAG, "Move " + moveId + " status " + status);
16130
16131            final SomeArgs args = SomeArgs.obtain();
16132            args.argi1 = moveId;
16133            args.argi2 = status;
16134            args.arg3 = estMillis;
16135            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
16136
16137            synchronized (mLastStatus) {
16138                mLastStatus.put(moveId, status);
16139            }
16140        }
16141    }
16142
16143    private final class OnPermissionChangeListeners extends Handler {
16144        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
16145
16146        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
16147                new RemoteCallbackList<>();
16148
16149        public OnPermissionChangeListeners(Looper looper) {
16150            super(looper);
16151        }
16152
16153        @Override
16154        public void handleMessage(Message msg) {
16155            switch (msg.what) {
16156                case MSG_ON_PERMISSIONS_CHANGED: {
16157                    final int uid = msg.arg1;
16158                    handleOnPermissionsChanged(uid);
16159                } break;
16160            }
16161        }
16162
16163        public void addListenerLocked(IOnPermissionsChangeListener listener) {
16164            mPermissionListeners.register(listener);
16165
16166        }
16167
16168        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
16169            mPermissionListeners.unregister(listener);
16170        }
16171
16172        public void onPermissionsChanged(int uid) {
16173            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
16174                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
16175            }
16176        }
16177
16178        private void handleOnPermissionsChanged(int uid) {
16179            final int count = mPermissionListeners.beginBroadcast();
16180            try {
16181                for (int i = 0; i < count; i++) {
16182                    IOnPermissionsChangeListener callback = mPermissionListeners
16183                            .getBroadcastItem(i);
16184                    try {
16185                        callback.onPermissionsChanged(uid);
16186                    } catch (RemoteException e) {
16187                        Log.e(TAG, "Permission listener is dead", e);
16188                    }
16189                }
16190            } finally {
16191                mPermissionListeners.finishBroadcast();
16192            }
16193        }
16194    }
16195
16196    private class PackageManagerInternalImpl extends PackageManagerInternal {
16197        @Override
16198        public void setLocationPackagesProvider(PackagesProvider provider) {
16199            synchronized (mPackages) {
16200                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
16201            }
16202        }
16203
16204        @Override
16205        public void setImePackagesProvider(PackagesProvider provider) {
16206            synchronized (mPackages) {
16207                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
16208            }
16209        }
16210
16211        @Override
16212        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
16213            synchronized (mPackages) {
16214                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
16215            }
16216        }
16217
16218        @Override
16219        public void setSmsAppPackagesProvider(PackagesProvider provider) {
16220            synchronized (mPackages) {
16221                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
16222            }
16223        }
16224
16225        @Override
16226        public void setDialerAppPackagesProvider(PackagesProvider provider) {
16227            synchronized (mPackages) {
16228                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
16229            }
16230        }
16231
16232        @Override
16233        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
16234            synchronized (mPackages) {
16235                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderrLPw(provider);
16236            }
16237        }
16238
16239        @Override
16240        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
16241            synchronized (mPackages) {
16242                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
16243                        packageName, userId);
16244            }
16245        }
16246
16247        @Override
16248        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
16249            synchronized (mPackages) {
16250                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
16251                        packageName, userId);
16252            }
16253        }
16254    }
16255
16256    @Override
16257    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
16258        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
16259        synchronized (mPackages) {
16260            final long identity = Binder.clearCallingIdentity();
16261            try {
16262                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
16263                        packageNames, userId);
16264            } finally {
16265                Binder.restoreCallingIdentity(identity);
16266            }
16267        }
16268    }
16269
16270    private static void enforceSystemOrPhoneCaller(String tag) {
16271        int callingUid = Binder.getCallingUid();
16272        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
16273            throw new SecurityException(
16274                    "Cannot call " + tag + " from UID " + callingUid);
16275        }
16276    }
16277}
16278