PackageManagerService.java revision 9ded760f6378b79ae5f91fe694744981a4154d0b
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.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
26import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
27import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
28import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
29import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT;
30import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
31import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
32import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
33import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
34import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
35import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
36import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
37import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
38import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
39import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
40import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
41import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED;
42import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
44import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
45import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
46import static android.content.pm.PackageManager.INSTALL_INTERNAL;
47import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
48import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
49import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
50import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
51import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
52import static android.content.pm.PackageManager.MATCH_ALL;
53import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
54import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
55import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
56import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
57import static android.content.pm.PackageParser.isApkFile;
58import static android.os.Process.FIRST_APPLICATION_UID;
59import static android.os.Process.PACKAGE_INFO_GID;
60import static android.os.Process.SYSTEM_UID;
61import static android.system.OsConstants.O_CREAT;
62import static android.system.OsConstants.O_RDWR;
63import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
64import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER;
65import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
66import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
67import static com.android.internal.util.ArrayUtils.appendInt;
68import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
69import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
70import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
71import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
72import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
73
74import android.Manifest;
75import android.app.ActivityManager;
76import android.app.ActivityManagerNative;
77import android.app.AppGlobals;
78import android.app.IActivityManager;
79import android.app.admin.IDevicePolicyManager;
80import android.app.backup.IBackupManager;
81import android.app.usage.UsageStats;
82import android.app.usage.UsageStatsManager;
83import android.content.BroadcastReceiver;
84import android.content.ComponentName;
85import android.content.Context;
86import android.content.IIntentReceiver;
87import android.content.Intent;
88import android.content.IntentFilter;
89import android.content.IntentSender;
90import android.content.IntentSender.SendIntentException;
91import android.content.ServiceConnection;
92import android.content.pm.ActivityInfo;
93import android.content.pm.ApplicationInfo;
94import android.content.pm.FeatureInfo;
95import android.content.pm.IPackageDataObserver;
96import android.content.pm.IPackageDeleteObserver;
97import android.content.pm.IPackageDeleteObserver2;
98import android.content.pm.IPackageInstallObserver2;
99import android.content.pm.IPackageInstaller;
100import android.content.pm.IPackageManager;
101import android.content.pm.IPackageMoveObserver;
102import android.content.pm.IPackageStatsObserver;
103import android.content.pm.InstrumentationInfo;
104import android.content.pm.IntentFilterVerificationInfo;
105import android.content.pm.KeySet;
106import android.content.pm.ManifestDigest;
107import android.content.pm.PackageCleanItem;
108import android.content.pm.PackageInfo;
109import android.content.pm.PackageInfoLite;
110import android.content.pm.PackageInstaller;
111import android.content.pm.PackageManager;
112import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
113import android.content.pm.PackageParser;
114import android.content.pm.PackageParser.ActivityIntentInfo;
115import android.content.pm.PackageParser.PackageLite;
116import android.content.pm.PackageParser.PackageParserException;
117import android.content.pm.PackageStats;
118import android.content.pm.PackageUserState;
119import android.content.pm.ParceledListSlice;
120import android.content.pm.PermissionGroupInfo;
121import android.content.pm.PermissionInfo;
122import android.content.pm.ProviderInfo;
123import android.content.pm.ResolveInfo;
124import android.content.pm.ServiceInfo;
125import android.content.pm.Signature;
126import android.content.pm.UserInfo;
127import android.content.pm.VerificationParams;
128import android.content.pm.VerifierDeviceIdentity;
129import android.content.pm.VerifierInfo;
130import android.content.res.Resources;
131import android.hardware.display.DisplayManager;
132import android.net.Uri;
133import android.os.Binder;
134import android.os.Build;
135import android.os.Bundle;
136import android.os.Debug;
137import android.os.Environment;
138import android.os.Environment.UserEnvironment;
139import android.os.FileUtils;
140import android.os.Handler;
141import android.os.IBinder;
142import android.os.Looper;
143import android.os.Message;
144import android.os.Parcel;
145import android.os.ParcelFileDescriptor;
146import android.os.Process;
147import android.os.RemoteCallbackList;
148import android.os.RemoteException;
149import android.os.SELinux;
150import android.os.ServiceManager;
151import android.os.SystemClock;
152import android.os.SystemProperties;
153import android.os.UserHandle;
154import android.os.UserManager;
155import android.os.storage.IMountService;
156import android.os.storage.StorageEventListener;
157import android.os.storage.StorageManager;
158import android.os.storage.VolumeInfo;
159import android.os.storage.VolumeRecord;
160import android.security.KeyStore;
161import android.security.SystemKeyStore;
162import android.system.ErrnoException;
163import android.system.Os;
164import android.system.StructStat;
165import android.text.TextUtils;
166import android.text.format.DateUtils;
167import android.util.ArrayMap;
168import android.util.ArraySet;
169import android.util.AtomicFile;
170import android.util.DisplayMetrics;
171import android.util.EventLog;
172import android.util.ExceptionUtils;
173import android.util.Log;
174import android.util.LogPrinter;
175import android.util.MathUtils;
176import android.util.PrintStreamPrinter;
177import android.util.Slog;
178import android.util.SparseArray;
179import android.util.SparseBooleanArray;
180import android.util.SparseIntArray;
181import android.util.Xml;
182import android.view.Display;
183
184import dalvik.system.DexFile;
185import dalvik.system.VMRuntime;
186
187import libcore.io.IoUtils;
188import libcore.util.EmptyArray;
189
190import com.android.internal.R;
191import com.android.internal.app.IMediaContainerService;
192import com.android.internal.app.ResolverActivity;
193import com.android.internal.content.NativeLibraryHelper;
194import com.android.internal.content.PackageHelper;
195import com.android.internal.os.IParcelFileDescriptorFactory;
196import com.android.internal.os.SomeArgs;
197import com.android.internal.util.ArrayUtils;
198import com.android.internal.util.FastPrintWriter;
199import com.android.internal.util.FastXmlSerializer;
200import com.android.internal.util.IndentingPrintWriter;
201import com.android.internal.util.Preconditions;
202import com.android.server.EventLogTags;
203import com.android.server.FgThread;
204import com.android.server.IntentResolver;
205import com.android.server.LocalServices;
206import com.android.server.ServiceThread;
207import com.android.server.SystemConfig;
208import com.android.server.Watchdog;
209import com.android.server.pm.Settings.DatabaseVersion;
210import com.android.server.pm.PermissionsState.PermissionState;
211import com.android.server.storage.DeviceStorageMonitorInternal;
212
213import org.xmlpull.v1.XmlPullParser;
214import org.xmlpull.v1.XmlSerializer;
215
216import java.io.BufferedInputStream;
217import java.io.BufferedOutputStream;
218import java.io.BufferedReader;
219import java.io.ByteArrayInputStream;
220import java.io.ByteArrayOutputStream;
221import java.io.File;
222import java.io.FileDescriptor;
223import java.io.FileNotFoundException;
224import java.io.FileOutputStream;
225import java.io.FileReader;
226import java.io.FilenameFilter;
227import java.io.IOException;
228import java.io.InputStream;
229import java.io.PrintWriter;
230import java.nio.charset.StandardCharsets;
231import java.security.NoSuchAlgorithmException;
232import java.security.PublicKey;
233import java.security.cert.CertificateEncodingException;
234import java.security.cert.CertificateException;
235import java.text.SimpleDateFormat;
236import java.util.ArrayList;
237import java.util.Arrays;
238import java.util.Collection;
239import java.util.Collections;
240import java.util.Comparator;
241import java.util.Date;
242import java.util.Iterator;
243import java.util.List;
244import java.util.Map;
245import java.util.Objects;
246import java.util.Set;
247import java.util.concurrent.CountDownLatch;
248import java.util.concurrent.TimeUnit;
249import java.util.concurrent.atomic.AtomicBoolean;
250import java.util.concurrent.atomic.AtomicInteger;
251import java.util.concurrent.atomic.AtomicLong;
252
253/**
254 * Keep track of all those .apks everywhere.
255 *
256 * This is very central to the platform's security; please run the unit
257 * tests whenever making modifications here:
258 *
259mmm frameworks/base/tests/AndroidTests
260adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
261adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
262 *
263 * {@hide}
264 */
265public class PackageManagerService extends IPackageManager.Stub {
266    static final String TAG = "PackageManager";
267    static final boolean DEBUG_SETTINGS = false;
268    static final boolean DEBUG_PREFERRED = false;
269    static final boolean DEBUG_UPGRADE = false;
270    private static final boolean DEBUG_BACKUP = true;
271    private static final boolean DEBUG_INSTALL = false;
272    private static final boolean DEBUG_REMOVE = false;
273    private static final boolean DEBUG_BROADCASTS = false;
274    private static final boolean DEBUG_SHOW_INFO = false;
275    private static final boolean DEBUG_PACKAGE_INFO = false;
276    private static final boolean DEBUG_INTENT_MATCHING = false;
277    private static final boolean DEBUG_PACKAGE_SCANNING = false;
278    private static final boolean DEBUG_VERIFY = false;
279    private static final boolean DEBUG_DEXOPT = false;
280    private static final boolean DEBUG_ABI_SELECTION = false;
281
282    private static final int RADIO_UID = Process.PHONE_UID;
283    private static final int LOG_UID = Process.LOG_UID;
284    private static final int NFC_UID = Process.NFC_UID;
285    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
286    private static final int SHELL_UID = Process.SHELL_UID;
287
288    // Cap the size of permission trees that 3rd party apps can define
289    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
290
291    // Suffix used during package installation when copying/moving
292    // package apks to install directory.
293    private static final String INSTALL_PACKAGE_SUFFIX = "-";
294
295    static final int SCAN_NO_DEX = 1<<1;
296    static final int SCAN_FORCE_DEX = 1<<2;
297    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
298    static final int SCAN_NEW_INSTALL = 1<<4;
299    static final int SCAN_NO_PATHS = 1<<5;
300    static final int SCAN_UPDATE_TIME = 1<<6;
301    static final int SCAN_DEFER_DEX = 1<<7;
302    static final int SCAN_BOOTING = 1<<8;
303    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
304    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
305    static final int SCAN_REQUIRE_KNOWN = 1<<12;
306
307    static final int REMOVE_CHATTY = 1<<16;
308
309    private static final int[] EMPTY_INT_ARRAY = new int[0];
310
311    /**
312     * Timeout (in milliseconds) after which the watchdog should declare that
313     * our handler thread is wedged.  The usual default for such things is one
314     * minute but we sometimes do very lengthy I/O operations on this thread,
315     * such as installing multi-gigabyte applications, so ours needs to be longer.
316     */
317    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
318
319    /**
320     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
321     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
322     * settings entry if available, otherwise we use the hardcoded default.  If it's been
323     * more than this long since the last fstrim, we force one during the boot sequence.
324     *
325     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
326     * one gets run at the next available charging+idle time.  This final mandatory
327     * no-fstrim check kicks in only of the other scheduling criteria is never met.
328     */
329    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
330
331    /**
332     * Whether verification is enabled by default.
333     */
334    private static final boolean DEFAULT_VERIFY_ENABLE = true;
335
336    /**
337     * The default maximum time to wait for the verification agent to return in
338     * milliseconds.
339     */
340    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
341
342    /**
343     * The default response for package verification timeout.
344     *
345     * This can be either PackageManager.VERIFICATION_ALLOW or
346     * PackageManager.VERIFICATION_REJECT.
347     */
348    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
349
350    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
351
352    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
353            DEFAULT_CONTAINER_PACKAGE,
354            "com.android.defcontainer.DefaultContainerService");
355
356    private static final String KILL_APP_REASON_GIDS_CHANGED =
357            "permission grant or revoke changed gids";
358
359    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
360            "permissions revoked";
361
362    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
363
364    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
365
366    /** Permission grant: not grant the permission. */
367    private static final int GRANT_DENIED = 1;
368
369    /** Permission grant: grant the permission as an install permission. */
370    private static final int GRANT_INSTALL = 2;
371
372    /** Permission grant: grant the permission as a runtime one. */
373    private static final int GRANT_RUNTIME = 3;
374
375    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
376    private static final int GRANT_UPGRADE = 4;
377
378    final ServiceThread mHandlerThread;
379
380    final PackageHandler mHandler;
381
382    /**
383     * Messages for {@link #mHandler} that need to wait for system ready before
384     * being dispatched.
385     */
386    private ArrayList<Message> mPostSystemReadyMessages;
387
388    final int mSdkVersion = Build.VERSION.SDK_INT;
389
390    final Context mContext;
391    final boolean mFactoryTest;
392    final boolean mOnlyCore;
393    final boolean mLazyDexOpt;
394    final long mDexOptLRUThresholdInMills;
395    final DisplayMetrics mMetrics;
396    final int mDefParseFlags;
397    final String[] mSeparateProcesses;
398    final boolean mIsUpgrade;
399
400    // This is where all application persistent data goes.
401    final File mAppDataDir;
402
403    // This is where all application persistent data goes for secondary users.
404    final File mUserAppDataDir;
405
406    /** The location for ASEC container files on internal storage. */
407    final String mAsecInternalPath;
408
409    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
410    // LOCK HELD.  Can be called with mInstallLock held.
411    final Installer mInstaller;
412
413    /** Directory where installed third-party apps stored */
414    final File mAppInstallDir;
415
416    /**
417     * Directory to which applications installed internally have their
418     * 32 bit native libraries copied.
419     */
420    private File mAppLib32InstallDir;
421
422    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
423    // apps.
424    final File mDrmAppPrivateInstallDir;
425
426    // ----------------------------------------------------------------
427
428    // Lock for state used when installing and doing other long running
429    // operations.  Methods that must be called with this lock held have
430    // the suffix "LI".
431    final Object mInstallLock = new Object();
432
433    // ----------------------------------------------------------------
434
435    // Keys are String (package name), values are Package.  This also serves
436    // as the lock for the global state.  Methods that must be called with
437    // this lock held have the prefix "LP".
438    final ArrayMap<String, PackageParser.Package> mPackages =
439            new ArrayMap<String, PackageParser.Package>();
440
441    // Tracks available target package names -> overlay package paths.
442    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
443        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
444
445    final Settings mSettings;
446    boolean mRestoredSettings;
447
448    // System configuration read by SystemConfig.
449    final int[] mGlobalGids;
450    final SparseArray<ArraySet<String>> mSystemPermissions;
451    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
452
453    // If mac_permissions.xml was found for seinfo labeling.
454    boolean mFoundPolicyFile;
455
456    // If a recursive restorecon of /data/data/<pkg> is needed.
457    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
458
459    public static final class SharedLibraryEntry {
460        public final String path;
461        public final String apk;
462
463        SharedLibraryEntry(String _path, String _apk) {
464            path = _path;
465            apk = _apk;
466        }
467    }
468
469    // Currently known shared libraries.
470    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
471            new ArrayMap<String, SharedLibraryEntry>();
472
473    // All available activities, for your resolving pleasure.
474    final ActivityIntentResolver mActivities =
475            new ActivityIntentResolver();
476
477    // All available receivers, for your resolving pleasure.
478    final ActivityIntentResolver mReceivers =
479            new ActivityIntentResolver();
480
481    // All available services, for your resolving pleasure.
482    final ServiceIntentResolver mServices = new ServiceIntentResolver();
483
484    // All available providers, for your resolving pleasure.
485    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
486
487    // Mapping from provider base names (first directory in content URI codePath)
488    // to the provider information.
489    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
490            new ArrayMap<String, PackageParser.Provider>();
491
492    // Mapping from instrumentation class names to info about them.
493    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
494            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
495
496    // Mapping from permission names to info about them.
497    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
498            new ArrayMap<String, PackageParser.PermissionGroup>();
499
500    // Packages whose data we have transfered into another package, thus
501    // should no longer exist.
502    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
503
504    // Broadcast actions that are only available to the system.
505    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
506
507    /** List of packages waiting for verification. */
508    final SparseArray<PackageVerificationState> mPendingVerification
509            = new SparseArray<PackageVerificationState>();
510
511    /** Set of packages associated with each app op permission. */
512    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
513
514    final PackageInstallerService mInstallerService;
515
516    private final PackageDexOptimizer mPackageDexOptimizer;
517
518    private AtomicInteger mNextMoveId = new AtomicInteger();
519    private final MoveCallbacks mMoveCallbacks;
520
521    // Cache of users who need badging.
522    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
523
524    /** Token for keys in mPendingVerification. */
525    private int mPendingVerificationToken = 0;
526
527    volatile boolean mSystemReady;
528    volatile boolean mSafeMode;
529    volatile boolean mHasSystemUidErrors;
530
531    ApplicationInfo mAndroidApplication;
532    final ActivityInfo mResolveActivity = new ActivityInfo();
533    final ResolveInfo mResolveInfo = new ResolveInfo();
534    ComponentName mResolveComponentName;
535    PackageParser.Package mPlatformPackage;
536    ComponentName mCustomResolverComponentName;
537
538    boolean mResolverReplaced = false;
539
540    private final ComponentName mIntentFilterVerifierComponent;
541    private int mIntentFilterVerificationToken = 0;
542
543    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
544            = new SparseArray<IntentFilterVerificationState>();
545
546    private interface IntentFilterVerifier<T extends IntentFilter> {
547        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
548                                               T filter, String packageName);
549        void startVerifications(int userId);
550        void receiveVerificationResponse(int verificationId);
551    }
552
553    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
554        private Context mContext;
555        private ComponentName mIntentFilterVerifierComponent;
556        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
557
558        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
559            mContext = context;
560            mIntentFilterVerifierComponent = verifierComponent;
561        }
562
563        private String getDefaultScheme() {
564            // TODO: replace SCHEME_HTTP with SCHEME_HTTPS
565            return IntentFilter.SCHEME_HTTP;
566        }
567
568        @Override
569        public void startVerifications(int userId) {
570            // Launch verifications requests
571            int count = mCurrentIntentFilterVerifications.size();
572            for (int n=0; n<count; n++) {
573                int verificationId = mCurrentIntentFilterVerifications.get(n);
574                final IntentFilterVerificationState ivs =
575                        mIntentFilterVerificationStates.get(verificationId);
576
577                String packageName = ivs.getPackageName();
578
579                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
580                final int filterCount = filters.size();
581                ArraySet<String> domainsSet = new ArraySet<>();
582                for (int m=0; m<filterCount; m++) {
583                    PackageParser.ActivityIntentInfo filter = filters.get(m);
584                    domainsSet.addAll(filter.getHostsList());
585                }
586                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
587                synchronized (mPackages) {
588                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
589                            packageName, domainsList) != null) {
590                        scheduleWriteSettingsLocked();
591                    }
592                }
593                sendVerificationRequest(userId, verificationId, ivs);
594            }
595            mCurrentIntentFilterVerifications.clear();
596        }
597
598        private void sendVerificationRequest(int userId, int verificationId,
599                IntentFilterVerificationState ivs) {
600
601            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
602            verificationIntent.putExtra(
603                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
604                    verificationId);
605            verificationIntent.putExtra(
606                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
607                    getDefaultScheme());
608            verificationIntent.putExtra(
609                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
610                    ivs.getHostsString());
611            verificationIntent.putExtra(
612                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
613                    ivs.getPackageName());
614            verificationIntent.setComponent(mIntentFilterVerifierComponent);
615            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
616
617            UserHandle user = new UserHandle(userId);
618            mContext.sendBroadcastAsUser(verificationIntent, user);
619            Slog.d(TAG, "Sending IntenFilter verification broadcast");
620        }
621
622        public void receiveVerificationResponse(int verificationId) {
623            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
624
625            final boolean verified = ivs.isVerified();
626
627            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
628            final int count = filters.size();
629            for (int n=0; n<count; n++) {
630                PackageParser.ActivityIntentInfo filter = filters.get(n);
631                filter.setVerified(verified);
632
633                Slog.d(TAG, "IntentFilter " + filter.toString() + " verified with result:"
634                        + verified + " and hosts:" + ivs.getHostsString());
635            }
636
637            mIntentFilterVerificationStates.remove(verificationId);
638
639            final String packageName = ivs.getPackageName();
640            IntentFilterVerificationInfo ivi = null;
641
642            synchronized (mPackages) {
643                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
644            }
645            if (ivi == null) {
646                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
647                        + verificationId + " packageName:" + packageName);
648                return;
649            }
650            Slog.d(TAG, "Updating IntentFilterVerificationInfo for verificationId:"
651                    + verificationId);
652
653            synchronized (mPackages) {
654                if (verified) {
655                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
656                } else {
657                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
658                }
659                scheduleWriteSettingsLocked();
660
661                final int userId = ivs.getUserId();
662                if (userId != UserHandle.USER_ALL) {
663                    final int userStatus =
664                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
665
666                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
667                    boolean needUpdate = false;
668
669                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
670                    // already been set by the User thru the Disambiguation dialog
671                    switch (userStatus) {
672                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
673                            if (verified) {
674                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
675                            } else {
676                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
677                            }
678                            needUpdate = true;
679                            break;
680
681                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
682                            if (verified) {
683                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
684                                needUpdate = true;
685                            }
686                            break;
687
688                        default:
689                            // Nothing to do
690                    }
691
692                    if (needUpdate) {
693                        mSettings.updateIntentFilterVerificationStatusLPw(
694                                packageName, updatedStatus, userId);
695                        scheduleWritePackageRestrictionsLocked(userId);
696                    }
697                }
698            }
699        }
700
701        @Override
702        public boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
703                    ActivityIntentInfo filter, String packageName) {
704            if (!(filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
705                    filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
706                Slog.d(TAG, "IntentFilter does not contain HTTP nor HTTPS data scheme");
707                return false;
708            }
709            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
710            if (ivs == null) {
711                ivs = createDomainVerificationState(verifierId, userId, verificationId,
712                        packageName);
713            }
714            if (!hasValidDomains(filter)) {
715                return false;
716            }
717            ivs.addFilter(filter);
718            return true;
719        }
720
721        private IntentFilterVerificationState createDomainVerificationState(int verifierId,
722                int userId, int verificationId, String packageName) {
723            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
724                    verifierId, userId, packageName);
725            ivs.setPendingState();
726            synchronized (mPackages) {
727                mIntentFilterVerificationStates.append(verificationId, ivs);
728                mCurrentIntentFilterVerifications.add(verificationId);
729            }
730            return ivs;
731        }
732    }
733
734    private static boolean hasValidDomains(ActivityIntentInfo filter) {
735        return hasValidDomains(filter, true);
736    }
737
738    private static boolean hasValidDomains(ActivityIntentInfo filter, boolean logging) {
739        boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
740                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS);
741        if (!hasHTTPorHTTPS) {
742            if (logging) {
743                Slog.d(TAG, "IntentFilter does not contain any HTTP or HTTPS data scheme");
744            }
745            return false;
746        }
747        return true;
748    }
749
750    private IntentFilterVerifier mIntentFilterVerifier;
751
752    // Set of pending broadcasts for aggregating enable/disable of components.
753    static class PendingPackageBroadcasts {
754        // for each user id, a map of <package name -> components within that package>
755        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
756
757        public PendingPackageBroadcasts() {
758            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
759        }
760
761        public ArrayList<String> get(int userId, String packageName) {
762            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
763            return packages.get(packageName);
764        }
765
766        public void put(int userId, String packageName, ArrayList<String> components) {
767            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
768            packages.put(packageName, components);
769        }
770
771        public void remove(int userId, String packageName) {
772            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
773            if (packages != null) {
774                packages.remove(packageName);
775            }
776        }
777
778        public void remove(int userId) {
779            mUidMap.remove(userId);
780        }
781
782        public int userIdCount() {
783            return mUidMap.size();
784        }
785
786        public int userIdAt(int n) {
787            return mUidMap.keyAt(n);
788        }
789
790        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
791            return mUidMap.get(userId);
792        }
793
794        public int size() {
795            // total number of pending broadcast entries across all userIds
796            int num = 0;
797            for (int i = 0; i< mUidMap.size(); i++) {
798                num += mUidMap.valueAt(i).size();
799            }
800            return num;
801        }
802
803        public void clear() {
804            mUidMap.clear();
805        }
806
807        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
808            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
809            if (map == null) {
810                map = new ArrayMap<String, ArrayList<String>>();
811                mUidMap.put(userId, map);
812            }
813            return map;
814        }
815    }
816    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
817
818    // Service Connection to remote media container service to copy
819    // package uri's from external media onto secure containers
820    // or internal storage.
821    private IMediaContainerService mContainerService = null;
822
823    static final int SEND_PENDING_BROADCAST = 1;
824    static final int MCS_BOUND = 3;
825    static final int END_COPY = 4;
826    static final int INIT_COPY = 5;
827    static final int MCS_UNBIND = 6;
828    static final int START_CLEANING_PACKAGE = 7;
829    static final int FIND_INSTALL_LOC = 8;
830    static final int POST_INSTALL = 9;
831    static final int MCS_RECONNECT = 10;
832    static final int MCS_GIVE_UP = 11;
833    static final int UPDATED_MEDIA_STATUS = 12;
834    static final int WRITE_SETTINGS = 13;
835    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
836    static final int PACKAGE_VERIFIED = 15;
837    static final int CHECK_PENDING_VERIFICATION = 16;
838    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
839    static final int INTENT_FILTER_VERIFIED = 18;
840
841    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
842
843    // Delay time in millisecs
844    static final int BROADCAST_DELAY = 10 * 1000;
845
846    static UserManagerService sUserManager;
847
848    // Stores a list of users whose package restrictions file needs to be updated
849    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
850
851    final private DefaultContainerConnection mDefContainerConn =
852            new DefaultContainerConnection();
853    class DefaultContainerConnection implements ServiceConnection {
854        public void onServiceConnected(ComponentName name, IBinder service) {
855            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
856            IMediaContainerService imcs =
857                IMediaContainerService.Stub.asInterface(service);
858            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
859        }
860
861        public void onServiceDisconnected(ComponentName name) {
862            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
863        }
864    };
865
866    // Recordkeeping of restore-after-install operations that are currently in flight
867    // between the Package Manager and the Backup Manager
868    class PostInstallData {
869        public InstallArgs args;
870        public PackageInstalledInfo res;
871
872        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
873            args = _a;
874            res = _r;
875        }
876    };
877    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
878    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
879
880    // backup/restore of preferred activity state
881    private static final String TAG_PREFERRED_BACKUP = "pa";
882
883    private final String mRequiredVerifierPackage;
884
885    private final PackageUsage mPackageUsage = new PackageUsage();
886
887    private class PackageUsage {
888        private static final int WRITE_INTERVAL
889            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
890
891        private final Object mFileLock = new Object();
892        private final AtomicLong mLastWritten = new AtomicLong(0);
893        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
894
895        private boolean mIsHistoricalPackageUsageAvailable = true;
896
897        boolean isHistoricalPackageUsageAvailable() {
898            return mIsHistoricalPackageUsageAvailable;
899        }
900
901        void write(boolean force) {
902            if (force) {
903                writeInternal();
904                return;
905            }
906            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
907                && !DEBUG_DEXOPT) {
908                return;
909            }
910            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
911                new Thread("PackageUsage_DiskWriter") {
912                    @Override
913                    public void run() {
914                        try {
915                            writeInternal();
916                        } finally {
917                            mBackgroundWriteRunning.set(false);
918                        }
919                    }
920                }.start();
921            }
922        }
923
924        private void writeInternal() {
925            synchronized (mPackages) {
926                synchronized (mFileLock) {
927                    AtomicFile file = getFile();
928                    FileOutputStream f = null;
929                    try {
930                        f = file.startWrite();
931                        BufferedOutputStream out = new BufferedOutputStream(f);
932                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
933                        StringBuilder sb = new StringBuilder();
934                        for (PackageParser.Package pkg : mPackages.values()) {
935                            if (pkg.mLastPackageUsageTimeInMills == 0) {
936                                continue;
937                            }
938                            sb.setLength(0);
939                            sb.append(pkg.packageName);
940                            sb.append(' ');
941                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
942                            sb.append('\n');
943                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
944                        }
945                        out.flush();
946                        file.finishWrite(f);
947                    } catch (IOException e) {
948                        if (f != null) {
949                            file.failWrite(f);
950                        }
951                        Log.e(TAG, "Failed to write package usage times", e);
952                    }
953                }
954            }
955            mLastWritten.set(SystemClock.elapsedRealtime());
956        }
957
958        void readLP() {
959            synchronized (mFileLock) {
960                AtomicFile file = getFile();
961                BufferedInputStream in = null;
962                try {
963                    in = new BufferedInputStream(file.openRead());
964                    StringBuffer sb = new StringBuffer();
965                    while (true) {
966                        String packageName = readToken(in, sb, ' ');
967                        if (packageName == null) {
968                            break;
969                        }
970                        String timeInMillisString = readToken(in, sb, '\n');
971                        if (timeInMillisString == null) {
972                            throw new IOException("Failed to find last usage time for package "
973                                                  + packageName);
974                        }
975                        PackageParser.Package pkg = mPackages.get(packageName);
976                        if (pkg == null) {
977                            continue;
978                        }
979                        long timeInMillis;
980                        try {
981                            timeInMillis = Long.parseLong(timeInMillisString.toString());
982                        } catch (NumberFormatException e) {
983                            throw new IOException("Failed to parse " + timeInMillisString
984                                                  + " as a long.", e);
985                        }
986                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
987                    }
988                } catch (FileNotFoundException expected) {
989                    mIsHistoricalPackageUsageAvailable = false;
990                } catch (IOException e) {
991                    Log.w(TAG, "Failed to read package usage times", e);
992                } finally {
993                    IoUtils.closeQuietly(in);
994                }
995            }
996            mLastWritten.set(SystemClock.elapsedRealtime());
997        }
998
999        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1000                throws IOException {
1001            sb.setLength(0);
1002            while (true) {
1003                int ch = in.read();
1004                if (ch == -1) {
1005                    if (sb.length() == 0) {
1006                        return null;
1007                    }
1008                    throw new IOException("Unexpected EOF");
1009                }
1010                if (ch == endOfToken) {
1011                    return sb.toString();
1012                }
1013                sb.append((char)ch);
1014            }
1015        }
1016
1017        private AtomicFile getFile() {
1018            File dataDir = Environment.getDataDirectory();
1019            File systemDir = new File(dataDir, "system");
1020            File fname = new File(systemDir, "package-usage.list");
1021            return new AtomicFile(fname);
1022        }
1023    }
1024
1025    class PackageHandler extends Handler {
1026        private boolean mBound = false;
1027        final ArrayList<HandlerParams> mPendingInstalls =
1028            new ArrayList<HandlerParams>();
1029
1030        private boolean connectToService() {
1031            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1032                    " DefaultContainerService");
1033            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1034            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1035            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1036                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
1037                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1038                mBound = true;
1039                return true;
1040            }
1041            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1042            return false;
1043        }
1044
1045        private void disconnectService() {
1046            mContainerService = null;
1047            mBound = false;
1048            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1049            mContext.unbindService(mDefContainerConn);
1050            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1051        }
1052
1053        PackageHandler(Looper looper) {
1054            super(looper);
1055        }
1056
1057        public void handleMessage(Message msg) {
1058            try {
1059                doHandleMessage(msg);
1060            } finally {
1061                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1062            }
1063        }
1064
1065        void doHandleMessage(Message msg) {
1066            switch (msg.what) {
1067                case INIT_COPY: {
1068                    HandlerParams params = (HandlerParams) msg.obj;
1069                    int idx = mPendingInstalls.size();
1070                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1071                    // If a bind was already initiated we dont really
1072                    // need to do anything. The pending install
1073                    // will be processed later on.
1074                    if (!mBound) {
1075                        // If this is the only one pending we might
1076                        // have to bind to the service again.
1077                        if (!connectToService()) {
1078                            Slog.e(TAG, "Failed to bind to media container service");
1079                            params.serviceError();
1080                            return;
1081                        } else {
1082                            // Once we bind to the service, the first
1083                            // pending request will be processed.
1084                            mPendingInstalls.add(idx, params);
1085                        }
1086                    } else {
1087                        mPendingInstalls.add(idx, params);
1088                        // Already bound to the service. Just make
1089                        // sure we trigger off processing the first request.
1090                        if (idx == 0) {
1091                            mHandler.sendEmptyMessage(MCS_BOUND);
1092                        }
1093                    }
1094                    break;
1095                }
1096                case MCS_BOUND: {
1097                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1098                    if (msg.obj != null) {
1099                        mContainerService = (IMediaContainerService) msg.obj;
1100                    }
1101                    if (mContainerService == null) {
1102                        // Something seriously wrong. Bail out
1103                        Slog.e(TAG, "Cannot bind to media container service");
1104                        for (HandlerParams params : mPendingInstalls) {
1105                            // Indicate service bind error
1106                            params.serviceError();
1107                        }
1108                        mPendingInstalls.clear();
1109                    } else if (mPendingInstalls.size() > 0) {
1110                        HandlerParams params = mPendingInstalls.get(0);
1111                        if (params != null) {
1112                            if (params.startCopy()) {
1113                                // We are done...  look for more work or to
1114                                // go idle.
1115                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1116                                        "Checking for more work or unbind...");
1117                                // Delete pending install
1118                                if (mPendingInstalls.size() > 0) {
1119                                    mPendingInstalls.remove(0);
1120                                }
1121                                if (mPendingInstalls.size() == 0) {
1122                                    if (mBound) {
1123                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1124                                                "Posting delayed MCS_UNBIND");
1125                                        removeMessages(MCS_UNBIND);
1126                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1127                                        // Unbind after a little delay, to avoid
1128                                        // continual thrashing.
1129                                        sendMessageDelayed(ubmsg, 10000);
1130                                    }
1131                                } else {
1132                                    // There are more pending requests in queue.
1133                                    // Just post MCS_BOUND message to trigger processing
1134                                    // of next pending install.
1135                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1136                                            "Posting MCS_BOUND for next work");
1137                                    mHandler.sendEmptyMessage(MCS_BOUND);
1138                                }
1139                            }
1140                        }
1141                    } else {
1142                        // Should never happen ideally.
1143                        Slog.w(TAG, "Empty queue");
1144                    }
1145                    break;
1146                }
1147                case MCS_RECONNECT: {
1148                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1149                    if (mPendingInstalls.size() > 0) {
1150                        if (mBound) {
1151                            disconnectService();
1152                        }
1153                        if (!connectToService()) {
1154                            Slog.e(TAG, "Failed to bind to media container service");
1155                            for (HandlerParams params : mPendingInstalls) {
1156                                // Indicate service bind error
1157                                params.serviceError();
1158                            }
1159                            mPendingInstalls.clear();
1160                        }
1161                    }
1162                    break;
1163                }
1164                case MCS_UNBIND: {
1165                    // If there is no actual work left, then time to unbind.
1166                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1167
1168                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1169                        if (mBound) {
1170                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1171
1172                            disconnectService();
1173                        }
1174                    } else if (mPendingInstalls.size() > 0) {
1175                        // There are more pending requests in queue.
1176                        // Just post MCS_BOUND message to trigger processing
1177                        // of next pending install.
1178                        mHandler.sendEmptyMessage(MCS_BOUND);
1179                    }
1180
1181                    break;
1182                }
1183                case MCS_GIVE_UP: {
1184                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1185                    mPendingInstalls.remove(0);
1186                    break;
1187                }
1188                case SEND_PENDING_BROADCAST: {
1189                    String packages[];
1190                    ArrayList<String> components[];
1191                    int size = 0;
1192                    int uids[];
1193                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1194                    synchronized (mPackages) {
1195                        if (mPendingBroadcasts == null) {
1196                            return;
1197                        }
1198                        size = mPendingBroadcasts.size();
1199                        if (size <= 0) {
1200                            // Nothing to be done. Just return
1201                            return;
1202                        }
1203                        packages = new String[size];
1204                        components = new ArrayList[size];
1205                        uids = new int[size];
1206                        int i = 0;  // filling out the above arrays
1207
1208                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1209                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1210                            Iterator<Map.Entry<String, ArrayList<String>>> it
1211                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1212                                            .entrySet().iterator();
1213                            while (it.hasNext() && i < size) {
1214                                Map.Entry<String, ArrayList<String>> ent = it.next();
1215                                packages[i] = ent.getKey();
1216                                components[i] = ent.getValue();
1217                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1218                                uids[i] = (ps != null)
1219                                        ? UserHandle.getUid(packageUserId, ps.appId)
1220                                        : -1;
1221                                i++;
1222                            }
1223                        }
1224                        size = i;
1225                        mPendingBroadcasts.clear();
1226                    }
1227                    // Send broadcasts
1228                    for (int i = 0; i < size; i++) {
1229                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1230                    }
1231                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1232                    break;
1233                }
1234                case START_CLEANING_PACKAGE: {
1235                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1236                    final String packageName = (String)msg.obj;
1237                    final int userId = msg.arg1;
1238                    final boolean andCode = msg.arg2 != 0;
1239                    synchronized (mPackages) {
1240                        if (userId == UserHandle.USER_ALL) {
1241                            int[] users = sUserManager.getUserIds();
1242                            for (int user : users) {
1243                                mSettings.addPackageToCleanLPw(
1244                                        new PackageCleanItem(user, packageName, andCode));
1245                            }
1246                        } else {
1247                            mSettings.addPackageToCleanLPw(
1248                                    new PackageCleanItem(userId, packageName, andCode));
1249                        }
1250                    }
1251                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1252                    startCleaningPackages();
1253                } break;
1254                case POST_INSTALL: {
1255                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1256                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1257                    mRunningInstalls.delete(msg.arg1);
1258                    boolean deleteOld = false;
1259
1260                    if (data != null) {
1261                        InstallArgs args = data.args;
1262                        PackageInstalledInfo res = data.res;
1263
1264                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1265                            res.removedInfo.sendBroadcast(false, true, false);
1266                            Bundle extras = new Bundle(1);
1267                            extras.putInt(Intent.EXTRA_UID, res.uid);
1268
1269                            // Now that we successfully installed the package, grant runtime
1270                            // permissions if requested before broadcasting the install.
1271                            if ((args.installFlags
1272                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) {
1273                                grantRequestedRuntimePermissions(res.pkg,
1274                                        args.user.getIdentifier());
1275                            }
1276
1277                            // Determine the set of users who are adding this
1278                            // package for the first time vs. those who are seeing
1279                            // an update.
1280                            int[] firstUsers;
1281                            int[] updateUsers = new int[0];
1282                            if (res.origUsers == null || res.origUsers.length == 0) {
1283                                firstUsers = res.newUsers;
1284                            } else {
1285                                firstUsers = new int[0];
1286                                for (int i=0; i<res.newUsers.length; i++) {
1287                                    int user = res.newUsers[i];
1288                                    boolean isNew = true;
1289                                    for (int j=0; j<res.origUsers.length; j++) {
1290                                        if (res.origUsers[j] == user) {
1291                                            isNew = false;
1292                                            break;
1293                                        }
1294                                    }
1295                                    if (isNew) {
1296                                        int[] newFirst = new int[firstUsers.length+1];
1297                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1298                                                firstUsers.length);
1299                                        newFirst[firstUsers.length] = user;
1300                                        firstUsers = newFirst;
1301                                    } else {
1302                                        int[] newUpdate = new int[updateUsers.length+1];
1303                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1304                                                updateUsers.length);
1305                                        newUpdate[updateUsers.length] = user;
1306                                        updateUsers = newUpdate;
1307                                    }
1308                                }
1309                            }
1310                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1311                                    res.pkg.applicationInfo.packageName,
1312                                    extras, null, null, firstUsers);
1313                            final boolean update = res.removedInfo.removedPackage != null;
1314                            if (update) {
1315                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1316                            }
1317                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1318                                    res.pkg.applicationInfo.packageName,
1319                                    extras, null, null, updateUsers);
1320                            if (update) {
1321                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1322                                        res.pkg.applicationInfo.packageName,
1323                                        extras, null, null, updateUsers);
1324                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1325                                        null, null,
1326                                        res.pkg.applicationInfo.packageName, null, updateUsers);
1327
1328                                // treat asec-hosted packages like removable media on upgrade
1329                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1330                                    if (DEBUG_INSTALL) {
1331                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1332                                                + " is ASEC-hosted -> AVAILABLE");
1333                                    }
1334                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1335                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1336                                    pkgList.add(res.pkg.applicationInfo.packageName);
1337                                    sendResourcesChangedBroadcast(true, true,
1338                                            pkgList,uidArray, null);
1339                                }
1340                            }
1341                            if (res.removedInfo.args != null) {
1342                                // Remove the replaced package's older resources safely now
1343                                deleteOld = true;
1344                            }
1345
1346                            // Log current value of "unknown sources" setting
1347                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1348                                getUnknownSourcesSettings());
1349                        }
1350                        // Force a gc to clear up things
1351                        Runtime.getRuntime().gc();
1352                        // We delete after a gc for applications  on sdcard.
1353                        if (deleteOld) {
1354                            synchronized (mInstallLock) {
1355                                res.removedInfo.args.doPostDeleteLI(true);
1356                            }
1357                        }
1358                        if (args.observer != null) {
1359                            try {
1360                                Bundle extras = extrasForInstallResult(res);
1361                                args.observer.onPackageInstalled(res.name, res.returnCode,
1362                                        res.returnMsg, extras);
1363                            } catch (RemoteException e) {
1364                                Slog.i(TAG, "Observer no longer exists.");
1365                            }
1366                        }
1367                    } else {
1368                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1369                    }
1370                } break;
1371                case UPDATED_MEDIA_STATUS: {
1372                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1373                    boolean reportStatus = msg.arg1 == 1;
1374                    boolean doGc = msg.arg2 == 1;
1375                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1376                    if (doGc) {
1377                        // Force a gc to clear up stale containers.
1378                        Runtime.getRuntime().gc();
1379                    }
1380                    if (msg.obj != null) {
1381                        @SuppressWarnings("unchecked")
1382                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1383                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1384                        // Unload containers
1385                        unloadAllContainers(args);
1386                    }
1387                    if (reportStatus) {
1388                        try {
1389                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1390                            PackageHelper.getMountService().finishMediaUpdate();
1391                        } catch (RemoteException e) {
1392                            Log.e(TAG, "MountService not running?");
1393                        }
1394                    }
1395                } break;
1396                case WRITE_SETTINGS: {
1397                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1398                    synchronized (mPackages) {
1399                        removeMessages(WRITE_SETTINGS);
1400                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1401                        mSettings.writeLPr();
1402                        mDirtyUsers.clear();
1403                    }
1404                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1405                } break;
1406                case WRITE_PACKAGE_RESTRICTIONS: {
1407                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1408                    synchronized (mPackages) {
1409                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1410                        for (int userId : mDirtyUsers) {
1411                            mSettings.writePackageRestrictionsLPr(userId);
1412                        }
1413                        mDirtyUsers.clear();
1414                    }
1415                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1416                } break;
1417                case CHECK_PENDING_VERIFICATION: {
1418                    final int verificationId = msg.arg1;
1419                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1420
1421                    if ((state != null) && !state.timeoutExtended()) {
1422                        final InstallArgs args = state.getInstallArgs();
1423                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1424
1425                        Slog.i(TAG, "Verification timed out for " + originUri);
1426                        mPendingVerification.remove(verificationId);
1427
1428                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1429
1430                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1431                            Slog.i(TAG, "Continuing with installation of " + originUri);
1432                            state.setVerifierResponse(Binder.getCallingUid(),
1433                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1434                            broadcastPackageVerified(verificationId, originUri,
1435                                    PackageManager.VERIFICATION_ALLOW,
1436                                    state.getInstallArgs().getUser());
1437                            try {
1438                                ret = args.copyApk(mContainerService, true);
1439                            } catch (RemoteException e) {
1440                                Slog.e(TAG, "Could not contact the ContainerService");
1441                            }
1442                        } else {
1443                            broadcastPackageVerified(verificationId, originUri,
1444                                    PackageManager.VERIFICATION_REJECT,
1445                                    state.getInstallArgs().getUser());
1446                        }
1447
1448                        processPendingInstall(args, ret);
1449                        mHandler.sendEmptyMessage(MCS_UNBIND);
1450                    }
1451                    break;
1452                }
1453                case PACKAGE_VERIFIED: {
1454                    final int verificationId = msg.arg1;
1455
1456                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1457                    if (state == null) {
1458                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1459                        break;
1460                    }
1461
1462                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1463
1464                    state.setVerifierResponse(response.callerUid, response.code);
1465
1466                    if (state.isVerificationComplete()) {
1467                        mPendingVerification.remove(verificationId);
1468
1469                        final InstallArgs args = state.getInstallArgs();
1470                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1471
1472                        int ret;
1473                        if (state.isInstallAllowed()) {
1474                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1475                            broadcastPackageVerified(verificationId, originUri,
1476                                    response.code, state.getInstallArgs().getUser());
1477                            try {
1478                                ret = args.copyApk(mContainerService, true);
1479                            } catch (RemoteException e) {
1480                                Slog.e(TAG, "Could not contact the ContainerService");
1481                            }
1482                        } else {
1483                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1484                        }
1485
1486                        processPendingInstall(args, ret);
1487
1488                        mHandler.sendEmptyMessage(MCS_UNBIND);
1489                    }
1490
1491                    break;
1492                }
1493                case START_INTENT_FILTER_VERIFICATIONS: {
1494                    int userId = msg.arg1;
1495                    int verifierUid = msg.arg2;
1496                    PackageParser.Package pkg = (PackageParser.Package)msg.obj;
1497
1498                    verifyIntentFiltersIfNeeded(userId, verifierUid, pkg);
1499                    break;
1500                }
1501                case INTENT_FILTER_VERIFIED: {
1502                    final int verificationId = msg.arg1;
1503
1504                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1505                            verificationId);
1506                    if (state == null) {
1507                        Slog.w(TAG, "Invalid IntentFilter verification token "
1508                                + verificationId + " received");
1509                        break;
1510                    }
1511
1512                    final int userId = state.getUserId();
1513
1514                    Slog.d(TAG, "Processing IntentFilter verification with token:"
1515                            + verificationId + " and userId:" + userId);
1516
1517                    final IntentFilterVerificationResponse response =
1518                            (IntentFilterVerificationResponse) msg.obj;
1519
1520                    state.setVerifierResponse(response.callerUid, response.code);
1521
1522                    Slog.d(TAG, "IntentFilter verification with token:" + verificationId
1523                            + " and userId:" + userId
1524                            + " is settings verifier response with response code:"
1525                            + response.code);
1526
1527                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1528                        Slog.d(TAG, "Domains failing verification: "
1529                                + response.getFailedDomainsString());
1530                    }
1531
1532                    if (state.isVerificationComplete()) {
1533                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1534                    } else {
1535                        Slog.d(TAG, "IntentFilter verification with token:" + verificationId
1536                                + " was not said to be complete");
1537                    }
1538
1539                    break;
1540                }
1541            }
1542        }
1543    }
1544
1545    private StorageEventListener mStorageListener = new StorageEventListener() {
1546        @Override
1547        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1548            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1549                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1550                    // TODO: ensure that private directories exist for all active users
1551                    // TODO: remove user data whose serial number doesn't match
1552                    loadPrivatePackages(vol);
1553                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1554                    unloadPrivatePackages(vol);
1555                }
1556            }
1557
1558            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1559                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1560                    updateExternalMediaStatus(true, false);
1561                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1562                    updateExternalMediaStatus(false, false);
1563                }
1564            }
1565        }
1566
1567        @Override
1568        public void onVolumeForgotten(String fsUuid) {
1569            // TODO: remove all packages hosted on this uuid
1570        }
1571    };
1572
1573    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) {
1574        if (userId >= UserHandle.USER_OWNER) {
1575            grantRequestedRuntimePermissionsForUser(pkg, userId);
1576        } else if (userId == UserHandle.USER_ALL) {
1577            for (int someUserId : UserManagerService.getInstance().getUserIds()) {
1578                grantRequestedRuntimePermissionsForUser(pkg, someUserId);
1579            }
1580        }
1581    }
1582
1583    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) {
1584        SettingBase sb = (SettingBase) pkg.mExtras;
1585        if (sb == null) {
1586            return;
1587        }
1588
1589        PermissionsState permissionsState = sb.getPermissionsState();
1590
1591        for (String permission : pkg.requestedPermissions) {
1592            BasePermission bp = mSettings.mPermissions.get(permission);
1593            if (bp != null && bp.isRuntime()) {
1594                permissionsState.grantRuntimePermission(bp, userId);
1595            }
1596        }
1597    }
1598
1599    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1600        Bundle extras = null;
1601        switch (res.returnCode) {
1602            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1603                extras = new Bundle();
1604                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1605                        res.origPermission);
1606                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1607                        res.origPackage);
1608                break;
1609            }
1610            case PackageManager.INSTALL_SUCCEEDED: {
1611                extras = new Bundle();
1612                extras.putBoolean(Intent.EXTRA_REPLACING,
1613                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1614                break;
1615            }
1616        }
1617        return extras;
1618    }
1619
1620    void scheduleWriteSettingsLocked() {
1621        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1622            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1623        }
1624    }
1625
1626    void scheduleWritePackageRestrictionsLocked(int userId) {
1627        if (!sUserManager.exists(userId)) return;
1628        mDirtyUsers.add(userId);
1629        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1630            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1631        }
1632    }
1633
1634    public static PackageManagerService main(Context context, Installer installer,
1635            boolean factoryTest, boolean onlyCore) {
1636        PackageManagerService m = new PackageManagerService(context, installer,
1637                factoryTest, onlyCore);
1638        ServiceManager.addService("package", m);
1639        return m;
1640    }
1641
1642    static String[] splitString(String str, char sep) {
1643        int count = 1;
1644        int i = 0;
1645        while ((i=str.indexOf(sep, i)) >= 0) {
1646            count++;
1647            i++;
1648        }
1649
1650        String[] res = new String[count];
1651        i=0;
1652        count = 0;
1653        int lastI=0;
1654        while ((i=str.indexOf(sep, i)) >= 0) {
1655            res[count] = str.substring(lastI, i);
1656            count++;
1657            i++;
1658            lastI = i;
1659        }
1660        res[count] = str.substring(lastI, str.length());
1661        return res;
1662    }
1663
1664    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1665        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1666                Context.DISPLAY_SERVICE);
1667        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1668    }
1669
1670    public PackageManagerService(Context context, Installer installer,
1671            boolean factoryTest, boolean onlyCore) {
1672        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1673                SystemClock.uptimeMillis());
1674
1675        if (mSdkVersion <= 0) {
1676            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1677        }
1678
1679        mContext = context;
1680        mFactoryTest = factoryTest;
1681        mOnlyCore = onlyCore;
1682        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1683        mMetrics = new DisplayMetrics();
1684        mSettings = new Settings(mPackages);
1685        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1686                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1687        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1688                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1689        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1690                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1691        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1692                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1693        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1694                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1695        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1696                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1697
1698        // TODO: add a property to control this?
1699        long dexOptLRUThresholdInMinutes;
1700        if (mLazyDexOpt) {
1701            dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1702        } else {
1703            dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1704        }
1705        mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1706
1707        String separateProcesses = SystemProperties.get("debug.separate_processes");
1708        if (separateProcesses != null && separateProcesses.length() > 0) {
1709            if ("*".equals(separateProcesses)) {
1710                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1711                mSeparateProcesses = null;
1712                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1713            } else {
1714                mDefParseFlags = 0;
1715                mSeparateProcesses = separateProcesses.split(",");
1716                Slog.w(TAG, "Running with debug.separate_processes: "
1717                        + separateProcesses);
1718            }
1719        } else {
1720            mDefParseFlags = 0;
1721            mSeparateProcesses = null;
1722        }
1723
1724        mInstaller = installer;
1725        mPackageDexOptimizer = new PackageDexOptimizer(this);
1726        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1727
1728        getDefaultDisplayMetrics(context, mMetrics);
1729
1730        SystemConfig systemConfig = SystemConfig.getInstance();
1731        mGlobalGids = systemConfig.getGlobalGids();
1732        mSystemPermissions = systemConfig.getSystemPermissions();
1733        mAvailableFeatures = systemConfig.getAvailableFeatures();
1734
1735        synchronized (mInstallLock) {
1736        // writer
1737        synchronized (mPackages) {
1738            mHandlerThread = new ServiceThread(TAG,
1739                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1740            mHandlerThread.start();
1741            mHandler = new PackageHandler(mHandlerThread.getLooper());
1742            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1743
1744            File dataDir = Environment.getDataDirectory();
1745            mAppDataDir = new File(dataDir, "data");
1746            mAppInstallDir = new File(dataDir, "app");
1747            mAppLib32InstallDir = new File(dataDir, "app-lib");
1748            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1749            mUserAppDataDir = new File(dataDir, "user");
1750            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1751
1752            sUserManager = new UserManagerService(context, this,
1753                    mInstallLock, mPackages);
1754
1755            // Propagate permission configuration in to package manager.
1756            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1757                    = systemConfig.getPermissions();
1758            for (int i=0; i<permConfig.size(); i++) {
1759                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1760                BasePermission bp = mSettings.mPermissions.get(perm.name);
1761                if (bp == null) {
1762                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1763                    mSettings.mPermissions.put(perm.name, bp);
1764                }
1765                if (perm.gids != null) {
1766                    bp.setGids(perm.gids, perm.perUser);
1767                }
1768            }
1769
1770            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1771            for (int i=0; i<libConfig.size(); i++) {
1772                mSharedLibraries.put(libConfig.keyAt(i),
1773                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1774            }
1775
1776            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1777
1778            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1779                    mSdkVersion, mOnlyCore);
1780
1781            String customResolverActivity = Resources.getSystem().getString(
1782                    R.string.config_customResolverActivity);
1783            if (TextUtils.isEmpty(customResolverActivity)) {
1784                customResolverActivity = null;
1785            } else {
1786                mCustomResolverComponentName = ComponentName.unflattenFromString(
1787                        customResolverActivity);
1788            }
1789
1790            long startTime = SystemClock.uptimeMillis();
1791
1792            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1793                    startTime);
1794
1795            // Set flag to monitor and not change apk file paths when
1796            // scanning install directories.
1797            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
1798
1799            final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1800
1801            /**
1802             * Add everything in the in the boot class path to the
1803             * list of process files because dexopt will have been run
1804             * if necessary during zygote startup.
1805             */
1806            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1807            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1808
1809            if (bootClassPath != null) {
1810                String[] bootClassPathElements = splitString(bootClassPath, ':');
1811                for (String element : bootClassPathElements) {
1812                    alreadyDexOpted.add(element);
1813                }
1814            } else {
1815                Slog.w(TAG, "No BOOTCLASSPATH found!");
1816            }
1817
1818            if (systemServerClassPath != null) {
1819                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1820                for (String element : systemServerClassPathElements) {
1821                    alreadyDexOpted.add(element);
1822                }
1823            } else {
1824                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1825            }
1826
1827            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
1828            final String[] dexCodeInstructionSets =
1829                    getDexCodeInstructionSets(
1830                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
1831
1832            /**
1833             * Ensure all external libraries have had dexopt run on them.
1834             */
1835            if (mSharedLibraries.size() > 0) {
1836                // NOTE: For now, we're compiling these system "shared libraries"
1837                // (and framework jars) into all available architectures. It's possible
1838                // to compile them only when we come across an app that uses them (there's
1839                // already logic for that in scanPackageLI) but that adds some complexity.
1840                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1841                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1842                        final String lib = libEntry.path;
1843                        if (lib == null) {
1844                            continue;
1845                        }
1846
1847                        try {
1848                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
1849                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1850                                alreadyDexOpted.add(lib);
1851                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1852                            }
1853                        } catch (FileNotFoundException e) {
1854                            Slog.w(TAG, "Library not found: " + lib);
1855                        } catch (IOException e) {
1856                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1857                                    + e.getMessage());
1858                        }
1859                    }
1860                }
1861            }
1862
1863            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1864
1865            // Gross hack for now: we know this file doesn't contain any
1866            // code, so don't dexopt it to avoid the resulting log spew.
1867            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1868
1869            // Gross hack for now: we know this file is only part of
1870            // the boot class path for art, so don't dexopt it to
1871            // avoid the resulting log spew.
1872            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1873
1874            /**
1875             * And there are a number of commands implemented in Java, which
1876             * we currently need to do the dexopt on so that they can be
1877             * run from a non-root shell.
1878             */
1879            String[] frameworkFiles = frameworkDir.list();
1880            if (frameworkFiles != null) {
1881                // TODO: We could compile these only for the most preferred ABI. We should
1882                // first double check that the dex files for these commands are not referenced
1883                // by other system apps.
1884                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1885                    for (int i=0; i<frameworkFiles.length; i++) {
1886                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1887                        String path = libPath.getPath();
1888                        // Skip the file if we already did it.
1889                        if (alreadyDexOpted.contains(path)) {
1890                            continue;
1891                        }
1892                        // Skip the file if it is not a type we want to dexopt.
1893                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1894                            continue;
1895                        }
1896                        try {
1897                            int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false);
1898                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1899                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1900                            }
1901                        } catch (FileNotFoundException e) {
1902                            Slog.w(TAG, "Jar not found: " + path);
1903                        } catch (IOException e) {
1904                            Slog.w(TAG, "Exception reading jar: " + path, e);
1905                        }
1906                    }
1907                }
1908            }
1909
1910            // Collect vendor overlay packages.
1911            // (Do this before scanning any apps.)
1912            // For security and version matching reason, only consider
1913            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1914            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1915            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1916                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
1917
1918            // Find base frameworks (resource packages without code).
1919            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1920                    | PackageParser.PARSE_IS_SYSTEM_DIR
1921                    | PackageParser.PARSE_IS_PRIVILEGED,
1922                    scanFlags | SCAN_NO_DEX, 0);
1923
1924            // Collected privileged system packages.
1925            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1926            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1927                    | PackageParser.PARSE_IS_SYSTEM_DIR
1928                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
1929
1930            // Collect ordinary system packages.
1931            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
1932            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1933                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1934
1935            // Collect all vendor packages.
1936            File vendorAppDir = new File("/vendor/app");
1937            try {
1938                vendorAppDir = vendorAppDir.getCanonicalFile();
1939            } catch (IOException e) {
1940                // failed to look up canonical path, continue with original one
1941            }
1942            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1943                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1944
1945            // Collect all OEM packages.
1946            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
1947            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
1948                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1949
1950            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1951            mInstaller.moveFiles();
1952
1953            // Prune any system packages that no longer exist.
1954            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
1955            final ArrayMap<String, File> expectingBetter = new ArrayMap<>();
1956            if (!mOnlyCore) {
1957                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1958                while (psit.hasNext()) {
1959                    PackageSetting ps = psit.next();
1960
1961                    /*
1962                     * If this is not a system app, it can't be a
1963                     * disable system app.
1964                     */
1965                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
1966                        continue;
1967                    }
1968
1969                    /*
1970                     * If the package is scanned, it's not erased.
1971                     */
1972                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
1973                    if (scannedPkg != null) {
1974                        /*
1975                         * If the system app is both scanned and in the
1976                         * disabled packages list, then it must have been
1977                         * added via OTA. Remove it from the currently
1978                         * scanned package so the previously user-installed
1979                         * application can be scanned.
1980                         */
1981                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
1982                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
1983                                    + ps.name + "; removing system app.  Last known codePath="
1984                                    + ps.codePathString + ", installStatus=" + ps.installStatus
1985                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
1986                                    + scannedPkg.mVersionCode);
1987                            removePackageLI(ps, true);
1988                            expectingBetter.put(ps.name, ps.codePath);
1989                        }
1990
1991                        continue;
1992                    }
1993
1994                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
1995                        psit.remove();
1996                        logCriticalInfo(Log.WARN, "System package " + ps.name
1997                                + " no longer exists; wiping its data");
1998                        removeDataDirsLI(null, ps.name);
1999                    } else {
2000                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2001                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2002                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2003                        }
2004                    }
2005                }
2006            }
2007
2008            //look for any incomplete package installations
2009            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2010            //clean up list
2011            for(int i = 0; i < deletePkgsList.size(); i++) {
2012                //clean up here
2013                cleanupInstallFailedPackage(deletePkgsList.get(i));
2014            }
2015            //delete tmp files
2016            deleteTempPackageFiles();
2017
2018            // Remove any shared userIDs that have no associated packages
2019            mSettings.pruneSharedUsersLPw();
2020
2021            if (!mOnlyCore) {
2022                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2023                        SystemClock.uptimeMillis());
2024                scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2025
2026                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2027                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2028
2029                /**
2030                 * Remove disable package settings for any updated system
2031                 * apps that were removed via an OTA. If they're not a
2032                 * previously-updated app, remove them completely.
2033                 * Otherwise, just revoke their system-level permissions.
2034                 */
2035                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2036                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2037                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2038
2039                    String msg;
2040                    if (deletedPkg == null) {
2041                        msg = "Updated system package " + deletedAppName
2042                                + " no longer exists; wiping its data";
2043                        removeDataDirsLI(null, deletedAppName);
2044                    } else {
2045                        msg = "Updated system app + " + deletedAppName
2046                                + " no longer present; removing system privileges for "
2047                                + deletedAppName;
2048
2049                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2050
2051                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2052                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2053                    }
2054                    logCriticalInfo(Log.WARN, msg);
2055                }
2056
2057                /**
2058                 * Make sure all system apps that we expected to appear on
2059                 * the userdata partition actually showed up. If they never
2060                 * appeared, crawl back and revive the system version.
2061                 */
2062                for (int i = 0; i < expectingBetter.size(); i++) {
2063                    final String packageName = expectingBetter.keyAt(i);
2064                    if (!mPackages.containsKey(packageName)) {
2065                        final File scanFile = expectingBetter.valueAt(i);
2066
2067                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2068                                + " but never showed up; reverting to system");
2069
2070                        final int reparseFlags;
2071                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2072                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2073                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2074                                    | PackageParser.PARSE_IS_PRIVILEGED;
2075                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2076                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2077                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2078                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2079                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2080                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2081                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2082                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2083                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2084                        } else {
2085                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2086                            continue;
2087                        }
2088
2089                        mSettings.enableSystemPackageLPw(packageName);
2090
2091                        try {
2092                            scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
2093                        } catch (PackageManagerException e) {
2094                            Slog.e(TAG, "Failed to parse original system package: "
2095                                    + e.getMessage());
2096                        }
2097                    }
2098                }
2099            }
2100
2101            // Now that we know all of the shared libraries, update all clients to have
2102            // the correct library paths.
2103            updateAllSharedLibrariesLPw();
2104
2105            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2106                // NOTE: We ignore potential failures here during a system scan (like
2107                // the rest of the commands above) because there's precious little we
2108                // can do about it. A settings error is reported, though.
2109                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2110                        false /* force dexopt */, false /* defer dexopt */);
2111            }
2112
2113            // Now that we know all the packages we are keeping,
2114            // read and update their last usage times.
2115            mPackageUsage.readLP();
2116
2117            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2118                    SystemClock.uptimeMillis());
2119            Slog.i(TAG, "Time to scan packages: "
2120                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2121                    + " seconds");
2122
2123            // If the platform SDK has changed since the last time we booted,
2124            // we need to re-grant app permission to catch any new ones that
2125            // appear.  This is really a hack, and means that apps can in some
2126            // cases get permissions that the user didn't initially explicitly
2127            // allow...  it would be nice to have some better way to handle
2128            // this situation.
2129            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
2130                    != mSdkVersion;
2131            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
2132                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
2133                    + "; regranting permissions for internal storage");
2134            mSettings.mInternalSdkPlatform = mSdkVersion;
2135
2136            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
2137                    | (regrantPermissions
2138                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
2139                            : 0));
2140
2141            // If this is the first boot, and it is a normal boot, then
2142            // we need to initialize the default preferred apps.
2143            if (!mRestoredSettings && !onlyCore) {
2144                mSettings.readDefaultPreferredAppsLPw(this, 0);
2145            }
2146
2147            // If this is first boot after an OTA, and a normal boot, then
2148            // we need to clear code cache directories.
2149            mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint);
2150            if (mIsUpgrade && !onlyCore) {
2151                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2152                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2153                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2154                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2155                }
2156                mSettings.mFingerprint = Build.FINGERPRINT;
2157            }
2158
2159            primeDomainVerificationsLPw(false);
2160            checkDefaultBrowser();
2161
2162            // All the changes are done during package scanning.
2163            mSettings.updateInternalDatabaseVersion();
2164
2165            // can downgrade to reader
2166            mSettings.writeLPr();
2167
2168            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2169                    SystemClock.uptimeMillis());
2170
2171            mRequiredVerifierPackage = getRequiredVerifierLPr();
2172
2173            mInstallerService = new PackageInstallerService(context, this);
2174
2175            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2176            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2177                    mIntentFilterVerifierComponent);
2178
2179        } // synchronized (mPackages)
2180        } // synchronized (mInstallLock)
2181
2182        // Now after opening every single application zip, make sure they
2183        // are all flushed.  Not really needed, but keeps things nice and
2184        // tidy.
2185        Runtime.getRuntime().gc();
2186    }
2187
2188    @Override
2189    public boolean isFirstBoot() {
2190        return !mRestoredSettings;
2191    }
2192
2193    @Override
2194    public boolean isOnlyCoreApps() {
2195        return mOnlyCore;
2196    }
2197
2198    @Override
2199    public boolean isUpgrade() {
2200        return mIsUpgrade;
2201    }
2202
2203    private String getRequiredVerifierLPr() {
2204        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2205        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2206                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
2207
2208        String requiredVerifier = null;
2209
2210        final int N = receivers.size();
2211        for (int i = 0; i < N; i++) {
2212            final ResolveInfo info = receivers.get(i);
2213
2214            if (info.activityInfo == null) {
2215                continue;
2216            }
2217
2218            final String packageName = info.activityInfo.packageName;
2219
2220            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2221                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2222                continue;
2223            }
2224
2225            if (requiredVerifier != null) {
2226                throw new RuntimeException("There can be only one required verifier");
2227            }
2228
2229            requiredVerifier = packageName;
2230        }
2231
2232        return requiredVerifier;
2233    }
2234
2235    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2236        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2237        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2238                PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */);
2239
2240        ComponentName verifierComponentName = null;
2241
2242        int priority = -1000;
2243        final int N = receivers.size();
2244        for (int i = 0; i < N; i++) {
2245            final ResolveInfo info = receivers.get(i);
2246
2247            if (info.activityInfo == null) {
2248                continue;
2249            }
2250
2251            final String packageName = info.activityInfo.packageName;
2252
2253            final PackageSetting ps = mSettings.mPackages.get(packageName);
2254            if (ps == null) {
2255                continue;
2256            }
2257
2258            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2259                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2260                continue;
2261            }
2262
2263            // Select the IntentFilterVerifier with the highest priority
2264            if (priority < info.priority) {
2265                priority = info.priority;
2266                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2267                Slog.d(TAG, "Selecting IntentFilterVerifier: " + verifierComponentName +
2268                        " with priority: " + info.priority);
2269            }
2270        }
2271
2272        return verifierComponentName;
2273    }
2274
2275    private void primeDomainVerificationsLPw(boolean logging) {
2276        Slog.d(TAG, "Start priming domain verifications");
2277        boolean updated = false;
2278        ArraySet<String> allHostsSet = new ArraySet<>();
2279        for (PackageParser.Package pkg : mPackages.values()) {
2280            final String packageName = pkg.packageName;
2281            if (!hasDomainURLs(pkg)) {
2282                if (logging) {
2283                    Slog.d(TAG, "No priming domain verifications for " +
2284                            "package with no domain URLs: " + packageName);
2285                }
2286                continue;
2287            }
2288            if (!pkg.isSystemApp()) {
2289                if (logging) {
2290                    Slog.d(TAG, "No priming domain verifications for a non system package : " +
2291                            packageName);
2292                }
2293                continue;
2294            }
2295            for (PackageParser.Activity a : pkg.activities) {
2296                for (ActivityIntentInfo filter : a.intents) {
2297                    if (hasValidDomains(filter, false)) {
2298                        allHostsSet.addAll(filter.getHostsList());
2299                    }
2300                }
2301            }
2302            if (allHostsSet.size() == 0) {
2303                allHostsSet.add("*");
2304            }
2305            ArrayList<String> allHostsList = new ArrayList<>(allHostsSet);
2306            IntentFilterVerificationInfo ivi =
2307                    mSettings.createIntentFilterVerificationIfNeededLPw(packageName, allHostsList);
2308            if (ivi != null) {
2309                // We will always log this
2310                Slog.d(TAG, "Priming domain verifications for package: " + packageName +
2311                        " with hosts:" + ivi.getDomainsString());
2312                ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
2313                updated = true;
2314            }
2315            else {
2316                if (logging) {
2317                    Slog.d(TAG, "No priming domain verifications for package: " + packageName);
2318                }
2319            }
2320            allHostsSet.clear();
2321        }
2322        if (updated) {
2323            if (logging) {
2324                Slog.d(TAG, "Will need to write primed domain verifications");
2325            }
2326        }
2327        Slog.d(TAG, "End priming domain verifications");
2328    }
2329
2330    private void checkDefaultBrowser() {
2331        final int myUserId = UserHandle.myUserId();
2332        final String packageName = getDefaultBrowserPackageName(myUserId);
2333        PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2334        if (info == null) {
2335            Slog.w(TAG, "Clearing default Browser as its package is no more installed: " +
2336                    packageName);
2337            setDefaultBrowserPackageName(null, myUserId);
2338        }
2339    }
2340
2341    @Override
2342    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2343            throws RemoteException {
2344        try {
2345            return super.onTransact(code, data, reply, flags);
2346        } catch (RuntimeException e) {
2347            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2348                Slog.wtf(TAG, "Package Manager Crash", e);
2349            }
2350            throw e;
2351        }
2352    }
2353
2354    void cleanupInstallFailedPackage(PackageSetting ps) {
2355        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2356
2357        removeDataDirsLI(ps.volumeUuid, ps.name);
2358        if (ps.codePath != null) {
2359            if (ps.codePath.isDirectory()) {
2360                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2361            } else {
2362                ps.codePath.delete();
2363            }
2364        }
2365        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2366            if (ps.resourcePath.isDirectory()) {
2367                FileUtils.deleteContents(ps.resourcePath);
2368            }
2369            ps.resourcePath.delete();
2370        }
2371        mSettings.removePackageLPw(ps.name);
2372    }
2373
2374    static int[] appendInts(int[] cur, int[] add) {
2375        if (add == null) return cur;
2376        if (cur == null) return add;
2377        final int N = add.length;
2378        for (int i=0; i<N; i++) {
2379            cur = appendInt(cur, add[i]);
2380        }
2381        return cur;
2382    }
2383
2384    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2385        if (!sUserManager.exists(userId)) return null;
2386        final PackageSetting ps = (PackageSetting) p.mExtras;
2387        if (ps == null) {
2388            return null;
2389        }
2390
2391        final PermissionsState permissionsState = ps.getPermissionsState();
2392
2393        final int[] gids = permissionsState.computeGids(userId);
2394        final Set<String> permissions = permissionsState.getPermissions(userId);
2395        final PackageUserState state = ps.readUserState(userId);
2396
2397        return PackageParser.generatePackageInfo(p, gids, flags,
2398                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2399    }
2400
2401    @Override
2402    public boolean isPackageFrozen(String packageName) {
2403        synchronized (mPackages) {
2404            final PackageSetting ps = mSettings.mPackages.get(packageName);
2405            if (ps != null) {
2406                return ps.frozen;
2407            }
2408        }
2409        Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen");
2410        return true;
2411    }
2412
2413    @Override
2414    public boolean isPackageAvailable(String packageName, int userId) {
2415        if (!sUserManager.exists(userId)) return false;
2416        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2417        synchronized (mPackages) {
2418            PackageParser.Package p = mPackages.get(packageName);
2419            if (p != null) {
2420                final PackageSetting ps = (PackageSetting) p.mExtras;
2421                if (ps != null) {
2422                    final PackageUserState state = ps.readUserState(userId);
2423                    if (state != null) {
2424                        return PackageParser.isAvailable(state);
2425                    }
2426                }
2427            }
2428        }
2429        return false;
2430    }
2431
2432    @Override
2433    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2434        if (!sUserManager.exists(userId)) return null;
2435        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2436        // reader
2437        synchronized (mPackages) {
2438            PackageParser.Package p = mPackages.get(packageName);
2439            if (DEBUG_PACKAGE_INFO)
2440                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2441            if (p != null) {
2442                return generatePackageInfo(p, flags, userId);
2443            }
2444            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2445                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2446            }
2447        }
2448        return null;
2449    }
2450
2451    @Override
2452    public String[] currentToCanonicalPackageNames(String[] names) {
2453        String[] out = new String[names.length];
2454        // reader
2455        synchronized (mPackages) {
2456            for (int i=names.length-1; i>=0; i--) {
2457                PackageSetting ps = mSettings.mPackages.get(names[i]);
2458                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2459            }
2460        }
2461        return out;
2462    }
2463
2464    @Override
2465    public String[] canonicalToCurrentPackageNames(String[] names) {
2466        String[] out = new String[names.length];
2467        // reader
2468        synchronized (mPackages) {
2469            for (int i=names.length-1; i>=0; i--) {
2470                String cur = mSettings.mRenamedPackages.get(names[i]);
2471                out[i] = cur != null ? cur : names[i];
2472            }
2473        }
2474        return out;
2475    }
2476
2477    @Override
2478    public int getPackageUid(String packageName, int userId) {
2479        if (!sUserManager.exists(userId)) return -1;
2480        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2481
2482        // reader
2483        synchronized (mPackages) {
2484            PackageParser.Package p = mPackages.get(packageName);
2485            if(p != null) {
2486                return UserHandle.getUid(userId, p.applicationInfo.uid);
2487            }
2488            PackageSetting ps = mSettings.mPackages.get(packageName);
2489            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2490                return -1;
2491            }
2492            p = ps.pkg;
2493            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2494        }
2495    }
2496
2497    @Override
2498    public int[] getPackageGids(String packageName, int userId) throws RemoteException {
2499        if (!sUserManager.exists(userId)) {
2500            return null;
2501        }
2502
2503        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2504                "getPackageGids");
2505
2506        // reader
2507        synchronized (mPackages) {
2508            PackageParser.Package p = mPackages.get(packageName);
2509            if (DEBUG_PACKAGE_INFO) {
2510                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2511            }
2512            if (p != null) {
2513                PackageSetting ps = (PackageSetting) p.mExtras;
2514                return ps.getPermissionsState().computeGids(userId);
2515            }
2516        }
2517
2518        return null;
2519    }
2520
2521    static PermissionInfo generatePermissionInfo(
2522            BasePermission bp, int flags) {
2523        if (bp.perm != null) {
2524            return PackageParser.generatePermissionInfo(bp.perm, flags);
2525        }
2526        PermissionInfo pi = new PermissionInfo();
2527        pi.name = bp.name;
2528        pi.packageName = bp.sourcePackage;
2529        pi.nonLocalizedLabel = bp.name;
2530        pi.protectionLevel = bp.protectionLevel;
2531        return pi;
2532    }
2533
2534    @Override
2535    public PermissionInfo getPermissionInfo(String name, int flags) {
2536        // reader
2537        synchronized (mPackages) {
2538            final BasePermission p = mSettings.mPermissions.get(name);
2539            if (p != null) {
2540                return generatePermissionInfo(p, flags);
2541            }
2542            return null;
2543        }
2544    }
2545
2546    @Override
2547    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2548        // reader
2549        synchronized (mPackages) {
2550            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2551            for (BasePermission p : mSettings.mPermissions.values()) {
2552                if (group == null) {
2553                    if (p.perm == null || p.perm.info.group == null) {
2554                        out.add(generatePermissionInfo(p, flags));
2555                    }
2556                } else {
2557                    if (p.perm != null && group.equals(p.perm.info.group)) {
2558                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2559                    }
2560                }
2561            }
2562
2563            if (out.size() > 0) {
2564                return out;
2565            }
2566            return mPermissionGroups.containsKey(group) ? out : null;
2567        }
2568    }
2569
2570    @Override
2571    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2572        // reader
2573        synchronized (mPackages) {
2574            return PackageParser.generatePermissionGroupInfo(
2575                    mPermissionGroups.get(name), flags);
2576        }
2577    }
2578
2579    @Override
2580    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2581        // reader
2582        synchronized (mPackages) {
2583            final int N = mPermissionGroups.size();
2584            ArrayList<PermissionGroupInfo> out
2585                    = new ArrayList<PermissionGroupInfo>(N);
2586            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2587                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2588            }
2589            return out;
2590        }
2591    }
2592
2593    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2594            int userId) {
2595        if (!sUserManager.exists(userId)) return null;
2596        PackageSetting ps = mSettings.mPackages.get(packageName);
2597        if (ps != null) {
2598            if (ps.pkg == null) {
2599                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2600                        flags, userId);
2601                if (pInfo != null) {
2602                    return pInfo.applicationInfo;
2603                }
2604                return null;
2605            }
2606            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2607                    ps.readUserState(userId), userId);
2608        }
2609        return null;
2610    }
2611
2612    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2613            int userId) {
2614        if (!sUserManager.exists(userId)) return null;
2615        PackageSetting ps = mSettings.mPackages.get(packageName);
2616        if (ps != null) {
2617            PackageParser.Package pkg = ps.pkg;
2618            if (pkg == null) {
2619                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2620                    return null;
2621                }
2622                // Only data remains, so we aren't worried about code paths
2623                pkg = new PackageParser.Package(packageName);
2624                pkg.applicationInfo.packageName = packageName;
2625                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2626                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2627                pkg.applicationInfo.dataDir = PackageManager.getDataDirForUser(ps.volumeUuid,
2628                        packageName, userId).getAbsolutePath();
2629                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2630                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2631            }
2632            return generatePackageInfo(pkg, flags, userId);
2633        }
2634        return null;
2635    }
2636
2637    @Override
2638    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2639        if (!sUserManager.exists(userId)) return null;
2640        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2641        // writer
2642        synchronized (mPackages) {
2643            PackageParser.Package p = mPackages.get(packageName);
2644            if (DEBUG_PACKAGE_INFO) Log.v(
2645                    TAG, "getApplicationInfo " + packageName
2646                    + ": " + p);
2647            if (p != null) {
2648                PackageSetting ps = mSettings.mPackages.get(packageName);
2649                if (ps == null) return null;
2650                // Note: isEnabledLP() does not apply here - always return info
2651                return PackageParser.generateApplicationInfo(
2652                        p, flags, ps.readUserState(userId), userId);
2653            }
2654            if ("android".equals(packageName)||"system".equals(packageName)) {
2655                return mAndroidApplication;
2656            }
2657            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2658                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2659            }
2660        }
2661        return null;
2662    }
2663
2664    @Override
2665    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
2666            final IPackageDataObserver observer) {
2667        mContext.enforceCallingOrSelfPermission(
2668                android.Manifest.permission.CLEAR_APP_CACHE, null);
2669        // Queue up an async operation since clearing cache may take a little while.
2670        mHandler.post(new Runnable() {
2671            public void run() {
2672                mHandler.removeCallbacks(this);
2673                int retCode = -1;
2674                synchronized (mInstallLock) {
2675                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2676                    if (retCode < 0) {
2677                        Slog.w(TAG, "Couldn't clear application caches");
2678                    }
2679                }
2680                if (observer != null) {
2681                    try {
2682                        observer.onRemoveCompleted(null, (retCode >= 0));
2683                    } catch (RemoteException e) {
2684                        Slog.w(TAG, "RemoveException when invoking call back");
2685                    }
2686                }
2687            }
2688        });
2689    }
2690
2691    @Override
2692    public void freeStorage(final String volumeUuid, final long freeStorageSize,
2693            final IntentSender pi) {
2694        mContext.enforceCallingOrSelfPermission(
2695                android.Manifest.permission.CLEAR_APP_CACHE, null);
2696        // Queue up an async operation since clearing cache may take a little while.
2697        mHandler.post(new Runnable() {
2698            public void run() {
2699                mHandler.removeCallbacks(this);
2700                int retCode = -1;
2701                synchronized (mInstallLock) {
2702                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2703                    if (retCode < 0) {
2704                        Slog.w(TAG, "Couldn't clear application caches");
2705                    }
2706                }
2707                if(pi != null) {
2708                    try {
2709                        // Callback via pending intent
2710                        int code = (retCode >= 0) ? 1 : 0;
2711                        pi.sendIntent(null, code, null,
2712                                null, null);
2713                    } catch (SendIntentException e1) {
2714                        Slog.i(TAG, "Failed to send pending intent");
2715                    }
2716                }
2717            }
2718        });
2719    }
2720
2721    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
2722        synchronized (mInstallLock) {
2723            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
2724                throw new IOException("Failed to free enough space");
2725            }
2726        }
2727    }
2728
2729    @Override
2730    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2731        if (!sUserManager.exists(userId)) return null;
2732        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2733        synchronized (mPackages) {
2734            PackageParser.Activity a = mActivities.mActivities.get(component);
2735
2736            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2737            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2738                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2739                if (ps == null) return null;
2740                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2741                        userId);
2742            }
2743            if (mResolveComponentName.equals(component)) {
2744                return PackageParser.generateActivityInfo(mResolveActivity, flags,
2745                        new PackageUserState(), userId);
2746            }
2747        }
2748        return null;
2749    }
2750
2751    @Override
2752    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2753            String resolvedType) {
2754        synchronized (mPackages) {
2755            PackageParser.Activity a = mActivities.mActivities.get(component);
2756            if (a == null) {
2757                return false;
2758            }
2759            for (int i=0; i<a.intents.size(); i++) {
2760                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2761                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2762                    return true;
2763                }
2764            }
2765            return false;
2766        }
2767    }
2768
2769    @Override
2770    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2771        if (!sUserManager.exists(userId)) return null;
2772        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
2773        synchronized (mPackages) {
2774            PackageParser.Activity a = mReceivers.mActivities.get(component);
2775            if (DEBUG_PACKAGE_INFO) Log.v(
2776                TAG, "getReceiverInfo " + component + ": " + a);
2777            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2778                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2779                if (ps == null) return null;
2780                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2781                        userId);
2782            }
2783        }
2784        return null;
2785    }
2786
2787    @Override
2788    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2789        if (!sUserManager.exists(userId)) return null;
2790        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
2791        synchronized (mPackages) {
2792            PackageParser.Service s = mServices.mServices.get(component);
2793            if (DEBUG_PACKAGE_INFO) Log.v(
2794                TAG, "getServiceInfo " + component + ": " + s);
2795            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2796                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2797                if (ps == null) return null;
2798                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2799                        userId);
2800            }
2801        }
2802        return null;
2803    }
2804
2805    @Override
2806    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2807        if (!sUserManager.exists(userId)) return null;
2808        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
2809        synchronized (mPackages) {
2810            PackageParser.Provider p = mProviders.mProviders.get(component);
2811            if (DEBUG_PACKAGE_INFO) Log.v(
2812                TAG, "getProviderInfo " + component + ": " + p);
2813            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2814                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2815                if (ps == null) return null;
2816                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2817                        userId);
2818            }
2819        }
2820        return null;
2821    }
2822
2823    @Override
2824    public String[] getSystemSharedLibraryNames() {
2825        Set<String> libSet;
2826        synchronized (mPackages) {
2827            libSet = mSharedLibraries.keySet();
2828            int size = libSet.size();
2829            if (size > 0) {
2830                String[] libs = new String[size];
2831                libSet.toArray(libs);
2832                return libs;
2833            }
2834        }
2835        return null;
2836    }
2837
2838    /**
2839     * @hide
2840     */
2841    PackageParser.Package findSharedNonSystemLibrary(String libName) {
2842        synchronized (mPackages) {
2843            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
2844            if (lib != null && lib.apk != null) {
2845                return mPackages.get(lib.apk);
2846            }
2847        }
2848        return null;
2849    }
2850
2851    @Override
2852    public FeatureInfo[] getSystemAvailableFeatures() {
2853        Collection<FeatureInfo> featSet;
2854        synchronized (mPackages) {
2855            featSet = mAvailableFeatures.values();
2856            int size = featSet.size();
2857            if (size > 0) {
2858                FeatureInfo[] features = new FeatureInfo[size+1];
2859                featSet.toArray(features);
2860                FeatureInfo fi = new FeatureInfo();
2861                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2862                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2863                features[size] = fi;
2864                return features;
2865            }
2866        }
2867        return null;
2868    }
2869
2870    @Override
2871    public boolean hasSystemFeature(String name) {
2872        synchronized (mPackages) {
2873            return mAvailableFeatures.containsKey(name);
2874        }
2875    }
2876
2877    private void checkValidCaller(int uid, int userId) {
2878        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2879            return;
2880
2881        throw new SecurityException("Caller uid=" + uid
2882                + " is not privileged to communicate with user=" + userId);
2883    }
2884
2885    @Override
2886    public int checkPermission(String permName, String pkgName, int userId) {
2887        if (!sUserManager.exists(userId)) {
2888            return PackageManager.PERMISSION_DENIED;
2889        }
2890
2891        synchronized (mPackages) {
2892            final PackageParser.Package p = mPackages.get(pkgName);
2893            if (p != null && p.mExtras != null) {
2894                final PackageSetting ps = (PackageSetting) p.mExtras;
2895                if (ps.getPermissionsState().hasPermission(permName, userId)) {
2896                    return PackageManager.PERMISSION_GRANTED;
2897                }
2898            }
2899        }
2900
2901        return PackageManager.PERMISSION_DENIED;
2902    }
2903
2904    @Override
2905    public int checkUidPermission(String permName, int uid) {
2906        final int userId = UserHandle.getUserId(uid);
2907
2908        if (!sUserManager.exists(userId)) {
2909            return PackageManager.PERMISSION_DENIED;
2910        }
2911
2912        synchronized (mPackages) {
2913            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2914            if (obj != null) {
2915                final SettingBase ps = (SettingBase) obj;
2916                if (ps.getPermissionsState().hasPermission(permName, userId)) {
2917                    return PackageManager.PERMISSION_GRANTED;
2918                }
2919            } else {
2920                ArraySet<String> perms = mSystemPermissions.get(uid);
2921                if (perms != null && perms.contains(permName)) {
2922                    return PackageManager.PERMISSION_GRANTED;
2923                }
2924            }
2925        }
2926
2927        return PackageManager.PERMISSION_DENIED;
2928    }
2929
2930    /**
2931     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2932     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2933     * @param checkShell TODO(yamasani):
2934     * @param message the message to log on security exception
2935     */
2936    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
2937            boolean checkShell, String message) {
2938        if (userId < 0) {
2939            throw new IllegalArgumentException("Invalid userId " + userId);
2940        }
2941        if (checkShell) {
2942            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
2943        }
2944        if (userId == UserHandle.getUserId(callingUid)) return;
2945        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2946            if (requireFullPermission) {
2947                mContext.enforceCallingOrSelfPermission(
2948                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2949            } else {
2950                try {
2951                    mContext.enforceCallingOrSelfPermission(
2952                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2953                } catch (SecurityException se) {
2954                    mContext.enforceCallingOrSelfPermission(
2955                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2956                }
2957            }
2958        }
2959    }
2960
2961    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
2962        if (callingUid == Process.SHELL_UID) {
2963            if (userHandle >= 0
2964                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
2965                throw new SecurityException("Shell does not have permission to access user "
2966                        + userHandle);
2967            } else if (userHandle < 0) {
2968                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
2969                        + Debug.getCallers(3));
2970            }
2971        }
2972    }
2973
2974    private BasePermission findPermissionTreeLP(String permName) {
2975        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
2976            if (permName.startsWith(bp.name) &&
2977                    permName.length() > bp.name.length() &&
2978                    permName.charAt(bp.name.length()) == '.') {
2979                return bp;
2980            }
2981        }
2982        return null;
2983    }
2984
2985    private BasePermission checkPermissionTreeLP(String permName) {
2986        if (permName != null) {
2987            BasePermission bp = findPermissionTreeLP(permName);
2988            if (bp != null) {
2989                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
2990                    return bp;
2991                }
2992                throw new SecurityException("Calling uid "
2993                        + Binder.getCallingUid()
2994                        + " is not allowed to add to permission tree "
2995                        + bp.name + " owned by uid " + bp.uid);
2996            }
2997        }
2998        throw new SecurityException("No permission tree found for " + permName);
2999    }
3000
3001    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3002        if (s1 == null) {
3003            return s2 == null;
3004        }
3005        if (s2 == null) {
3006            return false;
3007        }
3008        if (s1.getClass() != s2.getClass()) {
3009            return false;
3010        }
3011        return s1.equals(s2);
3012    }
3013
3014    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3015        if (pi1.icon != pi2.icon) return false;
3016        if (pi1.logo != pi2.logo) return false;
3017        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3018        if (!compareStrings(pi1.name, pi2.name)) return false;
3019        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3020        // We'll take care of setting this one.
3021        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3022        // These are not currently stored in settings.
3023        //if (!compareStrings(pi1.group, pi2.group)) return false;
3024        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3025        //if (pi1.labelRes != pi2.labelRes) return false;
3026        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3027        return true;
3028    }
3029
3030    int permissionInfoFootprint(PermissionInfo info) {
3031        int size = info.name.length();
3032        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3033        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3034        return size;
3035    }
3036
3037    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3038        int size = 0;
3039        for (BasePermission perm : mSettings.mPermissions.values()) {
3040            if (perm.uid == tree.uid) {
3041                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3042            }
3043        }
3044        return size;
3045    }
3046
3047    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3048        // We calculate the max size of permissions defined by this uid and throw
3049        // if that plus the size of 'info' would exceed our stated maximum.
3050        if (tree.uid != Process.SYSTEM_UID) {
3051            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3052            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3053                throw new SecurityException("Permission tree size cap exceeded");
3054            }
3055        }
3056    }
3057
3058    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3059        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3060            throw new SecurityException("Label must be specified in permission");
3061        }
3062        BasePermission tree = checkPermissionTreeLP(info.name);
3063        BasePermission bp = mSettings.mPermissions.get(info.name);
3064        boolean added = bp == null;
3065        boolean changed = true;
3066        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3067        if (added) {
3068            enforcePermissionCapLocked(info, tree);
3069            bp = new BasePermission(info.name, tree.sourcePackage,
3070                    BasePermission.TYPE_DYNAMIC);
3071        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3072            throw new SecurityException(
3073                    "Not allowed to modify non-dynamic permission "
3074                    + info.name);
3075        } else {
3076            if (bp.protectionLevel == fixedLevel
3077                    && bp.perm.owner.equals(tree.perm.owner)
3078                    && bp.uid == tree.uid
3079                    && comparePermissionInfos(bp.perm.info, info)) {
3080                changed = false;
3081            }
3082        }
3083        bp.protectionLevel = fixedLevel;
3084        info = new PermissionInfo(info);
3085        info.protectionLevel = fixedLevel;
3086        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3087        bp.perm.info.packageName = tree.perm.info.packageName;
3088        bp.uid = tree.uid;
3089        if (added) {
3090            mSettings.mPermissions.put(info.name, bp);
3091        }
3092        if (changed) {
3093            if (!async) {
3094                mSettings.writeLPr();
3095            } else {
3096                scheduleWriteSettingsLocked();
3097            }
3098        }
3099        return added;
3100    }
3101
3102    @Override
3103    public boolean addPermission(PermissionInfo info) {
3104        synchronized (mPackages) {
3105            return addPermissionLocked(info, false);
3106        }
3107    }
3108
3109    @Override
3110    public boolean addPermissionAsync(PermissionInfo info) {
3111        synchronized (mPackages) {
3112            return addPermissionLocked(info, true);
3113        }
3114    }
3115
3116    @Override
3117    public void removePermission(String name) {
3118        synchronized (mPackages) {
3119            checkPermissionTreeLP(name);
3120            BasePermission bp = mSettings.mPermissions.get(name);
3121            if (bp != null) {
3122                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3123                    throw new SecurityException(
3124                            "Not allowed to modify non-dynamic permission "
3125                            + name);
3126                }
3127                mSettings.mPermissions.remove(name);
3128                mSettings.writeLPr();
3129            }
3130        }
3131    }
3132
3133    private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg,
3134            BasePermission bp) {
3135        int index = pkg.requestedPermissions.indexOf(bp.name);
3136        if (index == -1) {
3137            throw new SecurityException("Package " + pkg.packageName
3138                    + " has not requested permission " + bp.name);
3139        }
3140        if (!bp.isRuntime()) {
3141            throw new SecurityException("Permission " + bp.name
3142                    + " is not a changeable permission type");
3143        }
3144    }
3145
3146    @Override
3147    public void grantRuntimePermission(String packageName, String name, int userId) {
3148        if (!sUserManager.exists(userId)) {
3149            Log.e(TAG, "No such user:" + userId);
3150            return;
3151        }
3152
3153        mContext.enforceCallingOrSelfPermission(
3154                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3155                "grantRuntimePermission");
3156
3157        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3158                "grantRuntimePermission");
3159
3160        boolean gidsChanged = false;
3161        final SettingBase sb;
3162
3163        synchronized (mPackages) {
3164            final PackageParser.Package pkg = mPackages.get(packageName);
3165            if (pkg == null) {
3166                throw new IllegalArgumentException("Unknown package: " + packageName);
3167            }
3168
3169            final BasePermission bp = mSettings.mPermissions.get(name);
3170            if (bp == null) {
3171                throw new IllegalArgumentException("Unknown permission: " + name);
3172            }
3173
3174            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3175
3176            sb = (SettingBase) pkg.mExtras;
3177            if (sb == null) {
3178                throw new IllegalArgumentException("Unknown package: " + packageName);
3179            }
3180
3181            final PermissionsState permissionsState = sb.getPermissionsState();
3182
3183            final int result = permissionsState.grantRuntimePermission(bp, userId);
3184            switch (result) {
3185                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3186                    return;
3187                }
3188
3189                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3190                    gidsChanged = true;
3191                }
3192                break;
3193            }
3194
3195            // Not critical if that is lost - app has to request again.
3196            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3197        }
3198
3199        if (gidsChanged) {
3200            killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED);
3201        }
3202    }
3203
3204    @Override
3205    public void revokeRuntimePermission(String packageName, String name, int userId) {
3206        if (!sUserManager.exists(userId)) {
3207            Log.e(TAG, "No such user:" + userId);
3208            return;
3209        }
3210
3211        mContext.enforceCallingOrSelfPermission(
3212                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3213                "revokeRuntimePermission");
3214
3215        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3216                "revokeRuntimePermission");
3217
3218        final SettingBase sb;
3219
3220        synchronized (mPackages) {
3221            final PackageParser.Package pkg = mPackages.get(packageName);
3222            if (pkg == null) {
3223                throw new IllegalArgumentException("Unknown package: " + packageName);
3224            }
3225
3226            final BasePermission bp = mSettings.mPermissions.get(name);
3227            if (bp == null) {
3228                throw new IllegalArgumentException("Unknown permission: " + name);
3229            }
3230
3231            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3232
3233            sb = (SettingBase) pkg.mExtras;
3234            if (sb == null) {
3235                throw new IllegalArgumentException("Unknown package: " + packageName);
3236            }
3237
3238            final PermissionsState permissionsState = sb.getPermissionsState();
3239
3240            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3241                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3242                return;
3243            }
3244
3245            // Critical, after this call app should never have the permission.
3246            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3247        }
3248
3249        killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3250    }
3251
3252    @Override
3253    public int getPermissionFlags(String name, String packageName, int userId) {
3254        if (!sUserManager.exists(userId)) {
3255            return 0;
3256        }
3257
3258        mContext.enforceCallingOrSelfPermission(
3259                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3260                "getPermissionFlags");
3261
3262        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3263                "getPermissionFlags");
3264
3265        synchronized (mPackages) {
3266            final PackageParser.Package pkg = mPackages.get(packageName);
3267            if (pkg == null) {
3268                throw new IllegalArgumentException("Unknown package: " + packageName);
3269            }
3270
3271            final BasePermission bp = mSettings.mPermissions.get(name);
3272            if (bp == null) {
3273                throw new IllegalArgumentException("Unknown permission: " + name);
3274            }
3275
3276            SettingBase sb = (SettingBase) pkg.mExtras;
3277            if (sb == null) {
3278                throw new IllegalArgumentException("Unknown package: " + packageName);
3279            }
3280
3281            PermissionsState permissionsState = sb.getPermissionsState();
3282            return permissionsState.getPermissionFlags(name, userId);
3283        }
3284    }
3285
3286    @Override
3287    public void updatePermissionFlags(String name, String packageName, int flagMask,
3288            int flagValues, int userId) {
3289        if (!sUserManager.exists(userId)) {
3290            return;
3291        }
3292
3293        mContext.enforceCallingOrSelfPermission(
3294                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3295                "updatePermissionFlags");
3296
3297        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3298                "updatePermissionFlags");
3299
3300        // Only the system can change policy flags.
3301        if (getCallingUid() != Process.SYSTEM_UID) {
3302            flagMask &= ~PackageManager.FLAG_PERMISSION_POLICY_FIXED;
3303            flagValues &= ~PackageManager.FLAG_PERMISSION_POLICY_FIXED;
3304        }
3305
3306        // Only the package manager can change system flags.
3307        flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3308        flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3309
3310        synchronized (mPackages) {
3311            final PackageParser.Package pkg = mPackages.get(packageName);
3312            if (pkg == null) {
3313                throw new IllegalArgumentException("Unknown package: " + packageName);
3314            }
3315
3316            final BasePermission bp = mSettings.mPermissions.get(name);
3317            if (bp == null) {
3318                throw new IllegalArgumentException("Unknown permission: " + name);
3319            }
3320
3321            SettingBase sb = (SettingBase) pkg.mExtras;
3322            if (sb == null) {
3323                throw new IllegalArgumentException("Unknown package: " + packageName);
3324            }
3325
3326            PermissionsState permissionsState = sb.getPermissionsState();
3327
3328            // Only the package manager can change flags for system component permissions.
3329            final int flags = permissionsState.getPermissionFlags(bp.name, userId);
3330            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3331                return;
3332            }
3333
3334            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3335                // Install and runtime permissions are stored in different places,
3336                // so figure out what permission changed and persist the change.
3337                if (permissionsState.getInstallPermissionState(name) != null) {
3338                    scheduleWriteSettingsLocked();
3339                } else if (permissionsState.getRuntimePermissionState(name, userId) != null) {
3340                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3341                }
3342            }
3343        }
3344    }
3345
3346    @Override
3347    public boolean isProtectedBroadcast(String actionName) {
3348        synchronized (mPackages) {
3349            return mProtectedBroadcasts.contains(actionName);
3350        }
3351    }
3352
3353    @Override
3354    public int checkSignatures(String pkg1, String pkg2) {
3355        synchronized (mPackages) {
3356            final PackageParser.Package p1 = mPackages.get(pkg1);
3357            final PackageParser.Package p2 = mPackages.get(pkg2);
3358            if (p1 == null || p1.mExtras == null
3359                    || p2 == null || p2.mExtras == null) {
3360                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3361            }
3362            return compareSignatures(p1.mSignatures, p2.mSignatures);
3363        }
3364    }
3365
3366    @Override
3367    public int checkUidSignatures(int uid1, int uid2) {
3368        // Map to base uids.
3369        uid1 = UserHandle.getAppId(uid1);
3370        uid2 = UserHandle.getAppId(uid2);
3371        // reader
3372        synchronized (mPackages) {
3373            Signature[] s1;
3374            Signature[] s2;
3375            Object obj = mSettings.getUserIdLPr(uid1);
3376            if (obj != null) {
3377                if (obj instanceof SharedUserSetting) {
3378                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3379                } else if (obj instanceof PackageSetting) {
3380                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3381                } else {
3382                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3383                }
3384            } else {
3385                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3386            }
3387            obj = mSettings.getUserIdLPr(uid2);
3388            if (obj != null) {
3389                if (obj instanceof SharedUserSetting) {
3390                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3391                } else if (obj instanceof PackageSetting) {
3392                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3393                } else {
3394                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3395                }
3396            } else {
3397                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3398            }
3399            return compareSignatures(s1, s2);
3400        }
3401    }
3402
3403    private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) {
3404        final long identity = Binder.clearCallingIdentity();
3405        try {
3406            if (sb instanceof SharedUserSetting) {
3407                SharedUserSetting sus = (SharedUserSetting) sb;
3408                final int packageCount = sus.packages.size();
3409                for (int i = 0; i < packageCount; i++) {
3410                    PackageSetting susPs = sus.packages.valueAt(i);
3411                    if (userId == UserHandle.USER_ALL) {
3412                        killApplication(susPs.pkg.packageName, susPs.appId, reason);
3413                    } else {
3414                        final int uid = UserHandle.getUid(userId, susPs.appId);
3415                        killUid(uid, reason);
3416                    }
3417                }
3418            } else if (sb instanceof PackageSetting) {
3419                PackageSetting ps = (PackageSetting) sb;
3420                if (userId == UserHandle.USER_ALL) {
3421                    killApplication(ps.pkg.packageName, ps.appId, reason);
3422                } else {
3423                    final int uid = UserHandle.getUid(userId, ps.appId);
3424                    killUid(uid, reason);
3425                }
3426            }
3427        } finally {
3428            Binder.restoreCallingIdentity(identity);
3429        }
3430    }
3431
3432    private static void killUid(int uid, String reason) {
3433        IActivityManager am = ActivityManagerNative.getDefault();
3434        if (am != null) {
3435            try {
3436                am.killUid(uid, reason);
3437            } catch (RemoteException e) {
3438                /* ignore - same process */
3439            }
3440        }
3441    }
3442
3443    /**
3444     * Compares two sets of signatures. Returns:
3445     * <br />
3446     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3447     * <br />
3448     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3449     * <br />
3450     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3451     * <br />
3452     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3453     * <br />
3454     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3455     */
3456    static int compareSignatures(Signature[] s1, Signature[] s2) {
3457        if (s1 == null) {
3458            return s2 == null
3459                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3460                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3461        }
3462
3463        if (s2 == null) {
3464            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3465        }
3466
3467        if (s1.length != s2.length) {
3468            return PackageManager.SIGNATURE_NO_MATCH;
3469        }
3470
3471        // Since both signature sets are of size 1, we can compare without HashSets.
3472        if (s1.length == 1) {
3473            return s1[0].equals(s2[0]) ?
3474                    PackageManager.SIGNATURE_MATCH :
3475                    PackageManager.SIGNATURE_NO_MATCH;
3476        }
3477
3478        ArraySet<Signature> set1 = new ArraySet<Signature>();
3479        for (Signature sig : s1) {
3480            set1.add(sig);
3481        }
3482        ArraySet<Signature> set2 = new ArraySet<Signature>();
3483        for (Signature sig : s2) {
3484            set2.add(sig);
3485        }
3486        // Make sure s2 contains all signatures in s1.
3487        if (set1.equals(set2)) {
3488            return PackageManager.SIGNATURE_MATCH;
3489        }
3490        return PackageManager.SIGNATURE_NO_MATCH;
3491    }
3492
3493    /**
3494     * If the database version for this type of package (internal storage or
3495     * external storage) is less than the version where package signatures
3496     * were updated, return true.
3497     */
3498    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3499        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
3500                DatabaseVersion.SIGNATURE_END_ENTITY))
3501                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
3502                        DatabaseVersion.SIGNATURE_END_ENTITY));
3503    }
3504
3505    /**
3506     * Used for backward compatibility to make sure any packages with
3507     * certificate chains get upgraded to the new style. {@code existingSigs}
3508     * will be in the old format (since they were stored on disk from before the
3509     * system upgrade) and {@code scannedSigs} will be in the newer format.
3510     */
3511    private int compareSignaturesCompat(PackageSignatures existingSigs,
3512            PackageParser.Package scannedPkg) {
3513        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
3514            return PackageManager.SIGNATURE_NO_MATCH;
3515        }
3516
3517        ArraySet<Signature> existingSet = new ArraySet<Signature>();
3518        for (Signature sig : existingSigs.mSignatures) {
3519            existingSet.add(sig);
3520        }
3521        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
3522        for (Signature sig : scannedPkg.mSignatures) {
3523            try {
3524                Signature[] chainSignatures = sig.getChainSignatures();
3525                for (Signature chainSig : chainSignatures) {
3526                    scannedCompatSet.add(chainSig);
3527                }
3528            } catch (CertificateEncodingException e) {
3529                scannedCompatSet.add(sig);
3530            }
3531        }
3532        /*
3533         * Make sure the expanded scanned set contains all signatures in the
3534         * existing one.
3535         */
3536        if (scannedCompatSet.equals(existingSet)) {
3537            // Migrate the old signatures to the new scheme.
3538            existingSigs.assignSignatures(scannedPkg.mSignatures);
3539            // The new KeySets will be re-added later in the scanning process.
3540            synchronized (mPackages) {
3541                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
3542            }
3543            return PackageManager.SIGNATURE_MATCH;
3544        }
3545        return PackageManager.SIGNATURE_NO_MATCH;
3546    }
3547
3548    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3549        if (isExternal(scannedPkg)) {
3550            return mSettings.isExternalDatabaseVersionOlderThan(
3551                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3552        } else {
3553            return mSettings.isInternalDatabaseVersionOlderThan(
3554                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3555        }
3556    }
3557
3558    private int compareSignaturesRecover(PackageSignatures existingSigs,
3559            PackageParser.Package scannedPkg) {
3560        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
3561            return PackageManager.SIGNATURE_NO_MATCH;
3562        }
3563
3564        String msg = null;
3565        try {
3566            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
3567                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
3568                        + scannedPkg.packageName);
3569                return PackageManager.SIGNATURE_MATCH;
3570            }
3571        } catch (CertificateException e) {
3572            msg = e.getMessage();
3573        }
3574
3575        logCriticalInfo(Log.INFO,
3576                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
3577        return PackageManager.SIGNATURE_NO_MATCH;
3578    }
3579
3580    @Override
3581    public String[] getPackagesForUid(int uid) {
3582        uid = UserHandle.getAppId(uid);
3583        // reader
3584        synchronized (mPackages) {
3585            Object obj = mSettings.getUserIdLPr(uid);
3586            if (obj instanceof SharedUserSetting) {
3587                final SharedUserSetting sus = (SharedUserSetting) obj;
3588                final int N = sus.packages.size();
3589                final String[] res = new String[N];
3590                final Iterator<PackageSetting> it = sus.packages.iterator();
3591                int i = 0;
3592                while (it.hasNext()) {
3593                    res[i++] = it.next().name;
3594                }
3595                return res;
3596            } else if (obj instanceof PackageSetting) {
3597                final PackageSetting ps = (PackageSetting) obj;
3598                return new String[] { ps.name };
3599            }
3600        }
3601        return null;
3602    }
3603
3604    @Override
3605    public String getNameForUid(int uid) {
3606        // reader
3607        synchronized (mPackages) {
3608            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3609            if (obj instanceof SharedUserSetting) {
3610                final SharedUserSetting sus = (SharedUserSetting) obj;
3611                return sus.name + ":" + sus.userId;
3612            } else if (obj instanceof PackageSetting) {
3613                final PackageSetting ps = (PackageSetting) obj;
3614                return ps.name;
3615            }
3616        }
3617        return null;
3618    }
3619
3620    @Override
3621    public int getUidForSharedUser(String sharedUserName) {
3622        if(sharedUserName == null) {
3623            return -1;
3624        }
3625        // reader
3626        synchronized (mPackages) {
3627            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
3628            if (suid == null) {
3629                return -1;
3630            }
3631            return suid.userId;
3632        }
3633    }
3634
3635    @Override
3636    public int getFlagsForUid(int uid) {
3637        synchronized (mPackages) {
3638            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3639            if (obj instanceof SharedUserSetting) {
3640                final SharedUserSetting sus = (SharedUserSetting) obj;
3641                return sus.pkgFlags;
3642            } else if (obj instanceof PackageSetting) {
3643                final PackageSetting ps = (PackageSetting) obj;
3644                return ps.pkgFlags;
3645            }
3646        }
3647        return 0;
3648    }
3649
3650    @Override
3651    public int getPrivateFlagsForUid(int uid) {
3652        synchronized (mPackages) {
3653            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3654            if (obj instanceof SharedUserSetting) {
3655                final SharedUserSetting sus = (SharedUserSetting) obj;
3656                return sus.pkgPrivateFlags;
3657            } else if (obj instanceof PackageSetting) {
3658                final PackageSetting ps = (PackageSetting) obj;
3659                return ps.pkgPrivateFlags;
3660            }
3661        }
3662        return 0;
3663    }
3664
3665    @Override
3666    public boolean isUidPrivileged(int uid) {
3667        uid = UserHandle.getAppId(uid);
3668        // reader
3669        synchronized (mPackages) {
3670            Object obj = mSettings.getUserIdLPr(uid);
3671            if (obj instanceof SharedUserSetting) {
3672                final SharedUserSetting sus = (SharedUserSetting) obj;
3673                final Iterator<PackageSetting> it = sus.packages.iterator();
3674                while (it.hasNext()) {
3675                    if (it.next().isPrivileged()) {
3676                        return true;
3677                    }
3678                }
3679            } else if (obj instanceof PackageSetting) {
3680                final PackageSetting ps = (PackageSetting) obj;
3681                return ps.isPrivileged();
3682            }
3683        }
3684        return false;
3685    }
3686
3687    @Override
3688    public String[] getAppOpPermissionPackages(String permissionName) {
3689        synchronized (mPackages) {
3690            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
3691            if (pkgs == null) {
3692                return null;
3693            }
3694            return pkgs.toArray(new String[pkgs.size()]);
3695        }
3696    }
3697
3698    @Override
3699    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
3700            int flags, int userId) {
3701        if (!sUserManager.exists(userId)) return null;
3702        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
3703        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3704        return chooseBestActivity(intent, resolvedType, flags, query, userId);
3705    }
3706
3707    @Override
3708    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
3709            IntentFilter filter, int match, ComponentName activity) {
3710        final int userId = UserHandle.getCallingUserId();
3711        if (DEBUG_PREFERRED) {
3712            Log.v(TAG, "setLastChosenActivity intent=" + intent
3713                + " resolvedType=" + resolvedType
3714                + " flags=" + flags
3715                + " filter=" + filter
3716                + " match=" + match
3717                + " activity=" + activity);
3718            filter.dump(new PrintStreamPrinter(System.out), "    ");
3719        }
3720        intent.setComponent(null);
3721        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3722        // Find any earlier preferred or last chosen entries and nuke them
3723        findPreferredActivity(intent, resolvedType,
3724                flags, query, 0, false, true, false, userId);
3725        // Add the new activity as the last chosen for this filter
3726        addPreferredActivityInternal(filter, match, null, activity, false, userId,
3727                "Setting last chosen");
3728    }
3729
3730    @Override
3731    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
3732        final int userId = UserHandle.getCallingUserId();
3733        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
3734        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3735        return findPreferredActivity(intent, resolvedType, flags, query, 0,
3736                false, false, false, userId);
3737    }
3738
3739    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
3740            int flags, List<ResolveInfo> query, int userId) {
3741        if (query != null) {
3742            final int N = query.size();
3743            if (N == 1) {
3744                return query.get(0);
3745            } else if (N > 1) {
3746                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
3747                // If there is more than one activity with the same priority,
3748                // then let the user decide between them.
3749                ResolveInfo r0 = query.get(0);
3750                ResolveInfo r1 = query.get(1);
3751                if (DEBUG_INTENT_MATCHING || debug) {
3752                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
3753                            + r1.activityInfo.name + "=" + r1.priority);
3754                }
3755                // If the first activity has a higher priority, or a different
3756                // default, then it is always desireable to pick it.
3757                if (r0.priority != r1.priority
3758                        || r0.preferredOrder != r1.preferredOrder
3759                        || r0.isDefault != r1.isDefault) {
3760                    return query.get(0);
3761                }
3762                // If we have saved a preference for a preferred activity for
3763                // this Intent, use that.
3764                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
3765                        flags, query, r0.priority, true, false, debug, userId);
3766                if (ri != null) {
3767                    return ri;
3768                }
3769                if (userId != 0) {
3770                    ri = new ResolveInfo(mResolveInfo);
3771                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
3772                    ri.activityInfo.applicationInfo = new ApplicationInfo(
3773                            ri.activityInfo.applicationInfo);
3774                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
3775                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
3776                    return ri;
3777                }
3778                return mResolveInfo;
3779            }
3780        }
3781        return null;
3782    }
3783
3784    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
3785            int flags, List<ResolveInfo> query, boolean debug, int userId) {
3786        final int N = query.size();
3787        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
3788                .get(userId);
3789        // Get the list of persistent preferred activities that handle the intent
3790        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
3791        List<PersistentPreferredActivity> pprefs = ppir != null
3792                ? ppir.queryIntent(intent, resolvedType,
3793                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3794                : null;
3795        if (pprefs != null && pprefs.size() > 0) {
3796            final int M = pprefs.size();
3797            for (int i=0; i<M; i++) {
3798                final PersistentPreferredActivity ppa = pprefs.get(i);
3799                if (DEBUG_PREFERRED || debug) {
3800                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
3801                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
3802                            + "\n  component=" + ppa.mComponent);
3803                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3804                }
3805                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
3806                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3807                if (DEBUG_PREFERRED || debug) {
3808                    Slog.v(TAG, "Found persistent preferred activity:");
3809                    if (ai != null) {
3810                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3811                    } else {
3812                        Slog.v(TAG, "  null");
3813                    }
3814                }
3815                if (ai == null) {
3816                    // This previously registered persistent preferred activity
3817                    // component is no longer known. Ignore it and do NOT remove it.
3818                    continue;
3819                }
3820                for (int j=0; j<N; j++) {
3821                    final ResolveInfo ri = query.get(j);
3822                    if (!ri.activityInfo.applicationInfo.packageName
3823                            .equals(ai.applicationInfo.packageName)) {
3824                        continue;
3825                    }
3826                    if (!ri.activityInfo.name.equals(ai.name)) {
3827                        continue;
3828                    }
3829                    //  Found a persistent preference that can handle the intent.
3830                    if (DEBUG_PREFERRED || debug) {
3831                        Slog.v(TAG, "Returning persistent preferred activity: " +
3832                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3833                    }
3834                    return ri;
3835                }
3836            }
3837        }
3838        return null;
3839    }
3840
3841    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
3842            List<ResolveInfo> query, int priority, boolean always,
3843            boolean removeMatches, boolean debug, int userId) {
3844        if (!sUserManager.exists(userId)) return null;
3845        // writer
3846        synchronized (mPackages) {
3847            if (intent.getSelector() != null) {
3848                intent = intent.getSelector();
3849            }
3850            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3851
3852            // Try to find a matching persistent preferred activity.
3853            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
3854                    debug, userId);
3855
3856            // If a persistent preferred activity matched, use it.
3857            if (pri != null) {
3858                return pri;
3859            }
3860
3861            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
3862            // Get the list of preferred activities that handle the intent
3863            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
3864            List<PreferredActivity> prefs = pir != null
3865                    ? pir.queryIntent(intent, resolvedType,
3866                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3867                    : null;
3868            if (prefs != null && prefs.size() > 0) {
3869                boolean changed = false;
3870                try {
3871                    // First figure out how good the original match set is.
3872                    // We will only allow preferred activities that came
3873                    // from the same match quality.
3874                    int match = 0;
3875
3876                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
3877
3878                    final int N = query.size();
3879                    for (int j=0; j<N; j++) {
3880                        final ResolveInfo ri = query.get(j);
3881                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
3882                                + ": 0x" + Integer.toHexString(match));
3883                        if (ri.match > match) {
3884                            match = ri.match;
3885                        }
3886                    }
3887
3888                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
3889                            + Integer.toHexString(match));
3890
3891                    match &= IntentFilter.MATCH_CATEGORY_MASK;
3892                    final int M = prefs.size();
3893                    for (int i=0; i<M; i++) {
3894                        final PreferredActivity pa = prefs.get(i);
3895                        if (DEBUG_PREFERRED || debug) {
3896                            Slog.v(TAG, "Checking PreferredActivity ds="
3897                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
3898                                    + "\n  component=" + pa.mPref.mComponent);
3899                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3900                        }
3901                        if (pa.mPref.mMatch != match) {
3902                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
3903                                    + Integer.toHexString(pa.mPref.mMatch));
3904                            continue;
3905                        }
3906                        // If it's not an "always" type preferred activity and that's what we're
3907                        // looking for, skip it.
3908                        if (always && !pa.mPref.mAlways) {
3909                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
3910                            continue;
3911                        }
3912                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
3913                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3914                        if (DEBUG_PREFERRED || debug) {
3915                            Slog.v(TAG, "Found preferred activity:");
3916                            if (ai != null) {
3917                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3918                            } else {
3919                                Slog.v(TAG, "  null");
3920                            }
3921                        }
3922                        if (ai == null) {
3923                            // This previously registered preferred activity
3924                            // component is no longer known.  Most likely an update
3925                            // to the app was installed and in the new version this
3926                            // component no longer exists.  Clean it up by removing
3927                            // it from the preferred activities list, and skip it.
3928                            Slog.w(TAG, "Removing dangling preferred activity: "
3929                                    + pa.mPref.mComponent);
3930                            pir.removeFilter(pa);
3931                            changed = true;
3932                            continue;
3933                        }
3934                        for (int j=0; j<N; j++) {
3935                            final ResolveInfo ri = query.get(j);
3936                            if (!ri.activityInfo.applicationInfo.packageName
3937                                    .equals(ai.applicationInfo.packageName)) {
3938                                continue;
3939                            }
3940                            if (!ri.activityInfo.name.equals(ai.name)) {
3941                                continue;
3942                            }
3943
3944                            if (removeMatches) {
3945                                pir.removeFilter(pa);
3946                                changed = true;
3947                                if (DEBUG_PREFERRED) {
3948                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
3949                                }
3950                                break;
3951                            }
3952
3953                            // Okay we found a previously set preferred or last chosen app.
3954                            // If the result set is different from when this
3955                            // was created, we need to clear it and re-ask the
3956                            // user their preference, if we're looking for an "always" type entry.
3957                            if (always && !pa.mPref.sameSet(query)) {
3958                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
3959                                        + intent + " type " + resolvedType);
3960                                if (DEBUG_PREFERRED) {
3961                                    Slog.v(TAG, "Removing preferred activity since set changed "
3962                                            + pa.mPref.mComponent);
3963                                }
3964                                pir.removeFilter(pa);
3965                                // Re-add the filter as a "last chosen" entry (!always)
3966                                PreferredActivity lastChosen = new PreferredActivity(
3967                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
3968                                pir.addFilter(lastChosen);
3969                                changed = true;
3970                                return null;
3971                            }
3972
3973                            // Yay! Either the set matched or we're looking for the last chosen
3974                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
3975                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3976                            return ri;
3977                        }
3978                    }
3979                } finally {
3980                    if (changed) {
3981                        if (DEBUG_PREFERRED) {
3982                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
3983                        }
3984                        scheduleWritePackageRestrictionsLocked(userId);
3985                    }
3986                }
3987            }
3988        }
3989        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
3990        return null;
3991    }
3992
3993    /*
3994     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
3995     */
3996    @Override
3997    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
3998            int targetUserId) {
3999        mContext.enforceCallingOrSelfPermission(
4000                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4001        List<CrossProfileIntentFilter> matches =
4002                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4003        if (matches != null) {
4004            int size = matches.size();
4005            for (int i = 0; i < size; i++) {
4006                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4007            }
4008        }
4009        return false;
4010    }
4011
4012    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4013            String resolvedType, int userId) {
4014        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4015        if (resolver != null) {
4016            return resolver.queryIntent(intent, resolvedType, false, userId);
4017        }
4018        return null;
4019    }
4020
4021    @Override
4022    public List<ResolveInfo> queryIntentActivities(Intent intent,
4023            String resolvedType, int flags, int userId) {
4024        if (!sUserManager.exists(userId)) return Collections.emptyList();
4025        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4026        ComponentName comp = intent.getComponent();
4027        if (comp == null) {
4028            if (intent.getSelector() != null) {
4029                intent = intent.getSelector();
4030                comp = intent.getComponent();
4031            }
4032        }
4033
4034        if (comp != null) {
4035            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4036            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4037            if (ai != null) {
4038                final ResolveInfo ri = new ResolveInfo();
4039                ri.activityInfo = ai;
4040                list.add(ri);
4041            }
4042            return list;
4043        }
4044
4045        // reader
4046        synchronized (mPackages) {
4047            final String pkgName = intent.getPackage();
4048            if (pkgName == null) {
4049                List<CrossProfileIntentFilter> matchingFilters =
4050                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4051                // Check for results that need to skip the current profile.
4052                ResolveInfo resolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4053                        resolvedType, flags, userId);
4054                if (resolveInfo != null && isUserEnabled(resolveInfo.targetUserId)) {
4055                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4056                    result.add(resolveInfo);
4057                    return filterIfNotPrimaryUser(result, userId);
4058                }
4059
4060                // Check for results in the current profile.
4061                List<ResolveInfo> result = mActivities.queryIntent(
4062                        intent, resolvedType, flags, userId);
4063
4064                // Check for cross profile results.
4065                resolveInfo = queryCrossProfileIntents(
4066                        matchingFilters, intent, resolvedType, flags, userId);
4067                if (resolveInfo != null && isUserEnabled(resolveInfo.targetUserId)) {
4068                    result.add(resolveInfo);
4069                    Collections.sort(result, mResolvePrioritySorter);
4070                }
4071                result = filterIfNotPrimaryUser(result, userId);
4072                if (result.size() > 1 && hasWebURI(intent)) {
4073                    return filterCandidatesWithDomainPreferedActivitiesLPr(flags, result);
4074                }
4075                return result;
4076            }
4077            final PackageParser.Package pkg = mPackages.get(pkgName);
4078            if (pkg != null) {
4079                return filterIfNotPrimaryUser(
4080                        mActivities.queryIntentForPackage(
4081                                intent, resolvedType, flags, pkg.activities, userId),
4082                        userId);
4083            }
4084            return new ArrayList<ResolveInfo>();
4085        }
4086    }
4087
4088    private boolean isUserEnabled(int userId) {
4089        long callingId = Binder.clearCallingIdentity();
4090        try {
4091            UserInfo userInfo = sUserManager.getUserInfo(userId);
4092            return userInfo != null && userInfo.isEnabled();
4093        } finally {
4094            Binder.restoreCallingIdentity(callingId);
4095        }
4096    }
4097
4098    /**
4099     * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
4100     *
4101     * @return filtered list
4102     */
4103    private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
4104        if (userId == UserHandle.USER_OWNER) {
4105            return resolveInfos;
4106        }
4107        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4108            ResolveInfo info = resolveInfos.get(i);
4109            if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
4110                resolveInfos.remove(i);
4111            }
4112        }
4113        return resolveInfos;
4114    }
4115
4116    private static boolean hasWebURI(Intent intent) {
4117        if (intent.getData() == null) {
4118            return false;
4119        }
4120        final String scheme = intent.getScheme();
4121        if (TextUtils.isEmpty(scheme)) {
4122            return false;
4123        }
4124        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4125    }
4126
4127    private List<ResolveInfo> filterCandidatesWithDomainPreferedActivitiesLPr(
4128            int flags, List<ResolveInfo> candidates) {
4129        if (DEBUG_PREFERRED) {
4130            Slog.v("TAG", "Filtering results with prefered activities. Candidates count: " +
4131                    candidates.size());
4132        }
4133
4134        final int userId = UserHandle.getCallingUserId();
4135        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4136        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4137        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4138        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4139
4140        synchronized (mPackages) {
4141            final int count = candidates.size();
4142            // First, try to use the domain prefered App. Partition the candidates into four lists:
4143            // one for the final results, one for the "do not use ever", one for "undefined status"
4144            // and finally one for "Browser App type".
4145            for (int n=0; n<count; n++) {
4146                ResolveInfo info = candidates.get(n);
4147                String packageName = info.activityInfo.packageName;
4148                PackageSetting ps = mSettings.mPackages.get(packageName);
4149                if (ps != null) {
4150                    // Add to the special match all list (Browser use case)
4151                    if (info.handleAllWebDataURI) {
4152                        matchAllList.add(info);
4153                        continue;
4154                    }
4155                    // Try to get the status from User settings first
4156                    int status = getDomainVerificationStatusLPr(ps, userId);
4157                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4158                        result.add(info);
4159                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4160                        neverList.add(info);
4161                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4162                        undefinedList.add(info);
4163                    }
4164                }
4165            }
4166            // Add all undefined Apps as we want them to appear in the Disambiguation dialog.
4167            result.addAll(undefinedList);
4168            // If there is nothing selected, add all candidates and remove the ones that the User
4169            // has explicitely put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state and
4170            // also remove Browser Apps ones.
4171            // If there is still none after this pass, add all Browser Apps and
4172            // let the User decide with the Disambiguation dialog if there are several ones.
4173            if (result.size() == 0) {
4174                result.addAll(candidates);
4175            }
4176            result.removeAll(neverList);
4177            result.removeAll(matchAllList);
4178            if (result.size() == 0) {
4179                if ((flags & MATCH_ALL) != 0) {
4180                    result.addAll(matchAllList);
4181                } else {
4182                    // Try to add the Default Browser if we can
4183                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(
4184                            UserHandle.myUserId());
4185                    if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
4186                        boolean defaultBrowserFound = false;
4187                        final int browserCount = matchAllList.size();
4188                        for (int n=0; n<browserCount; n++) {
4189                            ResolveInfo browser = matchAllList.get(n);
4190                            if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) {
4191                                result.add(browser);
4192                                defaultBrowserFound = true;
4193                                break;
4194                            }
4195                        }
4196                        if (!defaultBrowserFound) {
4197                            result.addAll(matchAllList);
4198                        }
4199                    } else {
4200                        result.addAll(matchAllList);
4201                    }
4202                }
4203            }
4204        }
4205        if (DEBUG_PREFERRED) {
4206            Slog.v("TAG", "Filtered results with prefered activities. New candidates count: " +
4207                    result.size());
4208        }
4209        return result;
4210    }
4211
4212    private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4213        int status = ps.getDomainVerificationStatusForUser(userId);
4214        // if none available, get the master status
4215        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4216            if (ps.getIntentFilterVerificationInfo() != null) {
4217                status = ps.getIntentFilterVerificationInfo().getStatus();
4218            }
4219        }
4220        return status;
4221    }
4222
4223    private ResolveInfo querySkipCurrentProfileIntents(
4224            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4225            int flags, int sourceUserId) {
4226        if (matchingFilters != null) {
4227            int size = matchingFilters.size();
4228            for (int i = 0; i < size; i ++) {
4229                CrossProfileIntentFilter filter = matchingFilters.get(i);
4230                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4231                    // Checking if there are activities in the target user that can handle the
4232                    // intent.
4233                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4234                            flags, sourceUserId);
4235                    if (resolveInfo != null) {
4236                        return resolveInfo;
4237                    }
4238                }
4239            }
4240        }
4241        return null;
4242    }
4243
4244    // Return matching ResolveInfo if any for skip current profile intent filters.
4245    private ResolveInfo queryCrossProfileIntents(
4246            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4247            int flags, int sourceUserId) {
4248        if (matchingFilters != null) {
4249            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4250            // match the same intent. For performance reasons, it is better not to
4251            // run queryIntent twice for the same userId
4252            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4253            int size = matchingFilters.size();
4254            for (int i = 0; i < size; i++) {
4255                CrossProfileIntentFilter filter = matchingFilters.get(i);
4256                int targetUserId = filter.getTargetUserId();
4257                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4258                        && !alreadyTriedUserIds.get(targetUserId)) {
4259                    // Checking if there are activities in the target user that can handle the
4260                    // intent.
4261                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4262                            flags, sourceUserId);
4263                    if (resolveInfo != null) return resolveInfo;
4264                    alreadyTriedUserIds.put(targetUserId, true);
4265                }
4266            }
4267        }
4268        return null;
4269    }
4270
4271    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
4272            String resolvedType, int flags, int sourceUserId) {
4273        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4274                resolvedType, flags, filter.getTargetUserId());
4275        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
4276            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
4277        }
4278        return null;
4279    }
4280
4281    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
4282            int sourceUserId, int targetUserId) {
4283        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4284        String className;
4285        if (targetUserId == UserHandle.USER_OWNER) {
4286            className = FORWARD_INTENT_TO_USER_OWNER;
4287        } else {
4288            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4289        }
4290        ComponentName forwardingActivityComponentName = new ComponentName(
4291                mAndroidApplication.packageName, className);
4292        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
4293                sourceUserId);
4294        if (targetUserId == UserHandle.USER_OWNER) {
4295            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
4296            forwardingResolveInfo.noResourceId = true;
4297        }
4298        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
4299        forwardingResolveInfo.priority = 0;
4300        forwardingResolveInfo.preferredOrder = 0;
4301        forwardingResolveInfo.match = 0;
4302        forwardingResolveInfo.isDefault = true;
4303        forwardingResolveInfo.filter = filter;
4304        forwardingResolveInfo.targetUserId = targetUserId;
4305        return forwardingResolveInfo;
4306    }
4307
4308    @Override
4309    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
4310            Intent[] specifics, String[] specificTypes, Intent intent,
4311            String resolvedType, int flags, int userId) {
4312        if (!sUserManager.exists(userId)) return Collections.emptyList();
4313        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
4314                false, "query intent activity options");
4315        final String resultsAction = intent.getAction();
4316
4317        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
4318                | PackageManager.GET_RESOLVED_FILTER, userId);
4319
4320        if (DEBUG_INTENT_MATCHING) {
4321            Log.v(TAG, "Query " + intent + ": " + results);
4322        }
4323
4324        int specificsPos = 0;
4325        int N;
4326
4327        // todo: note that the algorithm used here is O(N^2).  This
4328        // isn't a problem in our current environment, but if we start running
4329        // into situations where we have more than 5 or 10 matches then this
4330        // should probably be changed to something smarter...
4331
4332        // First we go through and resolve each of the specific items
4333        // that were supplied, taking care of removing any corresponding
4334        // duplicate items in the generic resolve list.
4335        if (specifics != null) {
4336            for (int i=0; i<specifics.length; i++) {
4337                final Intent sintent = specifics[i];
4338                if (sintent == null) {
4339                    continue;
4340                }
4341
4342                if (DEBUG_INTENT_MATCHING) {
4343                    Log.v(TAG, "Specific #" + i + ": " + sintent);
4344                }
4345
4346                String action = sintent.getAction();
4347                if (resultsAction != null && resultsAction.equals(action)) {
4348                    // If this action was explicitly requested, then don't
4349                    // remove things that have it.
4350                    action = null;
4351                }
4352
4353                ResolveInfo ri = null;
4354                ActivityInfo ai = null;
4355
4356                ComponentName comp = sintent.getComponent();
4357                if (comp == null) {
4358                    ri = resolveIntent(
4359                        sintent,
4360                        specificTypes != null ? specificTypes[i] : null,
4361                            flags, userId);
4362                    if (ri == null) {
4363                        continue;
4364                    }
4365                    if (ri == mResolveInfo) {
4366                        // ACK!  Must do something better with this.
4367                    }
4368                    ai = ri.activityInfo;
4369                    comp = new ComponentName(ai.applicationInfo.packageName,
4370                            ai.name);
4371                } else {
4372                    ai = getActivityInfo(comp, flags, userId);
4373                    if (ai == null) {
4374                        continue;
4375                    }
4376                }
4377
4378                // Look for any generic query activities that are duplicates
4379                // of this specific one, and remove them from the results.
4380                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
4381                N = results.size();
4382                int j;
4383                for (j=specificsPos; j<N; j++) {
4384                    ResolveInfo sri = results.get(j);
4385                    if ((sri.activityInfo.name.equals(comp.getClassName())
4386                            && sri.activityInfo.applicationInfo.packageName.equals(
4387                                    comp.getPackageName()))
4388                        || (action != null && sri.filter.matchAction(action))) {
4389                        results.remove(j);
4390                        if (DEBUG_INTENT_MATCHING) Log.v(
4391                            TAG, "Removing duplicate item from " + j
4392                            + " due to specific " + specificsPos);
4393                        if (ri == null) {
4394                            ri = sri;
4395                        }
4396                        j--;
4397                        N--;
4398                    }
4399                }
4400
4401                // Add this specific item to its proper place.
4402                if (ri == null) {
4403                    ri = new ResolveInfo();
4404                    ri.activityInfo = ai;
4405                }
4406                results.add(specificsPos, ri);
4407                ri.specificIndex = i;
4408                specificsPos++;
4409            }
4410        }
4411
4412        // Now we go through the remaining generic results and remove any
4413        // duplicate actions that are found here.
4414        N = results.size();
4415        for (int i=specificsPos; i<N-1; i++) {
4416            final ResolveInfo rii = results.get(i);
4417            if (rii.filter == null) {
4418                continue;
4419            }
4420
4421            // Iterate over all of the actions of this result's intent
4422            // filter...  typically this should be just one.
4423            final Iterator<String> it = rii.filter.actionsIterator();
4424            if (it == null) {
4425                continue;
4426            }
4427            while (it.hasNext()) {
4428                final String action = it.next();
4429                if (resultsAction != null && resultsAction.equals(action)) {
4430                    // If this action was explicitly requested, then don't
4431                    // remove things that have it.
4432                    continue;
4433                }
4434                for (int j=i+1; j<N; j++) {
4435                    final ResolveInfo rij = results.get(j);
4436                    if (rij.filter != null && rij.filter.hasAction(action)) {
4437                        results.remove(j);
4438                        if (DEBUG_INTENT_MATCHING) Log.v(
4439                            TAG, "Removing duplicate item from " + j
4440                            + " due to action " + action + " at " + i);
4441                        j--;
4442                        N--;
4443                    }
4444                }
4445            }
4446
4447            // If the caller didn't request filter information, drop it now
4448            // so we don't have to marshall/unmarshall it.
4449            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4450                rii.filter = null;
4451            }
4452        }
4453
4454        // Filter out the caller activity if so requested.
4455        if (caller != null) {
4456            N = results.size();
4457            for (int i=0; i<N; i++) {
4458                ActivityInfo ainfo = results.get(i).activityInfo;
4459                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
4460                        && caller.getClassName().equals(ainfo.name)) {
4461                    results.remove(i);
4462                    break;
4463                }
4464            }
4465        }
4466
4467        // If the caller didn't request filter information,
4468        // drop them now so we don't have to
4469        // marshall/unmarshall it.
4470        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4471            N = results.size();
4472            for (int i=0; i<N; i++) {
4473                results.get(i).filter = null;
4474            }
4475        }
4476
4477        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
4478        return results;
4479    }
4480
4481    @Override
4482    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
4483            int userId) {
4484        if (!sUserManager.exists(userId)) return Collections.emptyList();
4485        ComponentName comp = intent.getComponent();
4486        if (comp == null) {
4487            if (intent.getSelector() != null) {
4488                intent = intent.getSelector();
4489                comp = intent.getComponent();
4490            }
4491        }
4492        if (comp != null) {
4493            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4494            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
4495            if (ai != null) {
4496                ResolveInfo ri = new ResolveInfo();
4497                ri.activityInfo = ai;
4498                list.add(ri);
4499            }
4500            return list;
4501        }
4502
4503        // reader
4504        synchronized (mPackages) {
4505            String pkgName = intent.getPackage();
4506            if (pkgName == null) {
4507                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
4508            }
4509            final PackageParser.Package pkg = mPackages.get(pkgName);
4510            if (pkg != null) {
4511                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
4512                        userId);
4513            }
4514            return null;
4515        }
4516    }
4517
4518    @Override
4519    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
4520        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
4521        if (!sUserManager.exists(userId)) return null;
4522        if (query != null) {
4523            if (query.size() >= 1) {
4524                // If there is more than one service with the same priority,
4525                // just arbitrarily pick the first one.
4526                return query.get(0);
4527            }
4528        }
4529        return null;
4530    }
4531
4532    @Override
4533    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
4534            int userId) {
4535        if (!sUserManager.exists(userId)) return Collections.emptyList();
4536        ComponentName comp = intent.getComponent();
4537        if (comp == null) {
4538            if (intent.getSelector() != null) {
4539                intent = intent.getSelector();
4540                comp = intent.getComponent();
4541            }
4542        }
4543        if (comp != null) {
4544            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4545            final ServiceInfo si = getServiceInfo(comp, flags, userId);
4546            if (si != null) {
4547                final ResolveInfo ri = new ResolveInfo();
4548                ri.serviceInfo = si;
4549                list.add(ri);
4550            }
4551            return list;
4552        }
4553
4554        // reader
4555        synchronized (mPackages) {
4556            String pkgName = intent.getPackage();
4557            if (pkgName == null) {
4558                return mServices.queryIntent(intent, resolvedType, flags, userId);
4559            }
4560            final PackageParser.Package pkg = mPackages.get(pkgName);
4561            if (pkg != null) {
4562                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
4563                        userId);
4564            }
4565            return null;
4566        }
4567    }
4568
4569    @Override
4570    public List<ResolveInfo> queryIntentContentProviders(
4571            Intent intent, String resolvedType, int flags, int userId) {
4572        if (!sUserManager.exists(userId)) return Collections.emptyList();
4573        ComponentName comp = intent.getComponent();
4574        if (comp == null) {
4575            if (intent.getSelector() != null) {
4576                intent = intent.getSelector();
4577                comp = intent.getComponent();
4578            }
4579        }
4580        if (comp != null) {
4581            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4582            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
4583            if (pi != null) {
4584                final ResolveInfo ri = new ResolveInfo();
4585                ri.providerInfo = pi;
4586                list.add(ri);
4587            }
4588            return list;
4589        }
4590
4591        // reader
4592        synchronized (mPackages) {
4593            String pkgName = intent.getPackage();
4594            if (pkgName == null) {
4595                return mProviders.queryIntent(intent, resolvedType, flags, userId);
4596            }
4597            final PackageParser.Package pkg = mPackages.get(pkgName);
4598            if (pkg != null) {
4599                return mProviders.queryIntentForPackage(
4600                        intent, resolvedType, flags, pkg.providers, userId);
4601            }
4602            return null;
4603        }
4604    }
4605
4606    @Override
4607    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
4608        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4609
4610        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
4611
4612        // writer
4613        synchronized (mPackages) {
4614            ArrayList<PackageInfo> list;
4615            if (listUninstalled) {
4616                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
4617                for (PackageSetting ps : mSettings.mPackages.values()) {
4618                    PackageInfo pi;
4619                    if (ps.pkg != null) {
4620                        pi = generatePackageInfo(ps.pkg, flags, userId);
4621                    } else {
4622                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
4623                    }
4624                    if (pi != null) {
4625                        list.add(pi);
4626                    }
4627                }
4628            } else {
4629                list = new ArrayList<PackageInfo>(mPackages.size());
4630                for (PackageParser.Package p : mPackages.values()) {
4631                    PackageInfo pi = generatePackageInfo(p, flags, userId);
4632                    if (pi != null) {
4633                        list.add(pi);
4634                    }
4635                }
4636            }
4637
4638            return new ParceledListSlice<PackageInfo>(list);
4639        }
4640    }
4641
4642    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
4643            String[] permissions, boolean[] tmp, int flags, int userId) {
4644        int numMatch = 0;
4645        final PermissionsState permissionsState = ps.getPermissionsState();
4646        for (int i=0; i<permissions.length; i++) {
4647            final String permission = permissions[i];
4648            if (permissionsState.hasPermission(permission, userId)) {
4649                tmp[i] = true;
4650                numMatch++;
4651            } else {
4652                tmp[i] = false;
4653            }
4654        }
4655        if (numMatch == 0) {
4656            return;
4657        }
4658        PackageInfo pi;
4659        if (ps.pkg != null) {
4660            pi = generatePackageInfo(ps.pkg, flags, userId);
4661        } else {
4662            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
4663        }
4664        // The above might return null in cases of uninstalled apps or install-state
4665        // skew across users/profiles.
4666        if (pi != null) {
4667            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
4668                if (numMatch == permissions.length) {
4669                    pi.requestedPermissions = permissions;
4670                } else {
4671                    pi.requestedPermissions = new String[numMatch];
4672                    numMatch = 0;
4673                    for (int i=0; i<permissions.length; i++) {
4674                        if (tmp[i]) {
4675                            pi.requestedPermissions[numMatch] = permissions[i];
4676                            numMatch++;
4677                        }
4678                    }
4679                }
4680            }
4681            list.add(pi);
4682        }
4683    }
4684
4685    @Override
4686    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
4687            String[] permissions, int flags, int userId) {
4688        if (!sUserManager.exists(userId)) return null;
4689        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4690
4691        // writer
4692        synchronized (mPackages) {
4693            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
4694            boolean[] tmpBools = new boolean[permissions.length];
4695            if (listUninstalled) {
4696                for (PackageSetting ps : mSettings.mPackages.values()) {
4697                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
4698                }
4699            } else {
4700                for (PackageParser.Package pkg : mPackages.values()) {
4701                    PackageSetting ps = (PackageSetting)pkg.mExtras;
4702                    if (ps != null) {
4703                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
4704                                userId);
4705                    }
4706                }
4707            }
4708
4709            return new ParceledListSlice<PackageInfo>(list);
4710        }
4711    }
4712
4713    @Override
4714    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
4715        if (!sUserManager.exists(userId)) return null;
4716        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4717
4718        // writer
4719        synchronized (mPackages) {
4720            ArrayList<ApplicationInfo> list;
4721            if (listUninstalled) {
4722                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
4723                for (PackageSetting ps : mSettings.mPackages.values()) {
4724                    ApplicationInfo ai;
4725                    if (ps.pkg != null) {
4726                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4727                                ps.readUserState(userId), userId);
4728                    } else {
4729                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
4730                    }
4731                    if (ai != null) {
4732                        list.add(ai);
4733                    }
4734                }
4735            } else {
4736                list = new ArrayList<ApplicationInfo>(mPackages.size());
4737                for (PackageParser.Package p : mPackages.values()) {
4738                    if (p.mExtras != null) {
4739                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
4740                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
4741                        if (ai != null) {
4742                            list.add(ai);
4743                        }
4744                    }
4745                }
4746            }
4747
4748            return new ParceledListSlice<ApplicationInfo>(list);
4749        }
4750    }
4751
4752    public List<ApplicationInfo> getPersistentApplications(int flags) {
4753        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
4754
4755        // reader
4756        synchronized (mPackages) {
4757            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
4758            final int userId = UserHandle.getCallingUserId();
4759            while (i.hasNext()) {
4760                final PackageParser.Package p = i.next();
4761                if (p.applicationInfo != null
4762                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
4763                        && (!mSafeMode || isSystemApp(p))) {
4764                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
4765                    if (ps != null) {
4766                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
4767                                ps.readUserState(userId), userId);
4768                        if (ai != null) {
4769                            finalList.add(ai);
4770                        }
4771                    }
4772                }
4773            }
4774        }
4775
4776        return finalList;
4777    }
4778
4779    @Override
4780    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
4781        if (!sUserManager.exists(userId)) return null;
4782        // reader
4783        synchronized (mPackages) {
4784            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
4785            PackageSetting ps = provider != null
4786                    ? mSettings.mPackages.get(provider.owner.packageName)
4787                    : null;
4788            return ps != null
4789                    && mSettings.isEnabledLPr(provider.info, flags, userId)
4790                    && (!mSafeMode || (provider.info.applicationInfo.flags
4791                            &ApplicationInfo.FLAG_SYSTEM) != 0)
4792                    ? PackageParser.generateProviderInfo(provider, flags,
4793                            ps.readUserState(userId), userId)
4794                    : null;
4795        }
4796    }
4797
4798    /**
4799     * @deprecated
4800     */
4801    @Deprecated
4802    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
4803        // reader
4804        synchronized (mPackages) {
4805            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
4806                    .entrySet().iterator();
4807            final int userId = UserHandle.getCallingUserId();
4808            while (i.hasNext()) {
4809                Map.Entry<String, PackageParser.Provider> entry = i.next();
4810                PackageParser.Provider p = entry.getValue();
4811                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
4812
4813                if (ps != null && p.syncable
4814                        && (!mSafeMode || (p.info.applicationInfo.flags
4815                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
4816                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
4817                            ps.readUserState(userId), userId);
4818                    if (info != null) {
4819                        outNames.add(entry.getKey());
4820                        outInfo.add(info);
4821                    }
4822                }
4823            }
4824        }
4825    }
4826
4827    @Override
4828    public List<ProviderInfo> queryContentProviders(String processName,
4829            int uid, int flags) {
4830        ArrayList<ProviderInfo> finalList = null;
4831        // reader
4832        synchronized (mPackages) {
4833            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
4834            final int userId = processName != null ?
4835                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
4836            while (i.hasNext()) {
4837                final PackageParser.Provider p = i.next();
4838                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
4839                if (ps != null && p.info.authority != null
4840                        && (processName == null
4841                                || (p.info.processName.equals(processName)
4842                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
4843                        && mSettings.isEnabledLPr(p.info, flags, userId)
4844                        && (!mSafeMode
4845                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
4846                    if (finalList == null) {
4847                        finalList = new ArrayList<ProviderInfo>(3);
4848                    }
4849                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
4850                            ps.readUserState(userId), userId);
4851                    if (info != null) {
4852                        finalList.add(info);
4853                    }
4854                }
4855            }
4856        }
4857
4858        if (finalList != null) {
4859            Collections.sort(finalList, mProviderInitOrderSorter);
4860        }
4861
4862        return finalList;
4863    }
4864
4865    @Override
4866    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
4867            int flags) {
4868        // reader
4869        synchronized (mPackages) {
4870            final PackageParser.Instrumentation i = mInstrumentation.get(name);
4871            return PackageParser.generateInstrumentationInfo(i, flags);
4872        }
4873    }
4874
4875    @Override
4876    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
4877            int flags) {
4878        ArrayList<InstrumentationInfo> finalList =
4879            new ArrayList<InstrumentationInfo>();
4880
4881        // reader
4882        synchronized (mPackages) {
4883            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
4884            while (i.hasNext()) {
4885                final PackageParser.Instrumentation p = i.next();
4886                if (targetPackage == null
4887                        || targetPackage.equals(p.info.targetPackage)) {
4888                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
4889                            flags);
4890                    if (ii != null) {
4891                        finalList.add(ii);
4892                    }
4893                }
4894            }
4895        }
4896
4897        return finalList;
4898    }
4899
4900    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
4901        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
4902        if (overlays == null) {
4903            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
4904            return;
4905        }
4906        for (PackageParser.Package opkg : overlays.values()) {
4907            // Not much to do if idmap fails: we already logged the error
4908            // and we certainly don't want to abort installation of pkg simply
4909            // because an overlay didn't fit properly. For these reasons,
4910            // ignore the return value of createIdmapForPackagePairLI.
4911            createIdmapForPackagePairLI(pkg, opkg);
4912        }
4913    }
4914
4915    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
4916            PackageParser.Package opkg) {
4917        if (!opkg.mTrustedOverlay) {
4918            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
4919                    opkg.baseCodePath + ": overlay not trusted");
4920            return false;
4921        }
4922        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
4923        if (overlaySet == null) {
4924            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
4925                    opkg.baseCodePath + " but target package has no known overlays");
4926            return false;
4927        }
4928        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4929        // TODO: generate idmap for split APKs
4930        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
4931            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
4932                    + opkg.baseCodePath);
4933            return false;
4934        }
4935        PackageParser.Package[] overlayArray =
4936            overlaySet.values().toArray(new PackageParser.Package[0]);
4937        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
4938            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
4939                return p1.mOverlayPriority - p2.mOverlayPriority;
4940            }
4941        };
4942        Arrays.sort(overlayArray, cmp);
4943
4944        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
4945        int i = 0;
4946        for (PackageParser.Package p : overlayArray) {
4947            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
4948        }
4949        return true;
4950    }
4951
4952    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
4953        final File[] files = dir.listFiles();
4954        if (ArrayUtils.isEmpty(files)) {
4955            Log.d(TAG, "No files in app dir " + dir);
4956            return;
4957        }
4958
4959        if (DEBUG_PACKAGE_SCANNING) {
4960            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
4961                    + " flags=0x" + Integer.toHexString(parseFlags));
4962        }
4963
4964        for (File file : files) {
4965            final boolean isPackage = (isApkFile(file) || file.isDirectory())
4966                    && !PackageInstallerService.isStageName(file.getName());
4967            if (!isPackage) {
4968                // Ignore entries which are not packages
4969                continue;
4970            }
4971            try {
4972                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
4973                        scanFlags, currentTime, null);
4974            } catch (PackageManagerException e) {
4975                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
4976
4977                // Delete invalid userdata apps
4978                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
4979                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
4980                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
4981                    if (file.isDirectory()) {
4982                        mInstaller.rmPackageDir(file.getAbsolutePath());
4983                    } else {
4984                        file.delete();
4985                    }
4986                }
4987            }
4988        }
4989    }
4990
4991    private static File getSettingsProblemFile() {
4992        File dataDir = Environment.getDataDirectory();
4993        File systemDir = new File(dataDir, "system");
4994        File fname = new File(systemDir, "uiderrors.txt");
4995        return fname;
4996    }
4997
4998    static void reportSettingsProblem(int priority, String msg) {
4999        logCriticalInfo(priority, msg);
5000    }
5001
5002    static void logCriticalInfo(int priority, String msg) {
5003        Slog.println(priority, TAG, msg);
5004        EventLogTags.writePmCriticalInfo(msg);
5005        try {
5006            File fname = getSettingsProblemFile();
5007            FileOutputStream out = new FileOutputStream(fname, true);
5008            PrintWriter pw = new FastPrintWriter(out);
5009            SimpleDateFormat formatter = new SimpleDateFormat();
5010            String dateString = formatter.format(new Date(System.currentTimeMillis()));
5011            pw.println(dateString + ": " + msg);
5012            pw.close();
5013            FileUtils.setPermissions(
5014                    fname.toString(),
5015                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5016                    -1, -1);
5017        } catch (java.io.IOException e) {
5018        }
5019    }
5020
5021    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5022            PackageParser.Package pkg, File srcFile, int parseFlags)
5023            throws PackageManagerException {
5024        if (ps != null
5025                && ps.codePath.equals(srcFile)
5026                && ps.timeStamp == srcFile.lastModified()
5027                && !isCompatSignatureUpdateNeeded(pkg)
5028                && !isRecoverSignatureUpdateNeeded(pkg)) {
5029            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5030            if (ps.signatures.mSignatures != null
5031                    && ps.signatures.mSignatures.length != 0
5032                    && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) {
5033                // Optimization: reuse the existing cached certificates
5034                // if the package appears to be unchanged.
5035                pkg.mSignatures = ps.signatures.mSignatures;
5036                KeySetManagerService ksms = mSettings.mKeySetManagerService;
5037                synchronized (mPackages) {
5038                    pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
5039                }
5040                return;
5041            }
5042
5043            Slog.w(TAG, "PackageSetting for " + ps.name
5044                    + " is missing signatures.  Collecting certs again to recover them.");
5045        } else {
5046            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
5047        }
5048
5049        try {
5050            pp.collectCertificates(pkg, parseFlags);
5051            pp.collectManifestDigest(pkg);
5052        } catch (PackageParserException e) {
5053            throw PackageManagerException.from(e);
5054        }
5055    }
5056
5057    /*
5058     *  Scan a package and return the newly parsed package.
5059     *  Returns null in case of errors and the error code is stored in mLastScanError
5060     */
5061    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
5062            long currentTime, UserHandle user) throws PackageManagerException {
5063        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
5064        parseFlags |= mDefParseFlags;
5065        PackageParser pp = new PackageParser();
5066        pp.setSeparateProcesses(mSeparateProcesses);
5067        pp.setOnlyCoreApps(mOnlyCore);
5068        pp.setDisplayMetrics(mMetrics);
5069
5070        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
5071            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
5072        }
5073
5074        final PackageParser.Package pkg;
5075        try {
5076            pkg = pp.parsePackage(scanFile, parseFlags);
5077        } catch (PackageParserException e) {
5078            throw PackageManagerException.from(e);
5079        }
5080
5081        PackageSetting ps = null;
5082        PackageSetting updatedPkg;
5083        // reader
5084        synchronized (mPackages) {
5085            // Look to see if we already know about this package.
5086            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
5087            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
5088                // This package has been renamed to its original name.  Let's
5089                // use that.
5090                ps = mSettings.peekPackageLPr(oldName);
5091            }
5092            // If there was no original package, see one for the real package name.
5093            if (ps == null) {
5094                ps = mSettings.peekPackageLPr(pkg.packageName);
5095            }
5096            // Check to see if this package could be hiding/updating a system
5097            // package.  Must look for it either under the original or real
5098            // package name depending on our state.
5099            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
5100            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
5101        }
5102        boolean updatedPkgBetter = false;
5103        // First check if this is a system package that may involve an update
5104        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5105            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
5106            // it needs to drop FLAG_PRIVILEGED.
5107            if (locationIsPrivileged(scanFile)) {
5108                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5109            } else {
5110                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5111            }
5112
5113            if (ps != null && !ps.codePath.equals(scanFile)) {
5114                // The path has changed from what was last scanned...  check the
5115                // version of the new path against what we have stored to determine
5116                // what to do.
5117                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
5118                if (pkg.mVersionCode <= ps.versionCode) {
5119                    // The system package has been updated and the code path does not match
5120                    // Ignore entry. Skip it.
5121                    Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5122                            + " ignored: updated version " + ps.versionCode
5123                            + " better than this " + pkg.mVersionCode);
5124                    if (!updatedPkg.codePath.equals(scanFile)) {
5125                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5126                                + ps.name + " changing from " + updatedPkg.codePathString
5127                                + " to " + scanFile);
5128                        updatedPkg.codePath = scanFile;
5129                        updatedPkg.codePathString = scanFile.toString();
5130                        updatedPkg.resourcePath = scanFile;
5131                        updatedPkg.resourcePathString = scanFile.toString();
5132                    }
5133                    updatedPkg.pkg = pkg;
5134                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null);
5135                } else {
5136                    // The current app on the system partition is better than
5137                    // what we have updated to on the data partition; switch
5138                    // back to the system partition version.
5139                    // At this point, its safely assumed that package installation for
5140                    // apps in system partition will go through. If not there won't be a working
5141                    // version of the app
5142                    // writer
5143                    synchronized (mPackages) {
5144                        // Just remove the loaded entries from package lists.
5145                        mPackages.remove(ps.name);
5146                    }
5147
5148                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5149                            + " reverting from " + ps.codePathString
5150                            + ": new version " + pkg.mVersionCode
5151                            + " better than installed " + ps.versionCode);
5152
5153                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5154                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5155                    synchronized (mInstallLock) {
5156                        args.cleanUpResourcesLI();
5157                    }
5158                    synchronized (mPackages) {
5159                        mSettings.enableSystemPackageLPw(ps.name);
5160                    }
5161                    updatedPkgBetter = true;
5162                }
5163            }
5164        }
5165
5166        if (updatedPkg != null) {
5167            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5168            // initially
5169            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5170
5171            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5172            // flag set initially
5173            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5174                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5175            }
5176        }
5177
5178        // Verify certificates against what was last scanned
5179        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5180
5181        /*
5182         * A new system app appeared, but we already had a non-system one of the
5183         * same name installed earlier.
5184         */
5185        boolean shouldHideSystemApp = false;
5186        if (updatedPkg == null && ps != null
5187                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5188            /*
5189             * Check to make sure the signatures match first. If they don't,
5190             * wipe the installed application and its data.
5191             */
5192            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5193                    != PackageManager.SIGNATURE_MATCH) {
5194                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5195                        + " signatures don't match existing userdata copy; removing");
5196                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5197                ps = null;
5198            } else {
5199                /*
5200                 * If the newly-added system app is an older version than the
5201                 * already installed version, hide it. It will be scanned later
5202                 * and re-added like an update.
5203                 */
5204                if (pkg.mVersionCode <= ps.versionCode) {
5205                    shouldHideSystemApp = true;
5206                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5207                            + " but new version " + pkg.mVersionCode + " better than installed "
5208                            + ps.versionCode + "; hiding system");
5209                } else {
5210                    /*
5211                     * The newly found system app is a newer version that the
5212                     * one previously installed. Simply remove the
5213                     * already-installed application and replace it with our own
5214                     * while keeping the application data.
5215                     */
5216                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5217                            + " reverting from " + ps.codePathString + ": new version "
5218                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5219                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5220                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5221                    synchronized (mInstallLock) {
5222                        args.cleanUpResourcesLI();
5223                    }
5224                }
5225            }
5226        }
5227
5228        // The apk is forward locked (not public) if its code and resources
5229        // are kept in different files. (except for app in either system or
5230        // vendor path).
5231        // TODO grab this value from PackageSettings
5232        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5233            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5234                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5235            }
5236        }
5237
5238        // TODO: extend to support forward-locked splits
5239        String resourcePath = null;
5240        String baseResourcePath = null;
5241        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5242            if (ps != null && ps.resourcePathString != null) {
5243                resourcePath = ps.resourcePathString;
5244                baseResourcePath = ps.resourcePathString;
5245            } else {
5246                // Should not happen at all. Just log an error.
5247                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5248            }
5249        } else {
5250            resourcePath = pkg.codePath;
5251            baseResourcePath = pkg.baseCodePath;
5252        }
5253
5254        // Set application objects path explicitly.
5255        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
5256        pkg.applicationInfo.setCodePath(pkg.codePath);
5257        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5258        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5259        pkg.applicationInfo.setResourcePath(resourcePath);
5260        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5261        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5262
5263        // Note that we invoke the following method only if we are about to unpack an application
5264        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5265                | SCAN_UPDATE_SIGNATURE, currentTime, user);
5266
5267        /*
5268         * If the system app should be overridden by a previously installed
5269         * data, hide the system app now and let the /data/app scan pick it up
5270         * again.
5271         */
5272        if (shouldHideSystemApp) {
5273            synchronized (mPackages) {
5274                /*
5275                 * We have to grant systems permissions before we hide, because
5276                 * grantPermissions will assume the package update is trying to
5277                 * expand its permissions.
5278                 */
5279                grantPermissionsLPw(pkg, true, pkg.packageName);
5280                mSettings.disableSystemPackageLPw(pkg.packageName);
5281            }
5282        }
5283
5284        return scannedPkg;
5285    }
5286
5287    private static String fixProcessName(String defProcessName,
5288            String processName, int uid) {
5289        if (processName == null) {
5290            return defProcessName;
5291        }
5292        return processName;
5293    }
5294
5295    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
5296            throws PackageManagerException {
5297        if (pkgSetting.signatures.mSignatures != null) {
5298            // Already existing package. Make sure signatures match
5299            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
5300                    == PackageManager.SIGNATURE_MATCH;
5301            if (!match) {
5302                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
5303                        == PackageManager.SIGNATURE_MATCH;
5304            }
5305            if (!match) {
5306                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
5307                        == PackageManager.SIGNATURE_MATCH;
5308            }
5309            if (!match) {
5310                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5311                        + pkg.packageName + " signatures do not match the "
5312                        + "previously installed version; ignoring!");
5313            }
5314        }
5315
5316        // Check for shared user signatures
5317        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
5318            // Already existing package. Make sure signatures match
5319            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5320                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
5321            if (!match) {
5322                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
5323                        == PackageManager.SIGNATURE_MATCH;
5324            }
5325            if (!match) {
5326                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
5327                        == PackageManager.SIGNATURE_MATCH;
5328            }
5329            if (!match) {
5330                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
5331                        "Package " + pkg.packageName
5332                        + " has no signatures that match those in shared user "
5333                        + pkgSetting.sharedUser.name + "; ignoring!");
5334            }
5335        }
5336    }
5337
5338    /**
5339     * Enforces that only the system UID or root's UID can call a method exposed
5340     * via Binder.
5341     *
5342     * @param message used as message if SecurityException is thrown
5343     * @throws SecurityException if the caller is not system or root
5344     */
5345    private static final void enforceSystemOrRoot(String message) {
5346        final int uid = Binder.getCallingUid();
5347        if (uid != Process.SYSTEM_UID && uid != 0) {
5348            throw new SecurityException(message);
5349        }
5350    }
5351
5352    @Override
5353    public void performBootDexOpt() {
5354        enforceSystemOrRoot("Only the system can request dexopt be performed");
5355
5356        // Before everything else, see whether we need to fstrim.
5357        try {
5358            IMountService ms = PackageHelper.getMountService();
5359            if (ms != null) {
5360                final boolean isUpgrade = isUpgrade();
5361                boolean doTrim = isUpgrade;
5362                if (doTrim) {
5363                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
5364                } else {
5365                    final long interval = android.provider.Settings.Global.getLong(
5366                            mContext.getContentResolver(),
5367                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
5368                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
5369                    if (interval > 0) {
5370                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
5371                        if (timeSinceLast > interval) {
5372                            doTrim = true;
5373                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
5374                                    + "; running immediately");
5375                        }
5376                    }
5377                }
5378                if (doTrim) {
5379                    if (!isFirstBoot()) {
5380                        try {
5381                            ActivityManagerNative.getDefault().showBootMessage(
5382                                    mContext.getResources().getString(
5383                                            R.string.android_upgrading_fstrim), true);
5384                        } catch (RemoteException e) {
5385                        }
5386                    }
5387                    ms.runMaintenance();
5388                }
5389            } else {
5390                Slog.e(TAG, "Mount service unavailable!");
5391            }
5392        } catch (RemoteException e) {
5393            // Can't happen; MountService is local
5394        }
5395
5396        final ArraySet<PackageParser.Package> pkgs;
5397        synchronized (mPackages) {
5398            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
5399        }
5400
5401        if (pkgs != null) {
5402            // Sort apps by importance for dexopt ordering. Important apps are given more priority
5403            // in case the device runs out of space.
5404            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
5405            // Give priority to core apps.
5406            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5407                PackageParser.Package pkg = it.next();
5408                if (pkg.coreApp) {
5409                    if (DEBUG_DEXOPT) {
5410                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
5411                    }
5412                    sortedPkgs.add(pkg);
5413                    it.remove();
5414                }
5415            }
5416            // Give priority to system apps that listen for pre boot complete.
5417            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
5418            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
5419            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5420                PackageParser.Package pkg = it.next();
5421                if (pkgNames.contains(pkg.packageName)) {
5422                    if (DEBUG_DEXOPT) {
5423                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
5424                    }
5425                    sortedPkgs.add(pkg);
5426                    it.remove();
5427                }
5428            }
5429            // Give priority to system apps.
5430            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5431                PackageParser.Package pkg = it.next();
5432                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
5433                    if (DEBUG_DEXOPT) {
5434                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
5435                    }
5436                    sortedPkgs.add(pkg);
5437                    it.remove();
5438                }
5439            }
5440            // Give priority to updated system apps.
5441            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5442                PackageParser.Package pkg = it.next();
5443                if (pkg.isUpdatedSystemApp()) {
5444                    if (DEBUG_DEXOPT) {
5445                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
5446                    }
5447                    sortedPkgs.add(pkg);
5448                    it.remove();
5449                }
5450            }
5451            // Give priority to apps that listen for boot complete.
5452            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
5453            pkgNames = getPackageNamesForIntent(intent);
5454            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5455                PackageParser.Package pkg = it.next();
5456                if (pkgNames.contains(pkg.packageName)) {
5457                    if (DEBUG_DEXOPT) {
5458                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
5459                    }
5460                    sortedPkgs.add(pkg);
5461                    it.remove();
5462                }
5463            }
5464            // Filter out packages that aren't recently used.
5465            filterRecentlyUsedApps(pkgs);
5466            // Add all remaining apps.
5467            for (PackageParser.Package pkg : pkgs) {
5468                if (DEBUG_DEXOPT) {
5469                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
5470                }
5471                sortedPkgs.add(pkg);
5472            }
5473
5474            // If we want to be lazy, filter everything that wasn't recently used.
5475            if (mLazyDexOpt) {
5476                filterRecentlyUsedApps(sortedPkgs);
5477            }
5478
5479            int i = 0;
5480            int total = sortedPkgs.size();
5481            File dataDir = Environment.getDataDirectory();
5482            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
5483            if (lowThreshold == 0) {
5484                throw new IllegalStateException("Invalid low memory threshold");
5485            }
5486            for (PackageParser.Package pkg : sortedPkgs) {
5487                long usableSpace = dataDir.getUsableSpace();
5488                if (usableSpace < lowThreshold) {
5489                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
5490                    break;
5491                }
5492                performBootDexOpt(pkg, ++i, total);
5493            }
5494        }
5495    }
5496
5497    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
5498        // Filter out packages that aren't recently used.
5499        //
5500        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
5501        // should do a full dexopt.
5502        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
5503            int total = pkgs.size();
5504            int skipped = 0;
5505            long now = System.currentTimeMillis();
5506            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
5507                PackageParser.Package pkg = i.next();
5508                long then = pkg.mLastPackageUsageTimeInMills;
5509                if (then + mDexOptLRUThresholdInMills < now) {
5510                    if (DEBUG_DEXOPT) {
5511                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
5512                              ((then == 0) ? "never" : new Date(then)));
5513                    }
5514                    i.remove();
5515                    skipped++;
5516                }
5517            }
5518            if (DEBUG_DEXOPT) {
5519                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
5520            }
5521        }
5522    }
5523
5524    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
5525        List<ResolveInfo> ris = null;
5526        try {
5527            ris = AppGlobals.getPackageManager().queryIntentReceivers(
5528                    intent, null, 0, UserHandle.USER_OWNER);
5529        } catch (RemoteException e) {
5530        }
5531        ArraySet<String> pkgNames = new ArraySet<String>();
5532        if (ris != null) {
5533            for (ResolveInfo ri : ris) {
5534                pkgNames.add(ri.activityInfo.packageName);
5535            }
5536        }
5537        return pkgNames;
5538    }
5539
5540    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
5541        if (DEBUG_DEXOPT) {
5542            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
5543        }
5544        if (!isFirstBoot()) {
5545            try {
5546                ActivityManagerNative.getDefault().showBootMessage(
5547                        mContext.getResources().getString(R.string.android_upgrading_apk,
5548                                curr, total), true);
5549            } catch (RemoteException e) {
5550            }
5551        }
5552        PackageParser.Package p = pkg;
5553        synchronized (mInstallLock) {
5554            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
5555                    false /* force dex */, false /* defer */, true /* include dependencies */);
5556        }
5557    }
5558
5559    @Override
5560    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
5561        return performDexOpt(packageName, instructionSet, false);
5562    }
5563
5564    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
5565        boolean dexopt = mLazyDexOpt || backgroundDexopt;
5566        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
5567        if (!dexopt && !updateUsage) {
5568            // We aren't going to dexopt or update usage, so bail early.
5569            return false;
5570        }
5571        PackageParser.Package p;
5572        final String targetInstructionSet;
5573        synchronized (mPackages) {
5574            p = mPackages.get(packageName);
5575            if (p == null) {
5576                return false;
5577            }
5578            if (updateUsage) {
5579                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
5580            }
5581            mPackageUsage.write(false);
5582            if (!dexopt) {
5583                // We aren't going to dexopt, so bail early.
5584                return false;
5585            }
5586
5587            targetInstructionSet = instructionSet != null ? instructionSet :
5588                    getPrimaryInstructionSet(p.applicationInfo);
5589            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
5590                return false;
5591            }
5592        }
5593
5594        synchronized (mInstallLock) {
5595            final String[] instructionSets = new String[] { targetInstructionSet };
5596            int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
5597                    false /* forceDex */, false /* defer */, true /* inclDependencies */);
5598            return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
5599        }
5600    }
5601
5602    public ArraySet<String> getPackagesThatNeedDexOpt() {
5603        ArraySet<String> pkgs = null;
5604        synchronized (mPackages) {
5605            for (PackageParser.Package p : mPackages.values()) {
5606                if (DEBUG_DEXOPT) {
5607                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
5608                }
5609                if (!p.mDexOptPerformed.isEmpty()) {
5610                    continue;
5611                }
5612                if (pkgs == null) {
5613                    pkgs = new ArraySet<String>();
5614                }
5615                pkgs.add(p.packageName);
5616            }
5617        }
5618        return pkgs;
5619    }
5620
5621    public void shutdown() {
5622        mPackageUsage.write(true);
5623    }
5624
5625    @Override
5626    public void forceDexOpt(String packageName) {
5627        enforceSystemOrRoot("forceDexOpt");
5628
5629        PackageParser.Package pkg;
5630        synchronized (mPackages) {
5631            pkg = mPackages.get(packageName);
5632            if (pkg == null) {
5633                throw new IllegalArgumentException("Missing package: " + packageName);
5634            }
5635        }
5636
5637        synchronized (mInstallLock) {
5638            final String[] instructionSets = new String[] {
5639                    getPrimaryInstructionSet(pkg.applicationInfo) };
5640            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
5641                    true /*forceDex*/, false /* defer */, true /* inclDependencies */);
5642            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
5643                throw new IllegalStateException("Failed to dexopt: " + res);
5644            }
5645        }
5646    }
5647
5648    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
5649        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
5650            Slog.w(TAG, "Unable to update from " + oldPkg.name
5651                    + " to " + newPkg.packageName
5652                    + ": old package not in system partition");
5653            return false;
5654        } else if (mPackages.get(oldPkg.name) != null) {
5655            Slog.w(TAG, "Unable to update from " + oldPkg.name
5656                    + " to " + newPkg.packageName
5657                    + ": old package still exists");
5658            return false;
5659        }
5660        return true;
5661    }
5662
5663    private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
5664        int[] users = sUserManager.getUserIds();
5665        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
5666        if (res < 0) {
5667            return res;
5668        }
5669        for (int user : users) {
5670            if (user != 0) {
5671                res = mInstaller.createUserData(volumeUuid, packageName,
5672                        UserHandle.getUid(user, uid), user, seinfo);
5673                if (res < 0) {
5674                    return res;
5675                }
5676            }
5677        }
5678        return res;
5679    }
5680
5681    private int removeDataDirsLI(String volumeUuid, String packageName) {
5682        int[] users = sUserManager.getUserIds();
5683        int res = 0;
5684        for (int user : users) {
5685            int resInner = mInstaller.remove(volumeUuid, packageName, user);
5686            if (resInner < 0) {
5687                res = resInner;
5688            }
5689        }
5690
5691        return res;
5692    }
5693
5694    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
5695        int[] users = sUserManager.getUserIds();
5696        int res = 0;
5697        for (int user : users) {
5698            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
5699            if (resInner < 0) {
5700                res = resInner;
5701            }
5702        }
5703        return res;
5704    }
5705
5706    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
5707            PackageParser.Package changingLib) {
5708        if (file.path != null) {
5709            usesLibraryFiles.add(file.path);
5710            return;
5711        }
5712        PackageParser.Package p = mPackages.get(file.apk);
5713        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
5714            // If we are doing this while in the middle of updating a library apk,
5715            // then we need to make sure to use that new apk for determining the
5716            // dependencies here.  (We haven't yet finished committing the new apk
5717            // to the package manager state.)
5718            if (p == null || p.packageName.equals(changingLib.packageName)) {
5719                p = changingLib;
5720            }
5721        }
5722        if (p != null) {
5723            usesLibraryFiles.addAll(p.getAllCodePaths());
5724        }
5725    }
5726
5727    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
5728            PackageParser.Package changingLib) throws PackageManagerException {
5729        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
5730            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
5731            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
5732            for (int i=0; i<N; i++) {
5733                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
5734                if (file == null) {
5735                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
5736                            "Package " + pkg.packageName + " requires unavailable shared library "
5737                            + pkg.usesLibraries.get(i) + "; failing!");
5738                }
5739                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
5740            }
5741            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
5742            for (int i=0; i<N; i++) {
5743                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
5744                if (file == null) {
5745                    Slog.w(TAG, "Package " + pkg.packageName
5746                            + " desires unavailable shared library "
5747                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
5748                } else {
5749                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
5750                }
5751            }
5752            N = usesLibraryFiles.size();
5753            if (N > 0) {
5754                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
5755            } else {
5756                pkg.usesLibraryFiles = null;
5757            }
5758        }
5759    }
5760
5761    private static boolean hasString(List<String> list, List<String> which) {
5762        if (list == null) {
5763            return false;
5764        }
5765        for (int i=list.size()-1; i>=0; i--) {
5766            for (int j=which.size()-1; j>=0; j--) {
5767                if (which.get(j).equals(list.get(i))) {
5768                    return true;
5769                }
5770            }
5771        }
5772        return false;
5773    }
5774
5775    private void updateAllSharedLibrariesLPw() {
5776        for (PackageParser.Package pkg : mPackages.values()) {
5777            try {
5778                updateSharedLibrariesLPw(pkg, null);
5779            } catch (PackageManagerException e) {
5780                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
5781            }
5782        }
5783    }
5784
5785    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
5786            PackageParser.Package changingPkg) {
5787        ArrayList<PackageParser.Package> res = null;
5788        for (PackageParser.Package pkg : mPackages.values()) {
5789            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
5790                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
5791                if (res == null) {
5792                    res = new ArrayList<PackageParser.Package>();
5793                }
5794                res.add(pkg);
5795                try {
5796                    updateSharedLibrariesLPw(pkg, changingPkg);
5797                } catch (PackageManagerException e) {
5798                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
5799                }
5800            }
5801        }
5802        return res;
5803    }
5804
5805    /**
5806     * Derive the value of the {@code cpuAbiOverride} based on the provided
5807     * value and an optional stored value from the package settings.
5808     */
5809    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
5810        String cpuAbiOverride = null;
5811
5812        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
5813            cpuAbiOverride = null;
5814        } else if (abiOverride != null) {
5815            cpuAbiOverride = abiOverride;
5816        } else if (settings != null) {
5817            cpuAbiOverride = settings.cpuAbiOverrideString;
5818        }
5819
5820        return cpuAbiOverride;
5821    }
5822
5823    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
5824            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5825        boolean success = false;
5826        try {
5827            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
5828                    currentTime, user);
5829            success = true;
5830            return res;
5831        } finally {
5832            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5833                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
5834            }
5835        }
5836    }
5837
5838    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
5839            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5840        final File scanFile = new File(pkg.codePath);
5841        if (pkg.applicationInfo.getCodePath() == null ||
5842                pkg.applicationInfo.getResourcePath() == null) {
5843            // Bail out. The resource and code paths haven't been set.
5844            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
5845                    "Code and resource paths haven't been set correctly");
5846        }
5847
5848        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5849            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
5850        } else {
5851            // Only allow system apps to be flagged as core apps.
5852            pkg.coreApp = false;
5853        }
5854
5855        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
5856            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5857        }
5858
5859        if (mCustomResolverComponentName != null &&
5860                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
5861            setUpCustomResolverActivity(pkg);
5862        }
5863
5864        if (pkg.packageName.equals("android")) {
5865            synchronized (mPackages) {
5866                if (mAndroidApplication != null) {
5867                    Slog.w(TAG, "*************************************************");
5868                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
5869                    Slog.w(TAG, " file=" + scanFile);
5870                    Slog.w(TAG, "*************************************************");
5871                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5872                            "Core android package being redefined.  Skipping.");
5873                }
5874
5875                // Set up information for our fall-back user intent resolution activity.
5876                mPlatformPackage = pkg;
5877                pkg.mVersionCode = mSdkVersion;
5878                mAndroidApplication = pkg.applicationInfo;
5879
5880                if (!mResolverReplaced) {
5881                    mResolveActivity.applicationInfo = mAndroidApplication;
5882                    mResolveActivity.name = ResolverActivity.class.getName();
5883                    mResolveActivity.packageName = mAndroidApplication.packageName;
5884                    mResolveActivity.processName = "system:ui";
5885                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
5886                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
5887                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
5888                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
5889                    mResolveActivity.exported = true;
5890                    mResolveActivity.enabled = true;
5891                    mResolveInfo.activityInfo = mResolveActivity;
5892                    mResolveInfo.priority = 0;
5893                    mResolveInfo.preferredOrder = 0;
5894                    mResolveInfo.match = 0;
5895                    mResolveComponentName = new ComponentName(
5896                            mAndroidApplication.packageName, mResolveActivity.name);
5897                }
5898            }
5899        }
5900
5901        if (DEBUG_PACKAGE_SCANNING) {
5902            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5903                Log.d(TAG, "Scanning package " + pkg.packageName);
5904        }
5905
5906        if (mPackages.containsKey(pkg.packageName)
5907                || mSharedLibraries.containsKey(pkg.packageName)) {
5908            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5909                    "Application package " + pkg.packageName
5910                    + " already installed.  Skipping duplicate.");
5911        }
5912
5913        // If we're only installing presumed-existing packages, require that the
5914        // scanned APK is both already known and at the path previously established
5915        // for it.  Previously unknown packages we pick up normally, but if we have an
5916        // a priori expectation about this package's install presence, enforce it.
5917        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
5918            PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
5919            if (known != null) {
5920                if (DEBUG_PACKAGE_SCANNING) {
5921                    Log.d(TAG, "Examining " + pkg.codePath
5922                            + " and requiring known paths " + known.codePathString
5923                            + " & " + known.resourcePathString);
5924                }
5925                if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
5926                        || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
5927                    throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
5928                            "Application package " + pkg.packageName
5929                            + " found at " + pkg.applicationInfo.getCodePath()
5930                            + " but expected at " + known.codePathString + "; ignoring.");
5931                }
5932            }
5933        }
5934
5935        // Initialize package source and resource directories
5936        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
5937        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
5938
5939        SharedUserSetting suid = null;
5940        PackageSetting pkgSetting = null;
5941
5942        if (!isSystemApp(pkg)) {
5943            // Only system apps can use these features.
5944            pkg.mOriginalPackages = null;
5945            pkg.mRealPackage = null;
5946            pkg.mAdoptPermissions = null;
5947        }
5948
5949        // writer
5950        synchronized (mPackages) {
5951            if (pkg.mSharedUserId != null) {
5952                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
5953                if (suid == null) {
5954                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5955                            "Creating application package " + pkg.packageName
5956                            + " for shared user failed");
5957                }
5958                if (DEBUG_PACKAGE_SCANNING) {
5959                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5960                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
5961                                + "): packages=" + suid.packages);
5962                }
5963            }
5964
5965            // Check if we are renaming from an original package name.
5966            PackageSetting origPackage = null;
5967            String realName = null;
5968            if (pkg.mOriginalPackages != null) {
5969                // This package may need to be renamed to a previously
5970                // installed name.  Let's check on that...
5971                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
5972                if (pkg.mOriginalPackages.contains(renamed)) {
5973                    // This package had originally been installed as the
5974                    // original name, and we have already taken care of
5975                    // transitioning to the new one.  Just update the new
5976                    // one to continue using the old name.
5977                    realName = pkg.mRealPackage;
5978                    if (!pkg.packageName.equals(renamed)) {
5979                        // Callers into this function may have already taken
5980                        // care of renaming the package; only do it here if
5981                        // it is not already done.
5982                        pkg.setPackageName(renamed);
5983                    }
5984
5985                } else {
5986                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
5987                        if ((origPackage = mSettings.peekPackageLPr(
5988                                pkg.mOriginalPackages.get(i))) != null) {
5989                            // We do have the package already installed under its
5990                            // original name...  should we use it?
5991                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
5992                                // New package is not compatible with original.
5993                                origPackage = null;
5994                                continue;
5995                            } else if (origPackage.sharedUser != null) {
5996                                // Make sure uid is compatible between packages.
5997                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
5998                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
5999                                            + " to " + pkg.packageName + ": old uid "
6000                                            + origPackage.sharedUser.name
6001                                            + " differs from " + pkg.mSharedUserId);
6002                                    origPackage = null;
6003                                    continue;
6004                                }
6005                            } else {
6006                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6007                                        + pkg.packageName + " to old name " + origPackage.name);
6008                            }
6009                            break;
6010                        }
6011                    }
6012                }
6013            }
6014
6015            if (mTransferedPackages.contains(pkg.packageName)) {
6016                Slog.w(TAG, "Package " + pkg.packageName
6017                        + " was transferred to another, but its .apk remains");
6018            }
6019
6020            // Just create the setting, don't add it yet. For already existing packages
6021            // the PkgSetting exists already and doesn't have to be created.
6022            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6023                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6024                    pkg.applicationInfo.primaryCpuAbi,
6025                    pkg.applicationInfo.secondaryCpuAbi,
6026                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6027                    user, false);
6028            if (pkgSetting == null) {
6029                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6030                        "Creating application package " + pkg.packageName + " failed");
6031            }
6032
6033            if (pkgSetting.origPackage != null) {
6034                // If we are first transitioning from an original package,
6035                // fix up the new package's name now.  We need to do this after
6036                // looking up the package under its new name, so getPackageLP
6037                // can take care of fiddling things correctly.
6038                pkg.setPackageName(origPackage.name);
6039
6040                // File a report about this.
6041                String msg = "New package " + pkgSetting.realName
6042                        + " renamed to replace old package " + pkgSetting.name;
6043                reportSettingsProblem(Log.WARN, msg);
6044
6045                // Make a note of it.
6046                mTransferedPackages.add(origPackage.name);
6047
6048                // No longer need to retain this.
6049                pkgSetting.origPackage = null;
6050            }
6051
6052            if (realName != null) {
6053                // Make a note of it.
6054                mTransferedPackages.add(pkg.packageName);
6055            }
6056
6057            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6058                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6059            }
6060
6061            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6062                // Check all shared libraries and map to their actual file path.
6063                // We only do this here for apps not on a system dir, because those
6064                // are the only ones that can fail an install due to this.  We
6065                // will take care of the system apps by updating all of their
6066                // library paths after the scan is done.
6067                updateSharedLibrariesLPw(pkg, null);
6068            }
6069
6070            if (mFoundPolicyFile) {
6071                SELinuxMMAC.assignSeinfoValue(pkg);
6072            }
6073
6074            pkg.applicationInfo.uid = pkgSetting.appId;
6075            pkg.mExtras = pkgSetting;
6076            if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) {
6077                try {
6078                    verifySignaturesLP(pkgSetting, pkg);
6079                    // We just determined the app is signed correctly, so bring
6080                    // over the latest parsed certs.
6081                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6082                } catch (PackageManagerException e) {
6083                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6084                        throw e;
6085                    }
6086                    // The signature has changed, but this package is in the system
6087                    // image...  let's recover!
6088                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6089                    // However...  if this package is part of a shared user, but it
6090                    // doesn't match the signature of the shared user, let's fail.
6091                    // What this means is that you can't change the signatures
6092                    // associated with an overall shared user, which doesn't seem all
6093                    // that unreasonable.
6094                    if (pkgSetting.sharedUser != null) {
6095                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6096                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
6097                            throw new PackageManagerException(
6098                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
6099                                            "Signature mismatch for shared user : "
6100                                            + pkgSetting.sharedUser);
6101                        }
6102                    }
6103                    // File a report about this.
6104                    String msg = "System package " + pkg.packageName
6105                        + " signature changed; retaining data.";
6106                    reportSettingsProblem(Log.WARN, msg);
6107                }
6108            } else {
6109                if (!checkUpgradeKeySetLP(pkgSetting, pkg)) {
6110                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
6111                            + pkg.packageName + " upgrade keys do not match the "
6112                            + "previously installed version");
6113                } else {
6114                    // We just determined the app is signed correctly, so bring
6115                    // over the latest parsed certs.
6116                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6117                }
6118            }
6119            // Verify that this new package doesn't have any content providers
6120            // that conflict with existing packages.  Only do this if the
6121            // package isn't already installed, since we don't want to break
6122            // things that are installed.
6123            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6124                final int N = pkg.providers.size();
6125                int i;
6126                for (i=0; i<N; i++) {
6127                    PackageParser.Provider p = pkg.providers.get(i);
6128                    if (p.info.authority != null) {
6129                        String names[] = p.info.authority.split(";");
6130                        for (int j = 0; j < names.length; j++) {
6131                            if (mProvidersByAuthority.containsKey(names[j])) {
6132                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6133                                final String otherPackageName =
6134                                        ((other != null && other.getComponentName() != null) ?
6135                                                other.getComponentName().getPackageName() : "?");
6136                                throw new PackageManagerException(
6137                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
6138                                                "Can't install because provider name " + names[j]
6139                                                + " (in package " + pkg.applicationInfo.packageName
6140                                                + ") is already used by " + otherPackageName);
6141                            }
6142                        }
6143                    }
6144                }
6145            }
6146
6147            if (pkg.mAdoptPermissions != null) {
6148                // This package wants to adopt ownership of permissions from
6149                // another package.
6150                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6151                    final String origName = pkg.mAdoptPermissions.get(i);
6152                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
6153                    if (orig != null) {
6154                        if (verifyPackageUpdateLPr(orig, pkg)) {
6155                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
6156                                    + pkg.packageName);
6157                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
6158                        }
6159                    }
6160                }
6161            }
6162        }
6163
6164        final String pkgName = pkg.packageName;
6165
6166        final long scanFileTime = scanFile.lastModified();
6167        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6168        pkg.applicationInfo.processName = fixProcessName(
6169                pkg.applicationInfo.packageName,
6170                pkg.applicationInfo.processName,
6171                pkg.applicationInfo.uid);
6172
6173        File dataPath;
6174        if (mPlatformPackage == pkg) {
6175            // The system package is special.
6176            dataPath = new File(Environment.getDataDirectory(), "system");
6177
6178            pkg.applicationInfo.dataDir = dataPath.getPath();
6179
6180        } else {
6181            // This is a normal package, need to make its data directory.
6182            dataPath = PackageManager.getDataDirForUser(pkg.volumeUuid, pkg.packageName,
6183                    UserHandle.USER_OWNER);
6184
6185            boolean uidError = false;
6186            if (dataPath.exists()) {
6187                int currentUid = 0;
6188                try {
6189                    StructStat stat = Os.stat(dataPath.getPath());
6190                    currentUid = stat.st_uid;
6191                } catch (ErrnoException e) {
6192                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6193                }
6194
6195                // If we have mismatched owners for the data path, we have a problem.
6196                if (currentUid != pkg.applicationInfo.uid) {
6197                    boolean recovered = false;
6198                    if (currentUid == 0) {
6199                        // The directory somehow became owned by root.  Wow.
6200                        // This is probably because the system was stopped while
6201                        // installd was in the middle of messing with its libs
6202                        // directory.  Ask installd to fix that.
6203                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
6204                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
6205                        if (ret >= 0) {
6206                            recovered = true;
6207                            String msg = "Package " + pkg.packageName
6208                                    + " unexpectedly changed to uid 0; recovered to " +
6209                                    + pkg.applicationInfo.uid;
6210                            reportSettingsProblem(Log.WARN, msg);
6211                        }
6212                    }
6213                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6214                            || (scanFlags&SCAN_BOOTING) != 0)) {
6215                        // If this is a system app, we can at least delete its
6216                        // current data so the application will still work.
6217                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
6218                        if (ret >= 0) {
6219                            // TODO: Kill the processes first
6220                            // Old data gone!
6221                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6222                                    ? "System package " : "Third party package ";
6223                            String msg = prefix + pkg.packageName
6224                                    + " has changed from uid: "
6225                                    + currentUid + " to "
6226                                    + pkg.applicationInfo.uid + "; old data erased";
6227                            reportSettingsProblem(Log.WARN, msg);
6228                            recovered = true;
6229
6230                            // And now re-install the app.
6231                            ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6232                                    pkg.applicationInfo.seinfo);
6233                            if (ret == -1) {
6234                                // Ack should not happen!
6235                                msg = prefix + pkg.packageName
6236                                        + " could not have data directory re-created after delete.";
6237                                reportSettingsProblem(Log.WARN, msg);
6238                                throw new PackageManagerException(
6239                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6240                            }
6241                        }
6242                        if (!recovered) {
6243                            mHasSystemUidErrors = true;
6244                        }
6245                    } else if (!recovered) {
6246                        // If we allow this install to proceed, we will be broken.
6247                        // Abort, abort!
6248                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
6249                                "scanPackageLI");
6250                    }
6251                    if (!recovered) {
6252                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
6253                            + pkg.applicationInfo.uid + "/fs_"
6254                            + currentUid;
6255                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
6256                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
6257                        String msg = "Package " + pkg.packageName
6258                                + " has mismatched uid: "
6259                                + currentUid + " on disk, "
6260                                + pkg.applicationInfo.uid + " in settings";
6261                        // writer
6262                        synchronized (mPackages) {
6263                            mSettings.mReadMessages.append(msg);
6264                            mSettings.mReadMessages.append('\n');
6265                            uidError = true;
6266                            if (!pkgSetting.uidError) {
6267                                reportSettingsProblem(Log.ERROR, msg);
6268                            }
6269                        }
6270                    }
6271                }
6272                pkg.applicationInfo.dataDir = dataPath.getPath();
6273                if (mShouldRestoreconData) {
6274                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
6275                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
6276                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
6277                }
6278            } else {
6279                if (DEBUG_PACKAGE_SCANNING) {
6280                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6281                        Log.v(TAG, "Want this data dir: " + dataPath);
6282                }
6283                //invoke installer to do the actual installation
6284                int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6285                        pkg.applicationInfo.seinfo);
6286                if (ret < 0) {
6287                    // Error from installer
6288                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6289                            "Unable to create data dirs [errorCode=" + ret + "]");
6290                }
6291
6292                if (dataPath.exists()) {
6293                    pkg.applicationInfo.dataDir = dataPath.getPath();
6294                } else {
6295                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
6296                    pkg.applicationInfo.dataDir = null;
6297                }
6298            }
6299
6300            pkgSetting.uidError = uidError;
6301        }
6302
6303        final String path = scanFile.getPath();
6304        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
6305        if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
6306            setBundledAppAbisAndRoots(pkg, pkgSetting);
6307
6308            // If we haven't found any native libraries for the app, check if it has
6309            // renderscript code. We'll need to force the app to 32 bit if it has
6310            // renderscript bitcode.
6311            if (pkg.applicationInfo.primaryCpuAbi == null
6312                    && pkg.applicationInfo.secondaryCpuAbi == null
6313                    && Build.SUPPORTED_64_BIT_ABIS.length >  0) {
6314                NativeLibraryHelper.Handle handle = null;
6315                try {
6316                    handle = NativeLibraryHelper.Handle.create(scanFile);
6317                    if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
6318                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6319                    }
6320                } catch (IOException ioe) {
6321                    Slog.w(TAG, "Error scanning system app : " + ioe);
6322                } finally {
6323                    IoUtils.closeQuietly(handle);
6324                }
6325            }
6326
6327            setNativeLibraryPaths(pkg);
6328        } else {
6329            if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
6330                deriveNonSystemPackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
6331            } else {
6332                // Verify the ABIs haven't changed since we last deduced them.
6333                String oldPrimaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
6334                String oldSecondaryCpuAbi = pkg.applicationInfo.secondaryCpuAbi;
6335
6336                // TODO: The only purpose of this code is to update the native library paths
6337                // based on the final install location. We can simplify this and avoid having
6338                // to scan the package again.
6339                deriveNonSystemPackageAbi(pkg, scanFile, cpuAbiOverride, false /* extract libs */);
6340                if (!TextUtils.equals(oldPrimaryCpuAbi, pkg.applicationInfo.primaryCpuAbi)) {
6341                    throw new IllegalStateException("unexpected abi change for " + pkg.packageName + " ("
6342                            + oldPrimaryCpuAbi + "-> " + pkg.applicationInfo.primaryCpuAbi);
6343                }
6344
6345                if (!TextUtils.equals(oldSecondaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi)) {
6346                    throw new IllegalStateException("unexpected abi change for " + pkg.packageName + " ("
6347                            + oldSecondaryCpuAbi + "-> " + pkg.applicationInfo.secondaryCpuAbi);
6348                }
6349            }
6350
6351            if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
6352            final int[] userIds = sUserManager.getUserIds();
6353            synchronized (mInstallLock) {
6354                // Create a native library symlink only if we have native libraries
6355                // and if the native libraries are 32 bit libraries. We do not provide
6356                // this symlink for 64 bit libraries.
6357                if (pkg.applicationInfo.primaryCpuAbi != null &&
6358                        !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
6359                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
6360                    for (int userId : userIds) {
6361                        if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
6362                                nativeLibPath, userId) < 0) {
6363                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
6364                                    "Failed linking native library dir (user=" + userId + ")");
6365                        }
6366                    }
6367                }
6368            }
6369        }
6370
6371        // This is a special case for the "system" package, where the ABI is
6372        // dictated by the zygote configuration (and init.rc). We should keep track
6373        // of this ABI so that we can deal with "normal" applications that run under
6374        // the same UID correctly.
6375        if (mPlatformPackage == pkg) {
6376            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
6377                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
6378        }
6379
6380        // If there's a mismatch between the abi-override in the package setting
6381        // and the abiOverride specified for the install. Warn about this because we
6382        // would've already compiled the app without taking the package setting into
6383        // account.
6384        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
6385            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
6386                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
6387                        " for package: " + pkg.packageName);
6388            }
6389        }
6390
6391        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6392        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6393        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
6394
6395        // Copy the derived override back to the parsed package, so that we can
6396        // update the package settings accordingly.
6397        pkg.cpuAbiOverride = cpuAbiOverride;
6398
6399        if (DEBUG_ABI_SELECTION) {
6400            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
6401                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
6402                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
6403        }
6404
6405        // Push the derived path down into PackageSettings so we know what to
6406        // clean up at uninstall time.
6407        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
6408
6409        if (DEBUG_ABI_SELECTION) {
6410            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
6411                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
6412                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
6413        }
6414
6415        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
6416            // We don't do this here during boot because we can do it all
6417            // at once after scanning all existing packages.
6418            //
6419            // We also do this *before* we perform dexopt on this package, so that
6420            // we can avoid redundant dexopts, and also to make sure we've got the
6421            // code and package path correct.
6422            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
6423                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
6424        }
6425
6426        if ((scanFlags & SCAN_NO_DEX) == 0) {
6427            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
6428                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */);
6429            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6430                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
6431            }
6432        }
6433        if (mFactoryTest && pkg.requestedPermissions.contains(
6434                android.Manifest.permission.FACTORY_TEST)) {
6435            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
6436        }
6437
6438        ArrayList<PackageParser.Package> clientLibPkgs = null;
6439
6440        // writer
6441        synchronized (mPackages) {
6442            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6443                // Only system apps can add new shared libraries.
6444                if (pkg.libraryNames != null) {
6445                    for (int i=0; i<pkg.libraryNames.size(); i++) {
6446                        String name = pkg.libraryNames.get(i);
6447                        boolean allowed = false;
6448                        if (pkg.isUpdatedSystemApp()) {
6449                            // New library entries can only be added through the
6450                            // system image.  This is important to get rid of a lot
6451                            // of nasty edge cases: for example if we allowed a non-
6452                            // system update of the app to add a library, then uninstalling
6453                            // the update would make the library go away, and assumptions
6454                            // we made such as through app install filtering would now
6455                            // have allowed apps on the device which aren't compatible
6456                            // with it.  Better to just have the restriction here, be
6457                            // conservative, and create many fewer cases that can negatively
6458                            // impact the user experience.
6459                            final PackageSetting sysPs = mSettings
6460                                    .getDisabledSystemPkgLPr(pkg.packageName);
6461                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
6462                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
6463                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
6464                                        allowed = true;
6465                                        allowed = true;
6466                                        break;
6467                                    }
6468                                }
6469                            }
6470                        } else {
6471                            allowed = true;
6472                        }
6473                        if (allowed) {
6474                            if (!mSharedLibraries.containsKey(name)) {
6475                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
6476                            } else if (!name.equals(pkg.packageName)) {
6477                                Slog.w(TAG, "Package " + pkg.packageName + " library "
6478                                        + name + " already exists; skipping");
6479                            }
6480                        } else {
6481                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
6482                                    + name + " that is not declared on system image; skipping");
6483                        }
6484                    }
6485                    if ((scanFlags&SCAN_BOOTING) == 0) {
6486                        // If we are not booting, we need to update any applications
6487                        // that are clients of our shared library.  If we are booting,
6488                        // this will all be done once the scan is complete.
6489                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
6490                    }
6491                }
6492            }
6493        }
6494
6495        // We also need to dexopt any apps that are dependent on this library.  Note that
6496        // if these fail, we should abort the install since installing the library will
6497        // result in some apps being broken.
6498        if (clientLibPkgs != null) {
6499            if ((scanFlags & SCAN_NO_DEX) == 0) {
6500                for (int i = 0; i < clientLibPkgs.size(); i++) {
6501                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
6502                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
6503                            null /* instruction sets */, forceDex,
6504                            (scanFlags & SCAN_DEFER_DEX) != 0, false);
6505                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6506                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
6507                                "scanPackageLI failed to dexopt clientLibPkgs");
6508                    }
6509                }
6510            }
6511        }
6512
6513        // Also need to kill any apps that are dependent on the library.
6514        if (clientLibPkgs != null) {
6515            for (int i=0; i<clientLibPkgs.size(); i++) {
6516                PackageParser.Package clientPkg = clientLibPkgs.get(i);
6517                killApplication(clientPkg.applicationInfo.packageName,
6518                        clientPkg.applicationInfo.uid, "update lib");
6519            }
6520        }
6521
6522        // writer
6523        synchronized (mPackages) {
6524            // We don't expect installation to fail beyond this point
6525
6526            // Add the new setting to mSettings
6527            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
6528            // Add the new setting to mPackages
6529            mPackages.put(pkg.applicationInfo.packageName, pkg);
6530            // Make sure we don't accidentally delete its data.
6531            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
6532            while (iter.hasNext()) {
6533                PackageCleanItem item = iter.next();
6534                if (pkgName.equals(item.packageName)) {
6535                    iter.remove();
6536                }
6537            }
6538
6539            // Take care of first install / last update times.
6540            if (currentTime != 0) {
6541                if (pkgSetting.firstInstallTime == 0) {
6542                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
6543                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
6544                    pkgSetting.lastUpdateTime = currentTime;
6545                }
6546            } else if (pkgSetting.firstInstallTime == 0) {
6547                // We need *something*.  Take time time stamp of the file.
6548                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
6549            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
6550                if (scanFileTime != pkgSetting.timeStamp) {
6551                    // A package on the system image has changed; consider this
6552                    // to be an update.
6553                    pkgSetting.lastUpdateTime = scanFileTime;
6554                }
6555            }
6556
6557            // Add the package's KeySets to the global KeySetManagerService
6558            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6559            try {
6560                ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys);
6561                if (pkg.mKeySetMapping != null) {
6562                    ksms.addDefinedKeySetsToPackageLPw(pkg.packageName, pkg.mKeySetMapping);
6563                    if (pkg.mUpgradeKeySets != null) {
6564                        ksms.addUpgradeKeySetsToPackageLPw(pkg.packageName, pkg.mUpgradeKeySets);
6565                    }
6566                }
6567            } catch (NullPointerException e) {
6568                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
6569            } catch (IllegalArgumentException e) {
6570                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
6571            }
6572
6573            int N = pkg.providers.size();
6574            StringBuilder r = null;
6575            int i;
6576            for (i=0; i<N; i++) {
6577                PackageParser.Provider p = pkg.providers.get(i);
6578                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
6579                        p.info.processName, pkg.applicationInfo.uid);
6580                mProviders.addProvider(p);
6581                p.syncable = p.info.isSyncable;
6582                if (p.info.authority != null) {
6583                    String names[] = p.info.authority.split(";");
6584                    p.info.authority = null;
6585                    for (int j = 0; j < names.length; j++) {
6586                        if (j == 1 && p.syncable) {
6587                            // We only want the first authority for a provider to possibly be
6588                            // syncable, so if we already added this provider using a different
6589                            // authority clear the syncable flag. We copy the provider before
6590                            // changing it because the mProviders object contains a reference
6591                            // to a provider that we don't want to change.
6592                            // Only do this for the second authority since the resulting provider
6593                            // object can be the same for all future authorities for this provider.
6594                            p = new PackageParser.Provider(p);
6595                            p.syncable = false;
6596                        }
6597                        if (!mProvidersByAuthority.containsKey(names[j])) {
6598                            mProvidersByAuthority.put(names[j], p);
6599                            if (p.info.authority == null) {
6600                                p.info.authority = names[j];
6601                            } else {
6602                                p.info.authority = p.info.authority + ";" + names[j];
6603                            }
6604                            if (DEBUG_PACKAGE_SCANNING) {
6605                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6606                                    Log.d(TAG, "Registered content provider: " + names[j]
6607                                            + ", className = " + p.info.name + ", isSyncable = "
6608                                            + p.info.isSyncable);
6609                            }
6610                        } else {
6611                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6612                            Slog.w(TAG, "Skipping provider name " + names[j] +
6613                                    " (in package " + pkg.applicationInfo.packageName +
6614                                    "): name already used by "
6615                                    + ((other != null && other.getComponentName() != null)
6616                                            ? other.getComponentName().getPackageName() : "?"));
6617                        }
6618                    }
6619                }
6620                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6621                    if (r == null) {
6622                        r = new StringBuilder(256);
6623                    } else {
6624                        r.append(' ');
6625                    }
6626                    r.append(p.info.name);
6627                }
6628            }
6629            if (r != null) {
6630                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
6631            }
6632
6633            N = pkg.services.size();
6634            r = null;
6635            for (i=0; i<N; i++) {
6636                PackageParser.Service s = pkg.services.get(i);
6637                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
6638                        s.info.processName, pkg.applicationInfo.uid);
6639                mServices.addService(s);
6640                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6641                    if (r == null) {
6642                        r = new StringBuilder(256);
6643                    } else {
6644                        r.append(' ');
6645                    }
6646                    r.append(s.info.name);
6647                }
6648            }
6649            if (r != null) {
6650                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
6651            }
6652
6653            N = pkg.receivers.size();
6654            r = null;
6655            for (i=0; i<N; i++) {
6656                PackageParser.Activity a = pkg.receivers.get(i);
6657                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6658                        a.info.processName, pkg.applicationInfo.uid);
6659                mReceivers.addActivity(a, "receiver");
6660                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6661                    if (r == null) {
6662                        r = new StringBuilder(256);
6663                    } else {
6664                        r.append(' ');
6665                    }
6666                    r.append(a.info.name);
6667                }
6668            }
6669            if (r != null) {
6670                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
6671            }
6672
6673            N = pkg.activities.size();
6674            r = null;
6675            for (i=0; i<N; i++) {
6676                PackageParser.Activity a = pkg.activities.get(i);
6677                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6678                        a.info.processName, pkg.applicationInfo.uid);
6679                mActivities.addActivity(a, "activity");
6680                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6681                    if (r == null) {
6682                        r = new StringBuilder(256);
6683                    } else {
6684                        r.append(' ');
6685                    }
6686                    r.append(a.info.name);
6687                }
6688            }
6689            if (r != null) {
6690                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
6691            }
6692
6693            N = pkg.permissionGroups.size();
6694            r = null;
6695            for (i=0; i<N; i++) {
6696                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
6697                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
6698                if (cur == null) {
6699                    mPermissionGroups.put(pg.info.name, pg);
6700                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6701                        if (r == null) {
6702                            r = new StringBuilder(256);
6703                        } else {
6704                            r.append(' ');
6705                        }
6706                        r.append(pg.info.name);
6707                    }
6708                } else {
6709                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
6710                            + pg.info.packageName + " ignored: original from "
6711                            + cur.info.packageName);
6712                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6713                        if (r == null) {
6714                            r = new StringBuilder(256);
6715                        } else {
6716                            r.append(' ');
6717                        }
6718                        r.append("DUP:");
6719                        r.append(pg.info.name);
6720                    }
6721                }
6722            }
6723            if (r != null) {
6724                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
6725            }
6726
6727            N = pkg.permissions.size();
6728            r = null;
6729            for (i=0; i<N; i++) {
6730                PackageParser.Permission p = pkg.permissions.get(i);
6731
6732                // Now that permission groups have a special meaning, we ignore permission
6733                // groups for legacy apps to prevent unexpected behavior. In particular,
6734                // permissions for one app being granted to someone just becuase they happen
6735                // to be in a group defined by another app (before this had no implications).
6736                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
6737                    p.group = mPermissionGroups.get(p.info.group);
6738                    // Warn for a permission in an unknown group.
6739                    if (p.info.group != null && p.group == null) {
6740                        Slog.w(TAG, "Permission " + p.info.name + " from package "
6741                                + p.info.packageName + " in an unknown group " + p.info.group);
6742                    }
6743                }
6744
6745                ArrayMap<String, BasePermission> permissionMap =
6746                        p.tree ? mSettings.mPermissionTrees
6747                                : mSettings.mPermissions;
6748                BasePermission bp = permissionMap.get(p.info.name);
6749
6750                // Allow system apps to redefine non-system permissions
6751                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
6752                    final boolean currentOwnerIsSystem = (bp.perm != null
6753                            && isSystemApp(bp.perm.owner));
6754                    if (isSystemApp(p.owner)) {
6755                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
6756                            // It's a built-in permission and no owner, take ownership now
6757                            bp.packageSetting = pkgSetting;
6758                            bp.perm = p;
6759                            bp.uid = pkg.applicationInfo.uid;
6760                            bp.sourcePackage = p.info.packageName;
6761                        } else if (!currentOwnerIsSystem) {
6762                            String msg = "New decl " + p.owner + " of permission  "
6763                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
6764                            reportSettingsProblem(Log.WARN, msg);
6765                            bp = null;
6766                        }
6767                    }
6768                }
6769
6770                if (bp == null) {
6771                    bp = new BasePermission(p.info.name, p.info.packageName,
6772                            BasePermission.TYPE_NORMAL);
6773                    permissionMap.put(p.info.name, bp);
6774                }
6775
6776                if (bp.perm == null) {
6777                    if (bp.sourcePackage == null
6778                            || bp.sourcePackage.equals(p.info.packageName)) {
6779                        BasePermission tree = findPermissionTreeLP(p.info.name);
6780                        if (tree == null
6781                                || tree.sourcePackage.equals(p.info.packageName)) {
6782                            bp.packageSetting = pkgSetting;
6783                            bp.perm = p;
6784                            bp.uid = pkg.applicationInfo.uid;
6785                            bp.sourcePackage = p.info.packageName;
6786                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6787                                if (r == null) {
6788                                    r = new StringBuilder(256);
6789                                } else {
6790                                    r.append(' ');
6791                                }
6792                                r.append(p.info.name);
6793                            }
6794                        } else {
6795                            Slog.w(TAG, "Permission " + p.info.name + " from package "
6796                                    + p.info.packageName + " ignored: base tree "
6797                                    + tree.name + " is from package "
6798                                    + tree.sourcePackage);
6799                        }
6800                    } else {
6801                        Slog.w(TAG, "Permission " + p.info.name + " from package "
6802                                + p.info.packageName + " ignored: original from "
6803                                + bp.sourcePackage);
6804                    }
6805                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6806                    if (r == null) {
6807                        r = new StringBuilder(256);
6808                    } else {
6809                        r.append(' ');
6810                    }
6811                    r.append("DUP:");
6812                    r.append(p.info.name);
6813                }
6814                if (bp.perm == p) {
6815                    bp.protectionLevel = p.info.protectionLevel;
6816                }
6817            }
6818
6819            if (r != null) {
6820                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
6821            }
6822
6823            N = pkg.instrumentation.size();
6824            r = null;
6825            for (i=0; i<N; i++) {
6826                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6827                a.info.packageName = pkg.applicationInfo.packageName;
6828                a.info.sourceDir = pkg.applicationInfo.sourceDir;
6829                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
6830                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
6831                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
6832                a.info.dataDir = pkg.applicationInfo.dataDir;
6833
6834                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
6835                // need other information about the application, like the ABI and what not ?
6836                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
6837                mInstrumentation.put(a.getComponentName(), a);
6838                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6839                    if (r == null) {
6840                        r = new StringBuilder(256);
6841                    } else {
6842                        r.append(' ');
6843                    }
6844                    r.append(a.info.name);
6845                }
6846            }
6847            if (r != null) {
6848                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
6849            }
6850
6851            if (pkg.protectedBroadcasts != null) {
6852                N = pkg.protectedBroadcasts.size();
6853                for (i=0; i<N; i++) {
6854                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
6855                }
6856            }
6857
6858            pkgSetting.setTimeStamp(scanFileTime);
6859
6860            // Create idmap files for pairs of (packages, overlay packages).
6861            // Note: "android", ie framework-res.apk, is handled by native layers.
6862            if (pkg.mOverlayTarget != null) {
6863                // This is an overlay package.
6864                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
6865                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
6866                        mOverlays.put(pkg.mOverlayTarget,
6867                                new ArrayMap<String, PackageParser.Package>());
6868                    }
6869                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
6870                    map.put(pkg.packageName, pkg);
6871                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
6872                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
6873                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6874                                "scanPackageLI failed to createIdmap");
6875                    }
6876                }
6877            } else if (mOverlays.containsKey(pkg.packageName) &&
6878                    !pkg.packageName.equals("android")) {
6879                // This is a regular package, with one or more known overlay packages.
6880                createIdmapsForPackageLI(pkg);
6881            }
6882        }
6883
6884        return pkg;
6885    }
6886
6887    /**
6888     * Derive the ABI of a non-system package located at {@code scanFile}. This information
6889     * is derived purely on the basis of the contents of {@code scanFile} and
6890     * {@code cpuAbiOverride}.
6891     *
6892     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
6893     */
6894    public void deriveNonSystemPackageAbi(PackageParser.Package pkg, File scanFile,
6895                                          String cpuAbiOverride, boolean extractLibs)
6896            throws PackageManagerException {
6897        // TODO: We can probably be smarter about this stuff. For installed apps,
6898        // we can calculate this information at install time once and for all. For
6899        // system apps, we can probably assume that this information doesn't change
6900        // after the first boot scan. As things stand, we do lots of unnecessary work.
6901
6902        // Give ourselves some initial paths; we'll come back for another
6903        // pass once we've determined ABI below.
6904        setNativeLibraryPaths(pkg);
6905
6906        // We would never need to extract libs for forward-locked and external packages,
6907        // since the container service will do it for us.
6908        if (pkg.isForwardLocked() || isExternal(pkg)) {
6909            extractLibs = false;
6910        }
6911
6912        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
6913        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
6914
6915        NativeLibraryHelper.Handle handle = null;
6916        try {
6917            handle = NativeLibraryHelper.Handle.create(scanFile);
6918            // TODO(multiArch): This can be null for apps that didn't go through the
6919            // usual installation process. We can calculate it again, like we
6920            // do during install time.
6921            //
6922            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
6923            // unnecessary.
6924            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
6925
6926            // Null out the abis so that they can be recalculated.
6927            pkg.applicationInfo.primaryCpuAbi = null;
6928            pkg.applicationInfo.secondaryCpuAbi = null;
6929            if (isMultiArch(pkg.applicationInfo)) {
6930                // Warn if we've set an abiOverride for multi-lib packages..
6931                // By definition, we need to copy both 32 and 64 bit libraries for
6932                // such packages.
6933                if (pkg.cpuAbiOverride != null
6934                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
6935                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
6936                }
6937
6938                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
6939                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
6940                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
6941                    if (extractLibs) {
6942                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
6943                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
6944                                useIsaSpecificSubdirs);
6945                    } else {
6946                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
6947                    }
6948                }
6949
6950                maybeThrowExceptionForMultiArchCopy(
6951                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
6952
6953                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
6954                    if (extractLibs) {
6955                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
6956                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
6957                                useIsaSpecificSubdirs);
6958                    } else {
6959                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
6960                    }
6961                }
6962
6963                maybeThrowExceptionForMultiArchCopy(
6964                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
6965
6966                if (abi64 >= 0) {
6967                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
6968                }
6969
6970                if (abi32 >= 0) {
6971                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
6972                    if (abi64 >= 0) {
6973                        pkg.applicationInfo.secondaryCpuAbi = abi;
6974                    } else {
6975                        pkg.applicationInfo.primaryCpuAbi = abi;
6976                    }
6977                }
6978            } else {
6979                String[] abiList = (cpuAbiOverride != null) ?
6980                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
6981
6982                // Enable gross and lame hacks for apps that are built with old
6983                // SDK tools. We must scan their APKs for renderscript bitcode and
6984                // not launch them if it's present. Don't bother checking on devices
6985                // that don't have 64 bit support.
6986                boolean needsRenderScriptOverride = false;
6987                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
6988                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
6989                    abiList = Build.SUPPORTED_32_BIT_ABIS;
6990                    needsRenderScriptOverride = true;
6991                }
6992
6993                final int copyRet;
6994                if (extractLibs) {
6995                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
6996                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
6997                } else {
6998                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
6999                }
7000
7001                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7002                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7003                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7004                }
7005
7006                if (copyRet >= 0) {
7007                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7008                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7009                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7010                } else if (needsRenderScriptOverride) {
7011                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7012                }
7013            }
7014        } catch (IOException ioe) {
7015            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7016        } finally {
7017            IoUtils.closeQuietly(handle);
7018        }
7019
7020        // Now that we've calculated the ABIs and determined if it's an internal app,
7021        // we will go ahead and populate the nativeLibraryPath.
7022        setNativeLibraryPaths(pkg);
7023    }
7024
7025    /**
7026     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7027     * i.e, so that all packages can be run inside a single process if required.
7028     *
7029     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7030     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7031     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7032     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7033     * updating a package that belongs to a shared user.
7034     *
7035     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7036     * adds unnecessary complexity.
7037     */
7038    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7039            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
7040        String requiredInstructionSet = null;
7041        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7042            requiredInstructionSet = VMRuntime.getInstructionSet(
7043                     scannedPackage.applicationInfo.primaryCpuAbi);
7044        }
7045
7046        PackageSetting requirer = null;
7047        for (PackageSetting ps : packagesForUser) {
7048            // If packagesForUser contains scannedPackage, we skip it. This will happen
7049            // when scannedPackage is an update of an existing package. Without this check,
7050            // we will never be able to change the ABI of any package belonging to a shared
7051            // user, even if it's compatible with other packages.
7052            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7053                if (ps.primaryCpuAbiString == null) {
7054                    continue;
7055                }
7056
7057                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7058                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7059                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7060                    // this but there's not much we can do.
7061                    String errorMessage = "Instruction set mismatch, "
7062                            + ((requirer == null) ? "[caller]" : requirer)
7063                            + " requires " + requiredInstructionSet + " whereas " + ps
7064                            + " requires " + instructionSet;
7065                    Slog.w(TAG, errorMessage);
7066                }
7067
7068                if (requiredInstructionSet == null) {
7069                    requiredInstructionSet = instructionSet;
7070                    requirer = ps;
7071                }
7072            }
7073        }
7074
7075        if (requiredInstructionSet != null) {
7076            String adjustedAbi;
7077            if (requirer != null) {
7078                // requirer != null implies that either scannedPackage was null or that scannedPackage
7079                // did not require an ABI, in which case we have to adjust scannedPackage to match
7080                // the ABI of the set (which is the same as requirer's ABI)
7081                adjustedAbi = requirer.primaryCpuAbiString;
7082                if (scannedPackage != null) {
7083                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7084                }
7085            } else {
7086                // requirer == null implies that we're updating all ABIs in the set to
7087                // match scannedPackage.
7088                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7089            }
7090
7091            for (PackageSetting ps : packagesForUser) {
7092                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7093                    if (ps.primaryCpuAbiString != null) {
7094                        continue;
7095                    }
7096
7097                    ps.primaryCpuAbiString = adjustedAbi;
7098                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7099                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7100                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7101
7102                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
7103                                null /* instruction sets */, forceDexOpt, deferDexOpt, true);
7104                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7105                            ps.primaryCpuAbiString = null;
7106                            ps.pkg.applicationInfo.primaryCpuAbi = null;
7107                            return;
7108                        } else {
7109                            mInstaller.rmdex(ps.codePathString,
7110                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
7111                        }
7112                    }
7113                }
7114            }
7115        }
7116    }
7117
7118    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7119        synchronized (mPackages) {
7120            mResolverReplaced = true;
7121            // Set up information for custom user intent resolution activity.
7122            mResolveActivity.applicationInfo = pkg.applicationInfo;
7123            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7124            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7125            mResolveActivity.processName = pkg.applicationInfo.packageName;
7126            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7127            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7128                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7129            mResolveActivity.theme = 0;
7130            mResolveActivity.exported = true;
7131            mResolveActivity.enabled = true;
7132            mResolveInfo.activityInfo = mResolveActivity;
7133            mResolveInfo.priority = 0;
7134            mResolveInfo.preferredOrder = 0;
7135            mResolveInfo.match = 0;
7136            mResolveComponentName = mCustomResolverComponentName;
7137            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7138                    mResolveComponentName);
7139        }
7140    }
7141
7142    private static String calculateBundledApkRoot(final String codePathString) {
7143        final File codePath = new File(codePathString);
7144        final File codeRoot;
7145        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7146            codeRoot = Environment.getRootDirectory();
7147        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7148            codeRoot = Environment.getOemDirectory();
7149        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7150            codeRoot = Environment.getVendorDirectory();
7151        } else {
7152            // Unrecognized code path; take its top real segment as the apk root:
7153            // e.g. /something/app/blah.apk => /something
7154            try {
7155                File f = codePath.getCanonicalFile();
7156                File parent = f.getParentFile();    // non-null because codePath is a file
7157                File tmp;
7158                while ((tmp = parent.getParentFile()) != null) {
7159                    f = parent;
7160                    parent = tmp;
7161                }
7162                codeRoot = f;
7163                Slog.w(TAG, "Unrecognized code path "
7164                        + codePath + " - using " + codeRoot);
7165            } catch (IOException e) {
7166                // Can't canonicalize the code path -- shenanigans?
7167                Slog.w(TAG, "Can't canonicalize code path " + codePath);
7168                return Environment.getRootDirectory().getPath();
7169            }
7170        }
7171        return codeRoot.getPath();
7172    }
7173
7174    /**
7175     * Derive and set the location of native libraries for the given package,
7176     * which varies depending on where and how the package was installed.
7177     */
7178    private void setNativeLibraryPaths(PackageParser.Package pkg) {
7179        final ApplicationInfo info = pkg.applicationInfo;
7180        final String codePath = pkg.codePath;
7181        final File codeFile = new File(codePath);
7182        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7183        final boolean asecApp = info.isForwardLocked() || isExternal(info);
7184
7185        info.nativeLibraryRootDir = null;
7186        info.nativeLibraryRootRequiresIsa = false;
7187        info.nativeLibraryDir = null;
7188        info.secondaryNativeLibraryDir = null;
7189
7190        if (isApkFile(codeFile)) {
7191            // Monolithic install
7192            if (bundledApp) {
7193                // If "/system/lib64/apkname" exists, assume that is the per-package
7194                // native library directory to use; otherwise use "/system/lib/apkname".
7195                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
7196                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
7197                        getPrimaryInstructionSet(info));
7198
7199                // This is a bundled system app so choose the path based on the ABI.
7200                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
7201                // is just the default path.
7202                final String apkName = deriveCodePathName(codePath);
7203                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
7204                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
7205                        apkName).getAbsolutePath();
7206
7207                if (info.secondaryCpuAbi != null) {
7208                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7209                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7210                            secondaryLibDir, apkName).getAbsolutePath();
7211                }
7212            } else if (asecApp) {
7213                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
7214                        .getAbsolutePath();
7215            } else {
7216                final String apkName = deriveCodePathName(codePath);
7217                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
7218                        .getAbsolutePath();
7219            }
7220
7221            info.nativeLibraryRootRequiresIsa = false;
7222            info.nativeLibraryDir = info.nativeLibraryRootDir;
7223        } else {
7224            // Cluster install
7225            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7226            info.nativeLibraryRootRequiresIsa = true;
7227
7228            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7229                    getPrimaryInstructionSet(info)).getAbsolutePath();
7230
7231            if (info.secondaryCpuAbi != null) {
7232                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7233                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7234            }
7235        }
7236    }
7237
7238    /**
7239     * Calculate the abis and roots for a bundled app. These can uniquely
7240     * be determined from the contents of the system partition, i.e whether
7241     * it contains 64 or 32 bit shared libraries etc. We do not validate any
7242     * of this information, and instead assume that the system was built
7243     * sensibly.
7244     */
7245    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
7246                                           PackageSetting pkgSetting) {
7247        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
7248
7249        // If "/system/lib64/apkname" exists, assume that is the per-package
7250        // native library directory to use; otherwise use "/system/lib/apkname".
7251        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
7252        setBundledAppAbi(pkg, apkRoot, apkName);
7253        // pkgSetting might be null during rescan following uninstall of updates
7254        // to a bundled app, so accommodate that possibility.  The settings in
7255        // that case will be established later from the parsed package.
7256        //
7257        // If the settings aren't null, sync them up with what we've just derived.
7258        // note that apkRoot isn't stored in the package settings.
7259        if (pkgSetting != null) {
7260            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7261            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7262        }
7263    }
7264
7265    /**
7266     * Deduces the ABI of a bundled app and sets the relevant fields on the
7267     * parsed pkg object.
7268     *
7269     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
7270     *        under which system libraries are installed.
7271     * @param apkName the name of the installed package.
7272     */
7273    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7274        final File codeFile = new File(pkg.codePath);
7275
7276        final boolean has64BitLibs;
7277        final boolean has32BitLibs;
7278        if (isApkFile(codeFile)) {
7279            // Monolithic install
7280            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7281            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7282        } else {
7283            // Cluster install
7284            final File rootDir = new File(codeFile, LIB_DIR_NAME);
7285            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7286                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7287                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7288                has64BitLibs = (new File(rootDir, isa)).exists();
7289            } else {
7290                has64BitLibs = false;
7291            }
7292            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7293                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7294                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7295                has32BitLibs = (new File(rootDir, isa)).exists();
7296            } else {
7297                has32BitLibs = false;
7298            }
7299        }
7300
7301        if (has64BitLibs && !has32BitLibs) {
7302            // The package has 64 bit libs, but not 32 bit libs. Its primary
7303            // ABI should be 64 bit. We can safely assume here that the bundled
7304            // native libraries correspond to the most preferred ABI in the list.
7305
7306            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7307            pkg.applicationInfo.secondaryCpuAbi = null;
7308        } else if (has32BitLibs && !has64BitLibs) {
7309            // The package has 32 bit libs but not 64 bit libs. Its primary
7310            // ABI should be 32 bit.
7311
7312            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7313            pkg.applicationInfo.secondaryCpuAbi = null;
7314        } else if (has32BitLibs && has64BitLibs) {
7315            // The application has both 64 and 32 bit bundled libraries. We check
7316            // here that the app declares multiArch support, and warn if it doesn't.
7317            //
7318            // We will be lenient here and record both ABIs. The primary will be the
7319            // ABI that's higher on the list, i.e, a device that's configured to prefer
7320            // 64 bit apps will see a 64 bit primary ABI,
7321
7322            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
7323                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
7324            }
7325
7326            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
7327                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7328                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7329            } else {
7330                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7331                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7332            }
7333        } else {
7334            pkg.applicationInfo.primaryCpuAbi = null;
7335            pkg.applicationInfo.secondaryCpuAbi = null;
7336        }
7337    }
7338
7339    private void killApplication(String pkgName, int appId, String reason) {
7340        // Request the ActivityManager to kill the process(only for existing packages)
7341        // so that we do not end up in a confused state while the user is still using the older
7342        // version of the application while the new one gets installed.
7343        IActivityManager am = ActivityManagerNative.getDefault();
7344        if (am != null) {
7345            try {
7346                am.killApplicationWithAppId(pkgName, appId, reason);
7347            } catch (RemoteException e) {
7348            }
7349        }
7350    }
7351
7352    void removePackageLI(PackageSetting ps, boolean chatty) {
7353        if (DEBUG_INSTALL) {
7354            if (chatty)
7355                Log.d(TAG, "Removing package " + ps.name);
7356        }
7357
7358        // writer
7359        synchronized (mPackages) {
7360            mPackages.remove(ps.name);
7361            final PackageParser.Package pkg = ps.pkg;
7362            if (pkg != null) {
7363                cleanPackageDataStructuresLILPw(pkg, chatty);
7364            }
7365        }
7366    }
7367
7368    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
7369        if (DEBUG_INSTALL) {
7370            if (chatty)
7371                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
7372        }
7373
7374        // writer
7375        synchronized (mPackages) {
7376            mPackages.remove(pkg.applicationInfo.packageName);
7377            cleanPackageDataStructuresLILPw(pkg, chatty);
7378        }
7379    }
7380
7381    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
7382        int N = pkg.providers.size();
7383        StringBuilder r = null;
7384        int i;
7385        for (i=0; i<N; i++) {
7386            PackageParser.Provider p = pkg.providers.get(i);
7387            mProviders.removeProvider(p);
7388            if (p.info.authority == null) {
7389
7390                /* There was another ContentProvider with this authority when
7391                 * this app was installed so this authority is null,
7392                 * Ignore it as we don't have to unregister the provider.
7393                 */
7394                continue;
7395            }
7396            String names[] = p.info.authority.split(";");
7397            for (int j = 0; j < names.length; j++) {
7398                if (mProvidersByAuthority.get(names[j]) == p) {
7399                    mProvidersByAuthority.remove(names[j]);
7400                    if (DEBUG_REMOVE) {
7401                        if (chatty)
7402                            Log.d(TAG, "Unregistered content provider: " + names[j]
7403                                    + ", className = " + p.info.name + ", isSyncable = "
7404                                    + p.info.isSyncable);
7405                    }
7406                }
7407            }
7408            if (DEBUG_REMOVE && chatty) {
7409                if (r == null) {
7410                    r = new StringBuilder(256);
7411                } else {
7412                    r.append(' ');
7413                }
7414                r.append(p.info.name);
7415            }
7416        }
7417        if (r != null) {
7418            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
7419        }
7420
7421        N = pkg.services.size();
7422        r = null;
7423        for (i=0; i<N; i++) {
7424            PackageParser.Service s = pkg.services.get(i);
7425            mServices.removeService(s);
7426            if (chatty) {
7427                if (r == null) {
7428                    r = new StringBuilder(256);
7429                } else {
7430                    r.append(' ');
7431                }
7432                r.append(s.info.name);
7433            }
7434        }
7435        if (r != null) {
7436            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
7437        }
7438
7439        N = pkg.receivers.size();
7440        r = null;
7441        for (i=0; i<N; i++) {
7442            PackageParser.Activity a = pkg.receivers.get(i);
7443            mReceivers.removeActivity(a, "receiver");
7444            if (DEBUG_REMOVE && chatty) {
7445                if (r == null) {
7446                    r = new StringBuilder(256);
7447                } else {
7448                    r.append(' ');
7449                }
7450                r.append(a.info.name);
7451            }
7452        }
7453        if (r != null) {
7454            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
7455        }
7456
7457        N = pkg.activities.size();
7458        r = null;
7459        for (i=0; i<N; i++) {
7460            PackageParser.Activity a = pkg.activities.get(i);
7461            mActivities.removeActivity(a, "activity");
7462            if (DEBUG_REMOVE && chatty) {
7463                if (r == null) {
7464                    r = new StringBuilder(256);
7465                } else {
7466                    r.append(' ');
7467                }
7468                r.append(a.info.name);
7469            }
7470        }
7471        if (r != null) {
7472            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
7473        }
7474
7475        N = pkg.permissions.size();
7476        r = null;
7477        for (i=0; i<N; i++) {
7478            PackageParser.Permission p = pkg.permissions.get(i);
7479            BasePermission bp = mSettings.mPermissions.get(p.info.name);
7480            if (bp == null) {
7481                bp = mSettings.mPermissionTrees.get(p.info.name);
7482            }
7483            if (bp != null && bp.perm == p) {
7484                bp.perm = null;
7485                if (DEBUG_REMOVE && chatty) {
7486                    if (r == null) {
7487                        r = new StringBuilder(256);
7488                    } else {
7489                        r.append(' ');
7490                    }
7491                    r.append(p.info.name);
7492                }
7493            }
7494            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7495                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
7496                if (appOpPerms != null) {
7497                    appOpPerms.remove(pkg.packageName);
7498                }
7499            }
7500        }
7501        if (r != null) {
7502            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
7503        }
7504
7505        N = pkg.requestedPermissions.size();
7506        r = null;
7507        for (i=0; i<N; i++) {
7508            String perm = pkg.requestedPermissions.get(i);
7509            BasePermission bp = mSettings.mPermissions.get(perm);
7510            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7511                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
7512                if (appOpPerms != null) {
7513                    appOpPerms.remove(pkg.packageName);
7514                    if (appOpPerms.isEmpty()) {
7515                        mAppOpPermissionPackages.remove(perm);
7516                    }
7517                }
7518            }
7519        }
7520        if (r != null) {
7521            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
7522        }
7523
7524        N = pkg.instrumentation.size();
7525        r = null;
7526        for (i=0; i<N; i++) {
7527            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7528            mInstrumentation.remove(a.getComponentName());
7529            if (DEBUG_REMOVE && chatty) {
7530                if (r == null) {
7531                    r = new StringBuilder(256);
7532                } else {
7533                    r.append(' ');
7534                }
7535                r.append(a.info.name);
7536            }
7537        }
7538        if (r != null) {
7539            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
7540        }
7541
7542        r = null;
7543        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7544            // Only system apps can hold shared libraries.
7545            if (pkg.libraryNames != null) {
7546                for (i=0; i<pkg.libraryNames.size(); i++) {
7547                    String name = pkg.libraryNames.get(i);
7548                    SharedLibraryEntry cur = mSharedLibraries.get(name);
7549                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
7550                        mSharedLibraries.remove(name);
7551                        if (DEBUG_REMOVE && chatty) {
7552                            if (r == null) {
7553                                r = new StringBuilder(256);
7554                            } else {
7555                                r.append(' ');
7556                            }
7557                            r.append(name);
7558                        }
7559                    }
7560                }
7561            }
7562        }
7563        if (r != null) {
7564            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
7565        }
7566    }
7567
7568    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
7569        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
7570            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
7571                return true;
7572            }
7573        }
7574        return false;
7575    }
7576
7577    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
7578    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
7579    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
7580
7581    private void updatePermissionsLPw(String changingPkg,
7582            PackageParser.Package pkgInfo, int flags) {
7583        // Make sure there are no dangling permission trees.
7584        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
7585        while (it.hasNext()) {
7586            final BasePermission bp = it.next();
7587            if (bp.packageSetting == null) {
7588                // We may not yet have parsed the package, so just see if
7589                // we still know about its settings.
7590                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
7591            }
7592            if (bp.packageSetting == null) {
7593                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
7594                        + " from package " + bp.sourcePackage);
7595                it.remove();
7596            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
7597                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
7598                    Slog.i(TAG, "Removing old permission tree: " + bp.name
7599                            + " from package " + bp.sourcePackage);
7600                    flags |= UPDATE_PERMISSIONS_ALL;
7601                    it.remove();
7602                }
7603            }
7604        }
7605
7606        // Make sure all dynamic permissions have been assigned to a package,
7607        // and make sure there are no dangling permissions.
7608        it = mSettings.mPermissions.values().iterator();
7609        while (it.hasNext()) {
7610            final BasePermission bp = it.next();
7611            if (bp.type == BasePermission.TYPE_DYNAMIC) {
7612                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
7613                        + bp.name + " pkg=" + bp.sourcePackage
7614                        + " info=" + bp.pendingInfo);
7615                if (bp.packageSetting == null && bp.pendingInfo != null) {
7616                    final BasePermission tree = findPermissionTreeLP(bp.name);
7617                    if (tree != null && tree.perm != null) {
7618                        bp.packageSetting = tree.packageSetting;
7619                        bp.perm = new PackageParser.Permission(tree.perm.owner,
7620                                new PermissionInfo(bp.pendingInfo));
7621                        bp.perm.info.packageName = tree.perm.info.packageName;
7622                        bp.perm.info.name = bp.name;
7623                        bp.uid = tree.uid;
7624                    }
7625                }
7626            }
7627            if (bp.packageSetting == null) {
7628                // We may not yet have parsed the package, so just see if
7629                // we still know about its settings.
7630                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
7631            }
7632            if (bp.packageSetting == null) {
7633                Slog.w(TAG, "Removing dangling permission: " + bp.name
7634                        + " from package " + bp.sourcePackage);
7635                it.remove();
7636            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
7637                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
7638                    Slog.i(TAG, "Removing old permission: " + bp.name
7639                            + " from package " + bp.sourcePackage);
7640                    flags |= UPDATE_PERMISSIONS_ALL;
7641                    it.remove();
7642                }
7643            }
7644        }
7645
7646        // Now update the permissions for all packages, in particular
7647        // replace the granted permissions of the system packages.
7648        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
7649            for (PackageParser.Package pkg : mPackages.values()) {
7650                if (pkg != pkgInfo) {
7651                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
7652                            changingPkg);
7653                }
7654            }
7655        }
7656
7657        if (pkgInfo != null) {
7658            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
7659        }
7660    }
7661
7662    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
7663            String packageOfInterest) {
7664        // IMPORTANT: There are two types of permissions: install and runtime.
7665        // Install time permissions are granted when the app is installed to
7666        // all device users and users added in the future. Runtime permissions
7667        // are granted at runtime explicitly to specific users. Normal and signature
7668        // protected permissions are install time permissions. Dangerous permissions
7669        // are install permissions if the app's target SDK is Lollipop MR1 or older,
7670        // otherwise they are runtime permissions. This function does not manage
7671        // runtime permissions except for the case an app targeting Lollipop MR1
7672        // being upgraded to target a newer SDK, in which case dangerous permissions
7673        // are transformed from install time to runtime ones.
7674
7675        final PackageSetting ps = (PackageSetting) pkg.mExtras;
7676        if (ps == null) {
7677            return;
7678        }
7679
7680        PermissionsState permissionsState = ps.getPermissionsState();
7681        PermissionsState origPermissions = permissionsState;
7682
7683        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
7684
7685        int[] upgradeUserIds = EMPTY_INT_ARRAY;
7686        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
7687
7688        boolean changedInstallPermission = false;
7689
7690        if (replace) {
7691            ps.installPermissionsFixed = false;
7692            if (!ps.isSharedUser()) {
7693                origPermissions = new PermissionsState(permissionsState);
7694                permissionsState.reset();
7695            }
7696        }
7697
7698        permissionsState.setGlobalGids(mGlobalGids);
7699
7700        final int N = pkg.requestedPermissions.size();
7701        for (int i=0; i<N; i++) {
7702            final String name = pkg.requestedPermissions.get(i);
7703            final BasePermission bp = mSettings.mPermissions.get(name);
7704
7705            if (DEBUG_INSTALL) {
7706                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
7707            }
7708
7709            if (bp == null || bp.packageSetting == null) {
7710                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7711                    Slog.w(TAG, "Unknown permission " + name
7712                            + " in package " + pkg.packageName);
7713                }
7714                continue;
7715            }
7716
7717            final String perm = bp.name;
7718            boolean allowedSig = false;
7719            int grant = GRANT_DENIED;
7720
7721            // Keep track of app op permissions.
7722            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7723                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
7724                if (pkgs == null) {
7725                    pkgs = new ArraySet<>();
7726                    mAppOpPermissionPackages.put(bp.name, pkgs);
7727                }
7728                pkgs.add(pkg.packageName);
7729            }
7730
7731            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
7732            switch (level) {
7733                case PermissionInfo.PROTECTION_NORMAL: {
7734                    // For all apps normal permissions are install time ones.
7735                    grant = GRANT_INSTALL;
7736                } break;
7737
7738                case PermissionInfo.PROTECTION_DANGEROUS: {
7739                    if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
7740                        // For legacy apps dangerous permissions are install time ones.
7741                        grant = GRANT_INSTALL;
7742                    } else if (ps.isSystem()) {
7743                        final int[] updatedUserIds = ps.getPermissionsUpdatedForUserIds();
7744                        if (origPermissions.hasInstallPermission(bp.name)) {
7745                            // If a system app had an install permission, then the app was
7746                            // upgraded and we grant the permissions as runtime to all users.
7747                            grant = GRANT_UPGRADE;
7748                            upgradeUserIds = currentUserIds;
7749                        } else if (!Arrays.equals(updatedUserIds, currentUserIds)) {
7750                            // If users changed since the last permissions update for a
7751                            // system app, we grant the permission as runtime to the new users.
7752                            grant = GRANT_UPGRADE;
7753                            upgradeUserIds = currentUserIds;
7754                            for (int userId : updatedUserIds) {
7755                                upgradeUserIds = ArrayUtils.removeInt(upgradeUserIds, userId);
7756                            }
7757                        } else {
7758                            // Otherwise, we grant the permission as runtime if the app
7759                            // already had it, i.e. we preserve runtime permissions.
7760                            grant = GRANT_RUNTIME;
7761                        }
7762                    } else if (origPermissions.hasInstallPermission(bp.name)) {
7763                        // For legacy apps that became modern, install becomes runtime.
7764                        grant = GRANT_UPGRADE;
7765                        upgradeUserIds = currentUserIds;
7766                    } else if (replace) {
7767                        // For upgraded modern apps keep runtime permissions unchanged.
7768                        grant = GRANT_RUNTIME;
7769                    }
7770                } break;
7771
7772                case PermissionInfo.PROTECTION_SIGNATURE: {
7773                    // For all apps signature permissions are install time ones.
7774                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
7775                    if (allowedSig) {
7776                        grant = GRANT_INSTALL;
7777                    }
7778                } break;
7779            }
7780
7781            if (DEBUG_INSTALL) {
7782                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
7783            }
7784
7785            if (grant != GRANT_DENIED) {
7786                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
7787                    // If this is an existing, non-system package, then
7788                    // we can't add any new permissions to it.
7789                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
7790                        // Except...  if this is a permission that was added
7791                        // to the platform (note: need to only do this when
7792                        // updating the platform).
7793                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
7794                            grant = GRANT_DENIED;
7795                        }
7796                    }
7797                }
7798
7799                switch (grant) {
7800                    case GRANT_INSTALL: {
7801                        // Grant an install permission.
7802                        if (permissionsState.grantInstallPermission(bp) !=
7803                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
7804                            changedInstallPermission = true;
7805                        }
7806                    } break;
7807
7808                    case GRANT_RUNTIME: {
7809                        // Grant previously granted runtime permissions.
7810                        for (int userId : UserManagerService.getInstance().getUserIds()) {
7811                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
7812                                PermissionState permissionState = origPermissions
7813                                        .getRuntimePermissionState(bp.name, userId);
7814                                final int flags = permissionState.getFlags();
7815                                if (permissionsState.grantRuntimePermission(bp, userId) ==
7816                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
7817                                    // If we cannot put the permission as it was, we have to write.
7818                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
7819                                            changedRuntimePermissionUserIds, userId);
7820                                } else {
7821                                    // System components not only get the permissions but
7822                                    // they are also fixed, so nothing can change that.
7823                                    final int newFlags = !isSystemComponentOrPersistentPrivApp(pkg)
7824                                            ? flags
7825                                            : flags | PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
7826                                    // Propagate the permission flags.
7827                                    permissionsState.updatePermissionFlags(bp, userId,
7828                                            newFlags, newFlags);
7829                                }
7830                            }
7831                        }
7832                    } break;
7833
7834                    case GRANT_UPGRADE: {
7835                        // Grant runtime permissions for a previously held install permission.
7836                        PermissionState permissionState = origPermissions
7837                                .getInstallPermissionState(bp.name);
7838                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
7839
7840                        origPermissions.revokeInstallPermission(bp);
7841                        // We will be transferring the permission flags, so clear them.
7842                        origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
7843                                PackageManager.MASK_PERMISSION_FLAGS, 0);
7844
7845                        // If the permission is not to be promoted to runtime we ignore it and
7846                        // also its other flags as they are not applicable to install permissions.
7847                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
7848                            for (int userId : upgradeUserIds) {
7849                                if (permissionsState.grantRuntimePermission(bp, userId) !=
7850                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
7851                                    // System components not only get the permissions but
7852                                    // they are also fixed so nothing can change that.
7853                                    final int newFlags = !isSystemComponentOrPersistentPrivApp(pkg)
7854                                            ? flags
7855                                            : flags | PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
7856                                    // Transfer the permission flags.
7857                                    permissionsState.updatePermissionFlags(bp, userId,
7858                                            newFlags, newFlags);
7859                                    // If we granted the permission, we have to write.
7860                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
7861                                            changedRuntimePermissionUserIds, userId);
7862                                }
7863                            }
7864                        }
7865                    } break;
7866
7867                    default: {
7868                        if (packageOfInterest == null
7869                                || packageOfInterest.equals(pkg.packageName)) {
7870                            Slog.w(TAG, "Not granting permission " + perm
7871                                    + " to package " + pkg.packageName
7872                                    + " because it was previously installed without");
7873                        }
7874                    } break;
7875                }
7876            } else {
7877                if (permissionsState.revokeInstallPermission(bp) !=
7878                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
7879                    // Also drop the permission flags.
7880                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
7881                            PackageManager.MASK_PERMISSION_FLAGS, 0);
7882                    changedInstallPermission = true;
7883                    Slog.i(TAG, "Un-granting permission " + perm
7884                            + " from package " + pkg.packageName
7885                            + " (protectionLevel=" + bp.protectionLevel
7886                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
7887                            + ")");
7888                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
7889                    // Don't print warning for app op permissions, since it is fine for them
7890                    // not to be granted, there is a UI for the user to decide.
7891                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7892                        Slog.w(TAG, "Not granting permission " + perm
7893                                + " to package " + pkg.packageName
7894                                + " (protectionLevel=" + bp.protectionLevel
7895                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
7896                                + ")");
7897                    }
7898                }
7899            }
7900        }
7901
7902        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
7903                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
7904            // This is the first that we have heard about this package, so the
7905            // permissions we have now selected are fixed until explicitly
7906            // changed.
7907            ps.installPermissionsFixed = true;
7908        }
7909
7910        ps.setPermissionsUpdatedForUserIds(currentUserIds);
7911
7912        // Persist the runtime permissions state for users with changes.
7913        for (int userId : changedRuntimePermissionUserIds) {
7914            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
7915        }
7916    }
7917
7918    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
7919        boolean allowed = false;
7920        final int NP = PackageParser.NEW_PERMISSIONS.length;
7921        for (int ip=0; ip<NP; ip++) {
7922            final PackageParser.NewPermissionInfo npi
7923                    = PackageParser.NEW_PERMISSIONS[ip];
7924            if (npi.name.equals(perm)
7925                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
7926                allowed = true;
7927                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
7928                        + pkg.packageName);
7929                break;
7930            }
7931        }
7932        return allowed;
7933    }
7934
7935    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
7936            BasePermission bp, PermissionsState origPermissions) {
7937        boolean allowed;
7938        allowed = (compareSignatures(
7939                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
7940                        == PackageManager.SIGNATURE_MATCH)
7941                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
7942                        == PackageManager.SIGNATURE_MATCH);
7943        if (!allowed && (bp.protectionLevel
7944                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
7945            if (isSystemApp(pkg)) {
7946                // For updated system applications, a system permission
7947                // is granted only if it had been defined by the original application.
7948                if (pkg.isUpdatedSystemApp()) {
7949                    final PackageSetting sysPs = mSettings
7950                            .getDisabledSystemPkgLPr(pkg.packageName);
7951                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
7952                        // If the original was granted this permission, we take
7953                        // that grant decision as read and propagate it to the
7954                        // update.
7955                        if (sysPs.isPrivileged()) {
7956                            allowed = true;
7957                        }
7958                    } else {
7959                        // The system apk may have been updated with an older
7960                        // version of the one on the data partition, but which
7961                        // granted a new system permission that it didn't have
7962                        // before.  In this case we do want to allow the app to
7963                        // now get the new permission if the ancestral apk is
7964                        // privileged to get it.
7965                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
7966                            for (int j=0;
7967                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
7968                                if (perm.equals(
7969                                        sysPs.pkg.requestedPermissions.get(j))) {
7970                                    allowed = true;
7971                                    break;
7972                                }
7973                            }
7974                        }
7975                    }
7976                } else {
7977                    allowed = isPrivilegedApp(pkg);
7978                }
7979            }
7980        }
7981        if (!allowed && (bp.protectionLevel
7982                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
7983            // For development permissions, a development permission
7984            // is granted only if it was already granted.
7985            allowed = origPermissions.hasInstallPermission(perm);
7986        }
7987        return allowed;
7988    }
7989
7990    final class ActivityIntentResolver
7991            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
7992        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7993                boolean defaultOnly, int userId) {
7994            if (!sUserManager.exists(userId)) return null;
7995            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7996            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7997        }
7998
7999        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8000                int userId) {
8001            if (!sUserManager.exists(userId)) return null;
8002            mFlags = flags;
8003            return super.queryIntent(intent, resolvedType,
8004                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8005        }
8006
8007        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8008                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8009            if (!sUserManager.exists(userId)) return null;
8010            if (packageActivities == null) {
8011                return null;
8012            }
8013            mFlags = flags;
8014            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8015            final int N = packageActivities.size();
8016            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8017                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8018
8019            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8020            for (int i = 0; i < N; ++i) {
8021                intentFilters = packageActivities.get(i).intents;
8022                if (intentFilters != null && intentFilters.size() > 0) {
8023                    PackageParser.ActivityIntentInfo[] array =
8024                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
8025                    intentFilters.toArray(array);
8026                    listCut.add(array);
8027                }
8028            }
8029            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8030        }
8031
8032        public final void addActivity(PackageParser.Activity a, String type) {
8033            final boolean systemApp = a.info.applicationInfo.isSystemApp();
8034            mActivities.put(a.getComponentName(), a);
8035            if (DEBUG_SHOW_INFO)
8036                Log.v(
8037                TAG, "  " + type + " " +
8038                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8039            if (DEBUG_SHOW_INFO)
8040                Log.v(TAG, "    Class=" + a.info.name);
8041            final int NI = a.intents.size();
8042            for (int j=0; j<NI; j++) {
8043                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8044                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
8045                    intent.setPriority(0);
8046                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
8047                            + a.className + " with priority > 0, forcing to 0");
8048                }
8049                if (DEBUG_SHOW_INFO) {
8050                    Log.v(TAG, "    IntentFilter:");
8051                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8052                }
8053                if (!intent.debugCheck()) {
8054                    Log.w(TAG, "==> For Activity " + a.info.name);
8055                }
8056                addFilter(intent);
8057            }
8058        }
8059
8060        public final void removeActivity(PackageParser.Activity a, String type) {
8061            mActivities.remove(a.getComponentName());
8062            if (DEBUG_SHOW_INFO) {
8063                Log.v(TAG, "  " + type + " "
8064                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
8065                                : a.info.name) + ":");
8066                Log.v(TAG, "    Class=" + a.info.name);
8067            }
8068            final int NI = a.intents.size();
8069            for (int j=0; j<NI; j++) {
8070                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8071                if (DEBUG_SHOW_INFO) {
8072                    Log.v(TAG, "    IntentFilter:");
8073                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8074                }
8075                removeFilter(intent);
8076            }
8077        }
8078
8079        @Override
8080        protected boolean allowFilterResult(
8081                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
8082            ActivityInfo filterAi = filter.activity.info;
8083            for (int i=dest.size()-1; i>=0; i--) {
8084                ActivityInfo destAi = dest.get(i).activityInfo;
8085                if (destAi.name == filterAi.name
8086                        && destAi.packageName == filterAi.packageName) {
8087                    return false;
8088                }
8089            }
8090            return true;
8091        }
8092
8093        @Override
8094        protected ActivityIntentInfo[] newArray(int size) {
8095            return new ActivityIntentInfo[size];
8096        }
8097
8098        @Override
8099        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
8100            if (!sUserManager.exists(userId)) return true;
8101            PackageParser.Package p = filter.activity.owner;
8102            if (p != null) {
8103                PackageSetting ps = (PackageSetting)p.mExtras;
8104                if (ps != null) {
8105                    // System apps are never considered stopped for purposes of
8106                    // filtering, because there may be no way for the user to
8107                    // actually re-launch them.
8108                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
8109                            && ps.getStopped(userId);
8110                }
8111            }
8112            return false;
8113        }
8114
8115        @Override
8116        protected boolean isPackageForFilter(String packageName,
8117                PackageParser.ActivityIntentInfo info) {
8118            return packageName.equals(info.activity.owner.packageName);
8119        }
8120
8121        @Override
8122        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
8123                int match, int userId) {
8124            if (!sUserManager.exists(userId)) return null;
8125            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
8126                return null;
8127            }
8128            final PackageParser.Activity activity = info.activity;
8129            if (mSafeMode && (activity.info.applicationInfo.flags
8130                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8131                return null;
8132            }
8133            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
8134            if (ps == null) {
8135                return null;
8136            }
8137            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
8138                    ps.readUserState(userId), userId);
8139            if (ai == null) {
8140                return null;
8141            }
8142            final ResolveInfo res = new ResolveInfo();
8143            res.activityInfo = ai;
8144            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8145                res.filter = info;
8146            }
8147            if (info != null) {
8148                res.handleAllWebDataURI = info.handleAllWebDataURI();
8149            }
8150            res.priority = info.getPriority();
8151            res.preferredOrder = activity.owner.mPreferredOrder;
8152            //System.out.println("Result: " + res.activityInfo.className +
8153            //                   " = " + res.priority);
8154            res.match = match;
8155            res.isDefault = info.hasDefault;
8156            res.labelRes = info.labelRes;
8157            res.nonLocalizedLabel = info.nonLocalizedLabel;
8158            if (userNeedsBadging(userId)) {
8159                res.noResourceId = true;
8160            } else {
8161                res.icon = info.icon;
8162            }
8163            res.iconResourceId = info.icon;
8164            res.system = res.activityInfo.applicationInfo.isSystemApp();
8165            return res;
8166        }
8167
8168        @Override
8169        protected void sortResults(List<ResolveInfo> results) {
8170            Collections.sort(results, mResolvePrioritySorter);
8171        }
8172
8173        @Override
8174        protected void dumpFilter(PrintWriter out, String prefix,
8175                PackageParser.ActivityIntentInfo filter) {
8176            out.print(prefix); out.print(
8177                    Integer.toHexString(System.identityHashCode(filter.activity)));
8178                    out.print(' ');
8179                    filter.activity.printComponentShortName(out);
8180                    out.print(" filter ");
8181                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8182        }
8183
8184        @Override
8185        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
8186            return filter.activity;
8187        }
8188
8189        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8190            PackageParser.Activity activity = (PackageParser.Activity)label;
8191            out.print(prefix); out.print(
8192                    Integer.toHexString(System.identityHashCode(activity)));
8193                    out.print(' ');
8194                    activity.printComponentShortName(out);
8195            if (count > 1) {
8196                out.print(" ("); out.print(count); out.print(" filters)");
8197            }
8198            out.println();
8199        }
8200
8201//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8202//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8203//            final List<ResolveInfo> retList = Lists.newArrayList();
8204//            while (i.hasNext()) {
8205//                final ResolveInfo resolveInfo = i.next();
8206//                if (isEnabledLP(resolveInfo.activityInfo)) {
8207//                    retList.add(resolveInfo);
8208//                }
8209//            }
8210//            return retList;
8211//        }
8212
8213        // Keys are String (activity class name), values are Activity.
8214        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
8215                = new ArrayMap<ComponentName, PackageParser.Activity>();
8216        private int mFlags;
8217    }
8218
8219    private final class ServiceIntentResolver
8220            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
8221        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8222                boolean defaultOnly, int userId) {
8223            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8224            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8225        }
8226
8227        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8228                int userId) {
8229            if (!sUserManager.exists(userId)) return null;
8230            mFlags = flags;
8231            return super.queryIntent(intent, resolvedType,
8232                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8233        }
8234
8235        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8236                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
8237            if (!sUserManager.exists(userId)) return null;
8238            if (packageServices == null) {
8239                return null;
8240            }
8241            mFlags = flags;
8242            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8243            final int N = packageServices.size();
8244            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
8245                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
8246
8247            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
8248            for (int i = 0; i < N; ++i) {
8249                intentFilters = packageServices.get(i).intents;
8250                if (intentFilters != null && intentFilters.size() > 0) {
8251                    PackageParser.ServiceIntentInfo[] array =
8252                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
8253                    intentFilters.toArray(array);
8254                    listCut.add(array);
8255                }
8256            }
8257            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8258        }
8259
8260        public final void addService(PackageParser.Service s) {
8261            mServices.put(s.getComponentName(), s);
8262            if (DEBUG_SHOW_INFO) {
8263                Log.v(TAG, "  "
8264                        + (s.info.nonLocalizedLabel != null
8265                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8266                Log.v(TAG, "    Class=" + s.info.name);
8267            }
8268            final int NI = s.intents.size();
8269            int j;
8270            for (j=0; j<NI; j++) {
8271                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8272                if (DEBUG_SHOW_INFO) {
8273                    Log.v(TAG, "    IntentFilter:");
8274                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8275                }
8276                if (!intent.debugCheck()) {
8277                    Log.w(TAG, "==> For Service " + s.info.name);
8278                }
8279                addFilter(intent);
8280            }
8281        }
8282
8283        public final void removeService(PackageParser.Service s) {
8284            mServices.remove(s.getComponentName());
8285            if (DEBUG_SHOW_INFO) {
8286                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
8287                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8288                Log.v(TAG, "    Class=" + s.info.name);
8289            }
8290            final int NI = s.intents.size();
8291            int j;
8292            for (j=0; j<NI; j++) {
8293                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8294                if (DEBUG_SHOW_INFO) {
8295                    Log.v(TAG, "    IntentFilter:");
8296                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8297                }
8298                removeFilter(intent);
8299            }
8300        }
8301
8302        @Override
8303        protected boolean allowFilterResult(
8304                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
8305            ServiceInfo filterSi = filter.service.info;
8306            for (int i=dest.size()-1; i>=0; i--) {
8307                ServiceInfo destAi = dest.get(i).serviceInfo;
8308                if (destAi.name == filterSi.name
8309                        && destAi.packageName == filterSi.packageName) {
8310                    return false;
8311                }
8312            }
8313            return true;
8314        }
8315
8316        @Override
8317        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
8318            return new PackageParser.ServiceIntentInfo[size];
8319        }
8320
8321        @Override
8322        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
8323            if (!sUserManager.exists(userId)) return true;
8324            PackageParser.Package p = filter.service.owner;
8325            if (p != null) {
8326                PackageSetting ps = (PackageSetting)p.mExtras;
8327                if (ps != null) {
8328                    // System apps are never considered stopped for purposes of
8329                    // filtering, because there may be no way for the user to
8330                    // actually re-launch them.
8331                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8332                            && ps.getStopped(userId);
8333                }
8334            }
8335            return false;
8336        }
8337
8338        @Override
8339        protected boolean isPackageForFilter(String packageName,
8340                PackageParser.ServiceIntentInfo info) {
8341            return packageName.equals(info.service.owner.packageName);
8342        }
8343
8344        @Override
8345        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
8346                int match, int userId) {
8347            if (!sUserManager.exists(userId)) return null;
8348            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
8349            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
8350                return null;
8351            }
8352            final PackageParser.Service service = info.service;
8353            if (mSafeMode && (service.info.applicationInfo.flags
8354                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8355                return null;
8356            }
8357            PackageSetting ps = (PackageSetting) service.owner.mExtras;
8358            if (ps == null) {
8359                return null;
8360            }
8361            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
8362                    ps.readUserState(userId), userId);
8363            if (si == null) {
8364                return null;
8365            }
8366            final ResolveInfo res = new ResolveInfo();
8367            res.serviceInfo = si;
8368            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8369                res.filter = filter;
8370            }
8371            res.priority = info.getPriority();
8372            res.preferredOrder = service.owner.mPreferredOrder;
8373            res.match = match;
8374            res.isDefault = info.hasDefault;
8375            res.labelRes = info.labelRes;
8376            res.nonLocalizedLabel = info.nonLocalizedLabel;
8377            res.icon = info.icon;
8378            res.system = res.serviceInfo.applicationInfo.isSystemApp();
8379            return res;
8380        }
8381
8382        @Override
8383        protected void sortResults(List<ResolveInfo> results) {
8384            Collections.sort(results, mResolvePrioritySorter);
8385        }
8386
8387        @Override
8388        protected void dumpFilter(PrintWriter out, String prefix,
8389                PackageParser.ServiceIntentInfo filter) {
8390            out.print(prefix); out.print(
8391                    Integer.toHexString(System.identityHashCode(filter.service)));
8392                    out.print(' ');
8393                    filter.service.printComponentShortName(out);
8394                    out.print(" filter ");
8395                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8396        }
8397
8398        @Override
8399        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
8400            return filter.service;
8401        }
8402
8403        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8404            PackageParser.Service service = (PackageParser.Service)label;
8405            out.print(prefix); out.print(
8406                    Integer.toHexString(System.identityHashCode(service)));
8407                    out.print(' ');
8408                    service.printComponentShortName(out);
8409            if (count > 1) {
8410                out.print(" ("); out.print(count); out.print(" filters)");
8411            }
8412            out.println();
8413        }
8414
8415//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8416//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8417//            final List<ResolveInfo> retList = Lists.newArrayList();
8418//            while (i.hasNext()) {
8419//                final ResolveInfo resolveInfo = (ResolveInfo) i;
8420//                if (isEnabledLP(resolveInfo.serviceInfo)) {
8421//                    retList.add(resolveInfo);
8422//                }
8423//            }
8424//            return retList;
8425//        }
8426
8427        // Keys are String (activity class name), values are Activity.
8428        private final ArrayMap<ComponentName, PackageParser.Service> mServices
8429                = new ArrayMap<ComponentName, PackageParser.Service>();
8430        private int mFlags;
8431    };
8432
8433    private final class ProviderIntentResolver
8434            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
8435        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8436                boolean defaultOnly, int userId) {
8437            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8438            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8439        }
8440
8441        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8442                int userId) {
8443            if (!sUserManager.exists(userId))
8444                return null;
8445            mFlags = flags;
8446            return super.queryIntent(intent, resolvedType,
8447                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8448        }
8449
8450        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8451                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
8452            if (!sUserManager.exists(userId))
8453                return null;
8454            if (packageProviders == null) {
8455                return null;
8456            }
8457            mFlags = flags;
8458            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
8459            final int N = packageProviders.size();
8460            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
8461                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
8462
8463            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
8464            for (int i = 0; i < N; ++i) {
8465                intentFilters = packageProviders.get(i).intents;
8466                if (intentFilters != null && intentFilters.size() > 0) {
8467                    PackageParser.ProviderIntentInfo[] array =
8468                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
8469                    intentFilters.toArray(array);
8470                    listCut.add(array);
8471                }
8472            }
8473            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8474        }
8475
8476        public final void addProvider(PackageParser.Provider p) {
8477            if (mProviders.containsKey(p.getComponentName())) {
8478                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
8479                return;
8480            }
8481
8482            mProviders.put(p.getComponentName(), p);
8483            if (DEBUG_SHOW_INFO) {
8484                Log.v(TAG, "  "
8485                        + (p.info.nonLocalizedLabel != null
8486                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
8487                Log.v(TAG, "    Class=" + p.info.name);
8488            }
8489            final int NI = p.intents.size();
8490            int j;
8491            for (j = 0; j < NI; j++) {
8492                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
8493                if (DEBUG_SHOW_INFO) {
8494                    Log.v(TAG, "    IntentFilter:");
8495                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8496                }
8497                if (!intent.debugCheck()) {
8498                    Log.w(TAG, "==> For Provider " + p.info.name);
8499                }
8500                addFilter(intent);
8501            }
8502        }
8503
8504        public final void removeProvider(PackageParser.Provider p) {
8505            mProviders.remove(p.getComponentName());
8506            if (DEBUG_SHOW_INFO) {
8507                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
8508                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
8509                Log.v(TAG, "    Class=" + p.info.name);
8510            }
8511            final int NI = p.intents.size();
8512            int j;
8513            for (j = 0; j < NI; j++) {
8514                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
8515                if (DEBUG_SHOW_INFO) {
8516                    Log.v(TAG, "    IntentFilter:");
8517                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8518                }
8519                removeFilter(intent);
8520            }
8521        }
8522
8523        @Override
8524        protected boolean allowFilterResult(
8525                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
8526            ProviderInfo filterPi = filter.provider.info;
8527            for (int i = dest.size() - 1; i >= 0; i--) {
8528                ProviderInfo destPi = dest.get(i).providerInfo;
8529                if (destPi.name == filterPi.name
8530                        && destPi.packageName == filterPi.packageName) {
8531                    return false;
8532                }
8533            }
8534            return true;
8535        }
8536
8537        @Override
8538        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
8539            return new PackageParser.ProviderIntentInfo[size];
8540        }
8541
8542        @Override
8543        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
8544            if (!sUserManager.exists(userId))
8545                return true;
8546            PackageParser.Package p = filter.provider.owner;
8547            if (p != null) {
8548                PackageSetting ps = (PackageSetting) p.mExtras;
8549                if (ps != null) {
8550                    // System apps are never considered stopped for purposes of
8551                    // filtering, because there may be no way for the user to
8552                    // actually re-launch them.
8553                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8554                            && ps.getStopped(userId);
8555                }
8556            }
8557            return false;
8558        }
8559
8560        @Override
8561        protected boolean isPackageForFilter(String packageName,
8562                PackageParser.ProviderIntentInfo info) {
8563            return packageName.equals(info.provider.owner.packageName);
8564        }
8565
8566        @Override
8567        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
8568                int match, int userId) {
8569            if (!sUserManager.exists(userId))
8570                return null;
8571            final PackageParser.ProviderIntentInfo info = filter;
8572            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
8573                return null;
8574            }
8575            final PackageParser.Provider provider = info.provider;
8576            if (mSafeMode && (provider.info.applicationInfo.flags
8577                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
8578                return null;
8579            }
8580            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
8581            if (ps == null) {
8582                return null;
8583            }
8584            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
8585                    ps.readUserState(userId), userId);
8586            if (pi == null) {
8587                return null;
8588            }
8589            final ResolveInfo res = new ResolveInfo();
8590            res.providerInfo = pi;
8591            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
8592                res.filter = filter;
8593            }
8594            res.priority = info.getPriority();
8595            res.preferredOrder = provider.owner.mPreferredOrder;
8596            res.match = match;
8597            res.isDefault = info.hasDefault;
8598            res.labelRes = info.labelRes;
8599            res.nonLocalizedLabel = info.nonLocalizedLabel;
8600            res.icon = info.icon;
8601            res.system = res.providerInfo.applicationInfo.isSystemApp();
8602            return res;
8603        }
8604
8605        @Override
8606        protected void sortResults(List<ResolveInfo> results) {
8607            Collections.sort(results, mResolvePrioritySorter);
8608        }
8609
8610        @Override
8611        protected void dumpFilter(PrintWriter out, String prefix,
8612                PackageParser.ProviderIntentInfo filter) {
8613            out.print(prefix);
8614            out.print(
8615                    Integer.toHexString(System.identityHashCode(filter.provider)));
8616            out.print(' ');
8617            filter.provider.printComponentShortName(out);
8618            out.print(" filter ");
8619            out.println(Integer.toHexString(System.identityHashCode(filter)));
8620        }
8621
8622        @Override
8623        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
8624            return filter.provider;
8625        }
8626
8627        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8628            PackageParser.Provider provider = (PackageParser.Provider)label;
8629            out.print(prefix); out.print(
8630                    Integer.toHexString(System.identityHashCode(provider)));
8631                    out.print(' ');
8632                    provider.printComponentShortName(out);
8633            if (count > 1) {
8634                out.print(" ("); out.print(count); out.print(" filters)");
8635            }
8636            out.println();
8637        }
8638
8639        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
8640                = new ArrayMap<ComponentName, PackageParser.Provider>();
8641        private int mFlags;
8642    };
8643
8644    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
8645            new Comparator<ResolveInfo>() {
8646        public int compare(ResolveInfo r1, ResolveInfo r2) {
8647            int v1 = r1.priority;
8648            int v2 = r2.priority;
8649            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
8650            if (v1 != v2) {
8651                return (v1 > v2) ? -1 : 1;
8652            }
8653            v1 = r1.preferredOrder;
8654            v2 = r2.preferredOrder;
8655            if (v1 != v2) {
8656                return (v1 > v2) ? -1 : 1;
8657            }
8658            if (r1.isDefault != r2.isDefault) {
8659                return r1.isDefault ? -1 : 1;
8660            }
8661            v1 = r1.match;
8662            v2 = r2.match;
8663            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
8664            if (v1 != v2) {
8665                return (v1 > v2) ? -1 : 1;
8666            }
8667            if (r1.system != r2.system) {
8668                return r1.system ? -1 : 1;
8669            }
8670            return 0;
8671        }
8672    };
8673
8674    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
8675            new Comparator<ProviderInfo>() {
8676        public int compare(ProviderInfo p1, ProviderInfo p2) {
8677            final int v1 = p1.initOrder;
8678            final int v2 = p2.initOrder;
8679            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
8680        }
8681    };
8682
8683    final void sendPackageBroadcast(final String action, final String pkg,
8684            final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
8685            final int[] userIds) {
8686        mHandler.post(new Runnable() {
8687            @Override
8688            public void run() {
8689                try {
8690                    final IActivityManager am = ActivityManagerNative.getDefault();
8691                    if (am == null) return;
8692                    final int[] resolvedUserIds;
8693                    if (userIds == null) {
8694                        resolvedUserIds = am.getRunningUserIds();
8695                    } else {
8696                        resolvedUserIds = userIds;
8697                    }
8698                    for (int id : resolvedUserIds) {
8699                        final Intent intent = new Intent(action,
8700                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
8701                        if (extras != null) {
8702                            intent.putExtras(extras);
8703                        }
8704                        if (targetPkg != null) {
8705                            intent.setPackage(targetPkg);
8706                        }
8707                        // Modify the UID when posting to other users
8708                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
8709                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
8710                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
8711                            intent.putExtra(Intent.EXTRA_UID, uid);
8712                        }
8713                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
8714                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
8715                        if (DEBUG_BROADCASTS) {
8716                            RuntimeException here = new RuntimeException("here");
8717                            here.fillInStackTrace();
8718                            Slog.d(TAG, "Sending to user " + id + ": "
8719                                    + intent.toShortString(false, true, false, false)
8720                                    + " " + intent.getExtras(), here);
8721                        }
8722                        am.broadcastIntent(null, intent, null, finishedReceiver,
8723                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
8724                                finishedReceiver != null, false, id);
8725                    }
8726                } catch (RemoteException ex) {
8727                }
8728            }
8729        });
8730    }
8731
8732    /**
8733     * Check if the external storage media is available. This is true if there
8734     * is a mounted external storage medium or if the external storage is
8735     * emulated.
8736     */
8737    private boolean isExternalMediaAvailable() {
8738        return mMediaMounted || Environment.isExternalStorageEmulated();
8739    }
8740
8741    @Override
8742    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
8743        // writer
8744        synchronized (mPackages) {
8745            if (!isExternalMediaAvailable()) {
8746                // If the external storage is no longer mounted at this point,
8747                // the caller may not have been able to delete all of this
8748                // packages files and can not delete any more.  Bail.
8749                return null;
8750            }
8751            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
8752            if (lastPackage != null) {
8753                pkgs.remove(lastPackage);
8754            }
8755            if (pkgs.size() > 0) {
8756                return pkgs.get(0);
8757            }
8758        }
8759        return null;
8760    }
8761
8762    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
8763        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
8764                userId, andCode ? 1 : 0, packageName);
8765        if (mSystemReady) {
8766            msg.sendToTarget();
8767        } else {
8768            if (mPostSystemReadyMessages == null) {
8769                mPostSystemReadyMessages = new ArrayList<>();
8770            }
8771            mPostSystemReadyMessages.add(msg);
8772        }
8773    }
8774
8775    void startCleaningPackages() {
8776        // reader
8777        synchronized (mPackages) {
8778            if (!isExternalMediaAvailable()) {
8779                return;
8780            }
8781            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
8782                return;
8783            }
8784        }
8785        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
8786        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
8787        IActivityManager am = ActivityManagerNative.getDefault();
8788        if (am != null) {
8789            try {
8790                am.startService(null, intent, null, UserHandle.USER_OWNER);
8791            } catch (RemoteException e) {
8792            }
8793        }
8794    }
8795
8796    @Override
8797    public void installPackage(String originPath, IPackageInstallObserver2 observer,
8798            int installFlags, String installerPackageName, VerificationParams verificationParams,
8799            String packageAbiOverride) {
8800        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
8801                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
8802    }
8803
8804    @Override
8805    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
8806            int installFlags, String installerPackageName, VerificationParams verificationParams,
8807            String packageAbiOverride, int userId) {
8808        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
8809
8810        final int callingUid = Binder.getCallingUid();
8811        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
8812
8813        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
8814            try {
8815                if (observer != null) {
8816                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
8817                }
8818            } catch (RemoteException re) {
8819            }
8820            return;
8821        }
8822
8823        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
8824            installFlags |= PackageManager.INSTALL_FROM_ADB;
8825
8826        } else {
8827            // Caller holds INSTALL_PACKAGES permission, so we're less strict
8828            // about installerPackageName.
8829
8830            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
8831            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
8832        }
8833
8834        UserHandle user;
8835        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
8836            user = UserHandle.ALL;
8837        } else {
8838            user = new UserHandle(userId);
8839        }
8840
8841        // Only system components can circumvent runtime permissions when installing.
8842        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
8843                && mContext.checkCallingOrSelfPermission(Manifest.permission
8844                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
8845            throw new SecurityException("You need the "
8846                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
8847                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
8848        }
8849
8850        verificationParams.setInstallerUid(callingUid);
8851
8852        final File originFile = new File(originPath);
8853        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
8854
8855        final Message msg = mHandler.obtainMessage(INIT_COPY);
8856        msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName,
8857                null, verificationParams, user, packageAbiOverride);
8858        mHandler.sendMessage(msg);
8859    }
8860
8861    void installStage(String packageName, File stagedDir, String stagedCid,
8862            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
8863            String installerPackageName, int installerUid, UserHandle user) {
8864        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
8865                params.referrerUri, installerUid, null);
8866
8867        final OriginInfo origin;
8868        if (stagedDir != null) {
8869            origin = OriginInfo.fromStagedFile(stagedDir);
8870        } else {
8871            origin = OriginInfo.fromStagedContainer(stagedCid);
8872        }
8873
8874        final Message msg = mHandler.obtainMessage(INIT_COPY);
8875        msg.obj = new InstallParams(origin, null, observer, params.installFlags,
8876                installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride);
8877        mHandler.sendMessage(msg);
8878    }
8879
8880    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
8881        Bundle extras = new Bundle(1);
8882        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
8883
8884        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
8885                packageName, extras, null, null, new int[] {userId});
8886        try {
8887            IActivityManager am = ActivityManagerNative.getDefault();
8888            final boolean isSystem =
8889                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
8890            if (isSystem && am.isUserRunning(userId, false)) {
8891                // The just-installed/enabled app is bundled on the system, so presumed
8892                // to be able to run automatically without needing an explicit launch.
8893                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
8894                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
8895                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
8896                        .setPackage(packageName);
8897                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
8898                        android.app.AppOpsManager.OP_NONE, false, false, userId);
8899            }
8900        } catch (RemoteException e) {
8901            // shouldn't happen
8902            Slog.w(TAG, "Unable to bootstrap installed package", e);
8903        }
8904    }
8905
8906    @Override
8907    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
8908            int userId) {
8909        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
8910        PackageSetting pkgSetting;
8911        final int uid = Binder.getCallingUid();
8912        enforceCrossUserPermission(uid, userId, true, true,
8913                "setApplicationHiddenSetting for user " + userId);
8914
8915        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
8916            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
8917            return false;
8918        }
8919
8920        long callingId = Binder.clearCallingIdentity();
8921        try {
8922            boolean sendAdded = false;
8923            boolean sendRemoved = false;
8924            // writer
8925            synchronized (mPackages) {
8926                pkgSetting = mSettings.mPackages.get(packageName);
8927                if (pkgSetting == null) {
8928                    return false;
8929                }
8930                if (pkgSetting.getHidden(userId) != hidden) {
8931                    pkgSetting.setHidden(hidden, userId);
8932                    mSettings.writePackageRestrictionsLPr(userId);
8933                    if (hidden) {
8934                        sendRemoved = true;
8935                    } else {
8936                        sendAdded = true;
8937                    }
8938                }
8939            }
8940            if (sendAdded) {
8941                sendPackageAddedForUser(packageName, pkgSetting, userId);
8942                return true;
8943            }
8944            if (sendRemoved) {
8945                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
8946                        "hiding pkg");
8947                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
8948            }
8949        } finally {
8950            Binder.restoreCallingIdentity(callingId);
8951        }
8952        return false;
8953    }
8954
8955    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
8956            int userId) {
8957        final PackageRemovedInfo info = new PackageRemovedInfo();
8958        info.removedPackage = packageName;
8959        info.removedUsers = new int[] {userId};
8960        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
8961        info.sendBroadcast(false, false, false);
8962    }
8963
8964    /**
8965     * Returns true if application is not found or there was an error. Otherwise it returns
8966     * the hidden state of the package for the given user.
8967     */
8968    @Override
8969    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
8970        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
8971        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
8972                false, "getApplicationHidden for user " + userId);
8973        PackageSetting pkgSetting;
8974        long callingId = Binder.clearCallingIdentity();
8975        try {
8976            // writer
8977            synchronized (mPackages) {
8978                pkgSetting = mSettings.mPackages.get(packageName);
8979                if (pkgSetting == null) {
8980                    return true;
8981                }
8982                return pkgSetting.getHidden(userId);
8983            }
8984        } finally {
8985            Binder.restoreCallingIdentity(callingId);
8986        }
8987    }
8988
8989    /**
8990     * @hide
8991     */
8992    @Override
8993    public int installExistingPackageAsUser(String packageName, int userId) {
8994        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
8995                null);
8996        PackageSetting pkgSetting;
8997        final int uid = Binder.getCallingUid();
8998        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
8999                + userId);
9000        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9001            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9002        }
9003
9004        long callingId = Binder.clearCallingIdentity();
9005        try {
9006            boolean sendAdded = false;
9007
9008            // writer
9009            synchronized (mPackages) {
9010                pkgSetting = mSettings.mPackages.get(packageName);
9011                if (pkgSetting == null) {
9012                    return PackageManager.INSTALL_FAILED_INVALID_URI;
9013                }
9014                if (!pkgSetting.getInstalled(userId)) {
9015                    pkgSetting.setInstalled(true, userId);
9016                    pkgSetting.setHidden(false, userId);
9017                    mSettings.writePackageRestrictionsLPr(userId);
9018                    sendAdded = true;
9019                }
9020            }
9021
9022            if (sendAdded) {
9023                sendPackageAddedForUser(packageName, pkgSetting, userId);
9024            }
9025        } finally {
9026            Binder.restoreCallingIdentity(callingId);
9027        }
9028
9029        return PackageManager.INSTALL_SUCCEEDED;
9030    }
9031
9032    boolean isUserRestricted(int userId, String restrictionKey) {
9033        Bundle restrictions = sUserManager.getUserRestrictions(userId);
9034        if (restrictions.getBoolean(restrictionKey, false)) {
9035            Log.w(TAG, "User is restricted: " + restrictionKey);
9036            return true;
9037        }
9038        return false;
9039    }
9040
9041    @Override
9042    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
9043        mContext.enforceCallingOrSelfPermission(
9044                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9045                "Only package verification agents can verify applications");
9046
9047        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9048        final PackageVerificationResponse response = new PackageVerificationResponse(
9049                verificationCode, Binder.getCallingUid());
9050        msg.arg1 = id;
9051        msg.obj = response;
9052        mHandler.sendMessage(msg);
9053    }
9054
9055    @Override
9056    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
9057            long millisecondsToDelay) {
9058        mContext.enforceCallingOrSelfPermission(
9059                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9060                "Only package verification agents can extend verification timeouts");
9061
9062        final PackageVerificationState state = mPendingVerification.get(id);
9063        final PackageVerificationResponse response = new PackageVerificationResponse(
9064                verificationCodeAtTimeout, Binder.getCallingUid());
9065
9066        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
9067            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
9068        }
9069        if (millisecondsToDelay < 0) {
9070            millisecondsToDelay = 0;
9071        }
9072        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9073                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9074            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9075        }
9076
9077        if ((state != null) && !state.timeoutExtended()) {
9078            state.extendTimeout();
9079
9080            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9081            msg.arg1 = id;
9082            msg.obj = response;
9083            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
9084        }
9085    }
9086
9087    private void broadcastPackageVerified(int verificationId, Uri packageUri,
9088            int verificationCode, UserHandle user) {
9089        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
9090        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
9091        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9092        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9093        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
9094
9095        mContext.sendBroadcastAsUser(intent, user,
9096                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
9097    }
9098
9099    private ComponentName matchComponentForVerifier(String packageName,
9100            List<ResolveInfo> receivers) {
9101        ActivityInfo targetReceiver = null;
9102
9103        final int NR = receivers.size();
9104        for (int i = 0; i < NR; i++) {
9105            final ResolveInfo info = receivers.get(i);
9106            if (info.activityInfo == null) {
9107                continue;
9108            }
9109
9110            if (packageName.equals(info.activityInfo.packageName)) {
9111                targetReceiver = info.activityInfo;
9112                break;
9113            }
9114        }
9115
9116        if (targetReceiver == null) {
9117            return null;
9118        }
9119
9120        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
9121    }
9122
9123    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
9124            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
9125        if (pkgInfo.verifiers.length == 0) {
9126            return null;
9127        }
9128
9129        final int N = pkgInfo.verifiers.length;
9130        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
9131        for (int i = 0; i < N; i++) {
9132            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
9133
9134            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
9135                    receivers);
9136            if (comp == null) {
9137                continue;
9138            }
9139
9140            final int verifierUid = getUidForVerifier(verifierInfo);
9141            if (verifierUid == -1) {
9142                continue;
9143            }
9144
9145            if (DEBUG_VERIFY) {
9146                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
9147                        + " with the correct signature");
9148            }
9149            sufficientVerifiers.add(comp);
9150            verificationState.addSufficientVerifier(verifierUid);
9151        }
9152
9153        return sufficientVerifiers;
9154    }
9155
9156    private int getUidForVerifier(VerifierInfo verifierInfo) {
9157        synchronized (mPackages) {
9158            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
9159            if (pkg == null) {
9160                return -1;
9161            } else if (pkg.mSignatures.length != 1) {
9162                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9163                        + " has more than one signature; ignoring");
9164                return -1;
9165            }
9166
9167            /*
9168             * If the public key of the package's signature does not match
9169             * our expected public key, then this is a different package and
9170             * we should skip.
9171             */
9172
9173            final byte[] expectedPublicKey;
9174            try {
9175                final Signature verifierSig = pkg.mSignatures[0];
9176                final PublicKey publicKey = verifierSig.getPublicKey();
9177                expectedPublicKey = publicKey.getEncoded();
9178            } catch (CertificateException e) {
9179                return -1;
9180            }
9181
9182            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
9183
9184            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
9185                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9186                        + " does not have the expected public key; ignoring");
9187                return -1;
9188            }
9189
9190            return pkg.applicationInfo.uid;
9191        }
9192    }
9193
9194    @Override
9195    public void finishPackageInstall(int token) {
9196        enforceSystemOrRoot("Only the system is allowed to finish installs");
9197
9198        if (DEBUG_INSTALL) {
9199            Slog.v(TAG, "BM finishing package install for " + token);
9200        }
9201
9202        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9203        mHandler.sendMessage(msg);
9204    }
9205
9206    /**
9207     * Get the verification agent timeout.
9208     *
9209     * @return verification timeout in milliseconds
9210     */
9211    private long getVerificationTimeout() {
9212        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
9213                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
9214                DEFAULT_VERIFICATION_TIMEOUT);
9215    }
9216
9217    /**
9218     * Get the default verification agent response code.
9219     *
9220     * @return default verification response code
9221     */
9222    private int getDefaultVerificationResponse() {
9223        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9224                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
9225                DEFAULT_VERIFICATION_RESPONSE);
9226    }
9227
9228    /**
9229     * Check whether or not package verification has been enabled.
9230     *
9231     * @return true if verification should be performed
9232     */
9233    private boolean isVerificationEnabled(int userId, int installFlags) {
9234        if (!DEFAULT_VERIFY_ENABLE) {
9235            return false;
9236        }
9237
9238        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
9239
9240        // Check if installing from ADB
9241        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
9242            // Do not run verification in a test harness environment
9243            if (ActivityManager.isRunningInTestHarness()) {
9244                return false;
9245            }
9246            if (ensureVerifyAppsEnabled) {
9247                return true;
9248            }
9249            // Check if the developer does not want package verification for ADB installs
9250            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9251                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
9252                return false;
9253            }
9254        }
9255
9256        if (ensureVerifyAppsEnabled) {
9257            return true;
9258        }
9259
9260        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9261                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9262    }
9263
9264    @Override
9265    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9266            throws RemoteException {
9267        mContext.enforceCallingOrSelfPermission(
9268                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9269                "Only intentfilter verification agents can verify applications");
9270
9271        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9272        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9273                Binder.getCallingUid(), verificationCode, failedDomains);
9274        msg.arg1 = id;
9275        msg.obj = response;
9276        mHandler.sendMessage(msg);
9277    }
9278
9279    @Override
9280    public int getIntentVerificationStatus(String packageName, int userId) {
9281        synchronized (mPackages) {
9282            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
9283        }
9284    }
9285
9286    @Override
9287    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
9288        boolean result = false;
9289        synchronized (mPackages) {
9290            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
9291        }
9292        if (result) {
9293            scheduleWritePackageRestrictionsLocked(userId);
9294        }
9295        return result;
9296    }
9297
9298    @Override
9299    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
9300        synchronized (mPackages) {
9301            return mSettings.getIntentFilterVerificationsLPr(packageName);
9302        }
9303    }
9304
9305    @Override
9306    public List<IntentFilter> getAllIntentFilters(String packageName) {
9307        if (TextUtils.isEmpty(packageName)) {
9308            return Collections.<IntentFilter>emptyList();
9309        }
9310        synchronized (mPackages) {
9311            PackageParser.Package pkg = mPackages.get(packageName);
9312            if (pkg == null || pkg.activities == null) {
9313                return Collections.<IntentFilter>emptyList();
9314            }
9315            final int count = pkg.activities.size();
9316            ArrayList<IntentFilter> result = new ArrayList<>();
9317            for (int n=0; n<count; n++) {
9318                PackageParser.Activity activity = pkg.activities.get(n);
9319                if (activity.intents != null || activity.intents.size() > 0) {
9320                    result.addAll(activity.intents);
9321                }
9322            }
9323            return result;
9324        }
9325    }
9326
9327    @Override
9328    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
9329        synchronized (mPackages) {
9330            boolean result = mSettings.setDefaultBrowserPackageNameLPr(packageName, userId);
9331            if (packageName != null) {
9332                result |= updateIntentVerificationStatus(packageName,
9333                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
9334                        UserHandle.myUserId());
9335            }
9336            return result;
9337        }
9338    }
9339
9340    @Override
9341    public String getDefaultBrowserPackageName(int userId) {
9342        synchronized (mPackages) {
9343            return mSettings.getDefaultBrowserPackageNameLPw(userId);
9344        }
9345    }
9346
9347    /**
9348     * Get the "allow unknown sources" setting.
9349     *
9350     * @return the current "allow unknown sources" setting
9351     */
9352    private int getUnknownSourcesSettings() {
9353        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9354                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
9355                -1);
9356    }
9357
9358    @Override
9359    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
9360        final int uid = Binder.getCallingUid();
9361        // writer
9362        synchronized (mPackages) {
9363            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
9364            if (targetPackageSetting == null) {
9365                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
9366            }
9367
9368            PackageSetting installerPackageSetting;
9369            if (installerPackageName != null) {
9370                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
9371                if (installerPackageSetting == null) {
9372                    throw new IllegalArgumentException("Unknown installer package: "
9373                            + installerPackageName);
9374                }
9375            } else {
9376                installerPackageSetting = null;
9377            }
9378
9379            Signature[] callerSignature;
9380            Object obj = mSettings.getUserIdLPr(uid);
9381            if (obj != null) {
9382                if (obj instanceof SharedUserSetting) {
9383                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
9384                } else if (obj instanceof PackageSetting) {
9385                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
9386                } else {
9387                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
9388                }
9389            } else {
9390                throw new SecurityException("Unknown calling uid " + uid);
9391            }
9392
9393            // Verify: can't set installerPackageName to a package that is
9394            // not signed with the same cert as the caller.
9395            if (installerPackageSetting != null) {
9396                if (compareSignatures(callerSignature,
9397                        installerPackageSetting.signatures.mSignatures)
9398                        != PackageManager.SIGNATURE_MATCH) {
9399                    throw new SecurityException(
9400                            "Caller does not have same cert as new installer package "
9401                            + installerPackageName);
9402                }
9403            }
9404
9405            // Verify: if target already has an installer package, it must
9406            // be signed with the same cert as the caller.
9407            if (targetPackageSetting.installerPackageName != null) {
9408                PackageSetting setting = mSettings.mPackages.get(
9409                        targetPackageSetting.installerPackageName);
9410                // If the currently set package isn't valid, then it's always
9411                // okay to change it.
9412                if (setting != null) {
9413                    if (compareSignatures(callerSignature,
9414                            setting.signatures.mSignatures)
9415                            != PackageManager.SIGNATURE_MATCH) {
9416                        throw new SecurityException(
9417                                "Caller does not have same cert as old installer package "
9418                                + targetPackageSetting.installerPackageName);
9419                    }
9420                }
9421            }
9422
9423            // Okay!
9424            targetPackageSetting.installerPackageName = installerPackageName;
9425            scheduleWriteSettingsLocked();
9426        }
9427    }
9428
9429    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
9430        // Queue up an async operation since the package installation may take a little while.
9431        mHandler.post(new Runnable() {
9432            public void run() {
9433                mHandler.removeCallbacks(this);
9434                 // Result object to be returned
9435                PackageInstalledInfo res = new PackageInstalledInfo();
9436                res.returnCode = currentStatus;
9437                res.uid = -1;
9438                res.pkg = null;
9439                res.removedInfo = new PackageRemovedInfo();
9440                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
9441                    args.doPreInstall(res.returnCode);
9442                    synchronized (mInstallLock) {
9443                        installPackageLI(args, res);
9444                    }
9445                    args.doPostInstall(res.returnCode, res.uid);
9446                }
9447
9448                // A restore should be performed at this point if (a) the install
9449                // succeeded, (b) the operation is not an update, and (c) the new
9450                // package has not opted out of backup participation.
9451                final boolean update = res.removedInfo.removedPackage != null;
9452                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
9453                boolean doRestore = !update
9454                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
9455
9456                // Set up the post-install work request bookkeeping.  This will be used
9457                // and cleaned up by the post-install event handling regardless of whether
9458                // there's a restore pass performed.  Token values are >= 1.
9459                int token;
9460                if (mNextInstallToken < 0) mNextInstallToken = 1;
9461                token = mNextInstallToken++;
9462
9463                PostInstallData data = new PostInstallData(args, res);
9464                mRunningInstalls.put(token, data);
9465                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
9466
9467                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
9468                    // Pass responsibility to the Backup Manager.  It will perform a
9469                    // restore if appropriate, then pass responsibility back to the
9470                    // Package Manager to run the post-install observer callbacks
9471                    // and broadcasts.
9472                    IBackupManager bm = IBackupManager.Stub.asInterface(
9473                            ServiceManager.getService(Context.BACKUP_SERVICE));
9474                    if (bm != null) {
9475                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
9476                                + " to BM for possible restore");
9477                        try {
9478                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
9479                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
9480                            } else {
9481                                doRestore = false;
9482                            }
9483                        } catch (RemoteException e) {
9484                            // can't happen; the backup manager is local
9485                        } catch (Exception e) {
9486                            Slog.e(TAG, "Exception trying to enqueue restore", e);
9487                            doRestore = false;
9488                        }
9489                    } else {
9490                        Slog.e(TAG, "Backup Manager not found!");
9491                        doRestore = false;
9492                    }
9493                }
9494
9495                if (!doRestore) {
9496                    // No restore possible, or the Backup Manager was mysteriously not
9497                    // available -- just fire the post-install work request directly.
9498                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
9499                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9500                    mHandler.sendMessage(msg);
9501                }
9502            }
9503        });
9504    }
9505
9506    private abstract class HandlerParams {
9507        private static final int MAX_RETRIES = 4;
9508
9509        /**
9510         * Number of times startCopy() has been attempted and had a non-fatal
9511         * error.
9512         */
9513        private int mRetries = 0;
9514
9515        /** User handle for the user requesting the information or installation. */
9516        private final UserHandle mUser;
9517
9518        HandlerParams(UserHandle user) {
9519            mUser = user;
9520        }
9521
9522        UserHandle getUser() {
9523            return mUser;
9524        }
9525
9526        final boolean startCopy() {
9527            boolean res;
9528            try {
9529                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
9530
9531                if (++mRetries > MAX_RETRIES) {
9532                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
9533                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
9534                    handleServiceError();
9535                    return false;
9536                } else {
9537                    handleStartCopy();
9538                    res = true;
9539                }
9540            } catch (RemoteException e) {
9541                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
9542                mHandler.sendEmptyMessage(MCS_RECONNECT);
9543                res = false;
9544            }
9545            handleReturnCode();
9546            return res;
9547        }
9548
9549        final void serviceError() {
9550            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
9551            handleServiceError();
9552            handleReturnCode();
9553        }
9554
9555        abstract void handleStartCopy() throws RemoteException;
9556        abstract void handleServiceError();
9557        abstract void handleReturnCode();
9558    }
9559
9560    class MeasureParams extends HandlerParams {
9561        private final PackageStats mStats;
9562        private boolean mSuccess;
9563
9564        private final IPackageStatsObserver mObserver;
9565
9566        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
9567            super(new UserHandle(stats.userHandle));
9568            mObserver = observer;
9569            mStats = stats;
9570        }
9571
9572        @Override
9573        public String toString() {
9574            return "MeasureParams{"
9575                + Integer.toHexString(System.identityHashCode(this))
9576                + " " + mStats.packageName + "}";
9577        }
9578
9579        @Override
9580        void handleStartCopy() throws RemoteException {
9581            synchronized (mInstallLock) {
9582                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
9583            }
9584
9585            if (mSuccess) {
9586                final boolean mounted;
9587                if (Environment.isExternalStorageEmulated()) {
9588                    mounted = true;
9589                } else {
9590                    final String status = Environment.getExternalStorageState();
9591                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
9592                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
9593                }
9594
9595                if (mounted) {
9596                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
9597
9598                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
9599                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
9600
9601                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
9602                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
9603
9604                    // Always subtract cache size, since it's a subdirectory
9605                    mStats.externalDataSize -= mStats.externalCacheSize;
9606
9607                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
9608                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
9609
9610                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
9611                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
9612                }
9613            }
9614        }
9615
9616        @Override
9617        void handleReturnCode() {
9618            if (mObserver != null) {
9619                try {
9620                    mObserver.onGetStatsCompleted(mStats, mSuccess);
9621                } catch (RemoteException e) {
9622                    Slog.i(TAG, "Observer no longer exists.");
9623                }
9624            }
9625        }
9626
9627        @Override
9628        void handleServiceError() {
9629            Slog.e(TAG, "Could not measure application " + mStats.packageName
9630                            + " external storage");
9631        }
9632    }
9633
9634    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
9635            throws RemoteException {
9636        long result = 0;
9637        for (File path : paths) {
9638            result += mcs.calculateDirectorySize(path.getAbsolutePath());
9639        }
9640        return result;
9641    }
9642
9643    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
9644        for (File path : paths) {
9645            try {
9646                mcs.clearDirectory(path.getAbsolutePath());
9647            } catch (RemoteException e) {
9648            }
9649        }
9650    }
9651
9652    static class OriginInfo {
9653        /**
9654         * Location where install is coming from, before it has been
9655         * copied/renamed into place. This could be a single monolithic APK
9656         * file, or a cluster directory. This location may be untrusted.
9657         */
9658        final File file;
9659        final String cid;
9660
9661        /**
9662         * Flag indicating that {@link #file} or {@link #cid} has already been
9663         * staged, meaning downstream users don't need to defensively copy the
9664         * contents.
9665         */
9666        final boolean staged;
9667
9668        /**
9669         * Flag indicating that {@link #file} or {@link #cid} is an already
9670         * installed app that is being moved.
9671         */
9672        final boolean existing;
9673
9674        final String resolvedPath;
9675        final File resolvedFile;
9676
9677        static OriginInfo fromNothing() {
9678            return new OriginInfo(null, null, false, false);
9679        }
9680
9681        static OriginInfo fromUntrustedFile(File file) {
9682            return new OriginInfo(file, null, false, false);
9683        }
9684
9685        static OriginInfo fromExistingFile(File file) {
9686            return new OriginInfo(file, null, false, true);
9687        }
9688
9689        static OriginInfo fromStagedFile(File file) {
9690            return new OriginInfo(file, null, true, false);
9691        }
9692
9693        static OriginInfo fromStagedContainer(String cid) {
9694            return new OriginInfo(null, cid, true, false);
9695        }
9696
9697        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
9698            this.file = file;
9699            this.cid = cid;
9700            this.staged = staged;
9701            this.existing = existing;
9702
9703            if (cid != null) {
9704                resolvedPath = PackageHelper.getSdDir(cid);
9705                resolvedFile = new File(resolvedPath);
9706            } else if (file != null) {
9707                resolvedPath = file.getAbsolutePath();
9708                resolvedFile = file;
9709            } else {
9710                resolvedPath = null;
9711                resolvedFile = null;
9712            }
9713        }
9714    }
9715
9716    class MoveInfo {
9717        final int moveId;
9718        final String fromUuid;
9719        final String toUuid;
9720        final String packageName;
9721        final String dataAppName;
9722        final int appId;
9723        final String seinfo;
9724
9725        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
9726                String dataAppName, int appId, String seinfo) {
9727            this.moveId = moveId;
9728            this.fromUuid = fromUuid;
9729            this.toUuid = toUuid;
9730            this.packageName = packageName;
9731            this.dataAppName = dataAppName;
9732            this.appId = appId;
9733            this.seinfo = seinfo;
9734        }
9735    }
9736
9737    class InstallParams extends HandlerParams {
9738        final OriginInfo origin;
9739        final MoveInfo move;
9740        final IPackageInstallObserver2 observer;
9741        int installFlags;
9742        final String installerPackageName;
9743        final String volumeUuid;
9744        final VerificationParams verificationParams;
9745        private InstallArgs mArgs;
9746        private int mRet;
9747        final String packageAbiOverride;
9748
9749        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
9750                int installFlags, String installerPackageName, String volumeUuid,
9751                VerificationParams verificationParams, UserHandle user, String packageAbiOverride) {
9752            super(user);
9753            this.origin = origin;
9754            this.move = move;
9755            this.observer = observer;
9756            this.installFlags = installFlags;
9757            this.installerPackageName = installerPackageName;
9758            this.volumeUuid = volumeUuid;
9759            this.verificationParams = verificationParams;
9760            this.packageAbiOverride = packageAbiOverride;
9761        }
9762
9763        @Override
9764        public String toString() {
9765            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
9766                    + " file=" + origin.file + " cid=" + origin.cid + "}";
9767        }
9768
9769        public ManifestDigest getManifestDigest() {
9770            if (verificationParams == null) {
9771                return null;
9772            }
9773            return verificationParams.getManifestDigest();
9774        }
9775
9776        private int installLocationPolicy(PackageInfoLite pkgLite) {
9777            String packageName = pkgLite.packageName;
9778            int installLocation = pkgLite.installLocation;
9779            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9780            // reader
9781            synchronized (mPackages) {
9782                PackageParser.Package pkg = mPackages.get(packageName);
9783                if (pkg != null) {
9784                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
9785                        // Check for downgrading.
9786                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
9787                            try {
9788                                checkDowngrade(pkg, pkgLite);
9789                            } catch (PackageManagerException e) {
9790                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
9791                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
9792                            }
9793                        }
9794                        // Check for updated system application.
9795                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
9796                            if (onSd) {
9797                                Slog.w(TAG, "Cannot install update to system app on sdcard");
9798                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
9799                            }
9800                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
9801                        } else {
9802                            if (onSd) {
9803                                // Install flag overrides everything.
9804                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
9805                            }
9806                            // If current upgrade specifies particular preference
9807                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
9808                                // Application explicitly specified internal.
9809                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
9810                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
9811                                // App explictly prefers external. Let policy decide
9812                            } else {
9813                                // Prefer previous location
9814                                if (isExternal(pkg)) {
9815                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
9816                                }
9817                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
9818                            }
9819                        }
9820                    } else {
9821                        // Invalid install. Return error code
9822                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
9823                    }
9824                }
9825            }
9826            // All the special cases have been taken care of.
9827            // Return result based on recommended install location.
9828            if (onSd) {
9829                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
9830            }
9831            return pkgLite.recommendedInstallLocation;
9832        }
9833
9834        /*
9835         * Invoke remote method to get package information and install
9836         * location values. Override install location based on default
9837         * policy if needed and then create install arguments based
9838         * on the install location.
9839         */
9840        public void handleStartCopy() throws RemoteException {
9841            int ret = PackageManager.INSTALL_SUCCEEDED;
9842
9843            // If we're already staged, we've firmly committed to an install location
9844            if (origin.staged) {
9845                if (origin.file != null) {
9846                    installFlags |= PackageManager.INSTALL_INTERNAL;
9847                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
9848                } else if (origin.cid != null) {
9849                    installFlags |= PackageManager.INSTALL_EXTERNAL;
9850                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
9851                } else {
9852                    throw new IllegalStateException("Invalid stage location");
9853                }
9854            }
9855
9856            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9857            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
9858
9859            PackageInfoLite pkgLite = null;
9860
9861            if (onInt && onSd) {
9862                // Check if both bits are set.
9863                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
9864                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
9865            } else {
9866                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
9867                        packageAbiOverride);
9868
9869                /*
9870                 * If we have too little free space, try to free cache
9871                 * before giving up.
9872                 */
9873                if (!origin.staged && pkgLite.recommendedInstallLocation
9874                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
9875                    // TODO: focus freeing disk space on the target device
9876                    final StorageManager storage = StorageManager.from(mContext);
9877                    final long lowThreshold = storage.getStorageLowBytes(
9878                            Environment.getDataDirectory());
9879
9880                    final long sizeBytes = mContainerService.calculateInstalledSize(
9881                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
9882
9883                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
9884                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
9885                                installFlags, packageAbiOverride);
9886                    }
9887
9888                    /*
9889                     * The cache free must have deleted the file we
9890                     * downloaded to install.
9891                     *
9892                     * TODO: fix the "freeCache" call to not delete
9893                     *       the file we care about.
9894                     */
9895                    if (pkgLite.recommendedInstallLocation
9896                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
9897                        pkgLite.recommendedInstallLocation
9898                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
9899                    }
9900                }
9901            }
9902
9903            if (ret == PackageManager.INSTALL_SUCCEEDED) {
9904                int loc = pkgLite.recommendedInstallLocation;
9905                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
9906                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
9907                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
9908                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
9909                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
9910                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9911                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
9912                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
9913                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
9914                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
9915                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
9916                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
9917                } else {
9918                    // Override with defaults if needed.
9919                    loc = installLocationPolicy(pkgLite);
9920                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
9921                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
9922                    } else if (!onSd && !onInt) {
9923                        // Override install location with flags
9924                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
9925                            // Set the flag to install on external media.
9926                            installFlags |= PackageManager.INSTALL_EXTERNAL;
9927                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
9928                        } else {
9929                            // Make sure the flag for installing on external
9930                            // media is unset
9931                            installFlags |= PackageManager.INSTALL_INTERNAL;
9932                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
9933                        }
9934                    }
9935                }
9936            }
9937
9938            final InstallArgs args = createInstallArgs(this);
9939            mArgs = args;
9940
9941            if (ret == PackageManager.INSTALL_SUCCEEDED) {
9942                 /*
9943                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
9944                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
9945                 */
9946                int userIdentifier = getUser().getIdentifier();
9947                if (userIdentifier == UserHandle.USER_ALL
9948                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
9949                    userIdentifier = UserHandle.USER_OWNER;
9950                }
9951
9952                /*
9953                 * Determine if we have any installed package verifiers. If we
9954                 * do, then we'll defer to them to verify the packages.
9955                 */
9956                final int requiredUid = mRequiredVerifierPackage == null ? -1
9957                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
9958                if (!origin.existing && requiredUid != -1
9959                        && isVerificationEnabled(userIdentifier, installFlags)) {
9960                    final Intent verification = new Intent(
9961                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
9962                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
9963                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
9964                            PACKAGE_MIME_TYPE);
9965                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9966
9967                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
9968                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
9969                            0 /* TODO: Which userId? */);
9970
9971                    if (DEBUG_VERIFY) {
9972                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
9973                                + verification.toString() + " with " + pkgLite.verifiers.length
9974                                + " optional verifiers");
9975                    }
9976
9977                    final int verificationId = mPendingVerificationToken++;
9978
9979                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9980
9981                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
9982                            installerPackageName);
9983
9984                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
9985                            installFlags);
9986
9987                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
9988                            pkgLite.packageName);
9989
9990                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
9991                            pkgLite.versionCode);
9992
9993                    if (verificationParams != null) {
9994                        if (verificationParams.getVerificationURI() != null) {
9995                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
9996                                 verificationParams.getVerificationURI());
9997                        }
9998                        if (verificationParams.getOriginatingURI() != null) {
9999                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10000                                  verificationParams.getOriginatingURI());
10001                        }
10002                        if (verificationParams.getReferrer() != null) {
10003                            verification.putExtra(Intent.EXTRA_REFERRER,
10004                                  verificationParams.getReferrer());
10005                        }
10006                        if (verificationParams.getOriginatingUid() >= 0) {
10007                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
10008                                  verificationParams.getOriginatingUid());
10009                        }
10010                        if (verificationParams.getInstallerUid() >= 0) {
10011                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
10012                                  verificationParams.getInstallerUid());
10013                        }
10014                    }
10015
10016                    final PackageVerificationState verificationState = new PackageVerificationState(
10017                            requiredUid, args);
10018
10019                    mPendingVerification.append(verificationId, verificationState);
10020
10021                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
10022                            receivers, verificationState);
10023
10024                    /*
10025                     * If any sufficient verifiers were listed in the package
10026                     * manifest, attempt to ask them.
10027                     */
10028                    if (sufficientVerifiers != null) {
10029                        final int N = sufficientVerifiers.size();
10030                        if (N == 0) {
10031                            Slog.i(TAG, "Additional verifiers required, but none installed.");
10032                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
10033                        } else {
10034                            for (int i = 0; i < N; i++) {
10035                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
10036
10037                                final Intent sufficientIntent = new Intent(verification);
10038                                sufficientIntent.setComponent(verifierComponent);
10039
10040                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
10041                            }
10042                        }
10043                    }
10044
10045                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
10046                            mRequiredVerifierPackage, receivers);
10047                    if (ret == PackageManager.INSTALL_SUCCEEDED
10048                            && mRequiredVerifierPackage != null) {
10049                        /*
10050                         * Send the intent to the required verification agent,
10051                         * but only start the verification timeout after the
10052                         * target BroadcastReceivers have run.
10053                         */
10054                        verification.setComponent(requiredVerifierComponent);
10055                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
10056                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10057                                new BroadcastReceiver() {
10058                                    @Override
10059                                    public void onReceive(Context context, Intent intent) {
10060                                        final Message msg = mHandler
10061                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
10062                                        msg.arg1 = verificationId;
10063                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
10064                                    }
10065                                }, null, 0, null, null);
10066
10067                        /*
10068                         * We don't want the copy to proceed until verification
10069                         * succeeds, so null out this field.
10070                         */
10071                        mArgs = null;
10072                    }
10073                } else {
10074                    /*
10075                     * No package verification is enabled, so immediately start
10076                     * the remote call to initiate copy using temporary file.
10077                     */
10078                    ret = args.copyApk(mContainerService, true);
10079                }
10080            }
10081
10082            mRet = ret;
10083        }
10084
10085        @Override
10086        void handleReturnCode() {
10087            // If mArgs is null, then MCS couldn't be reached. When it
10088            // reconnects, it will try again to install. At that point, this
10089            // will succeed.
10090            if (mArgs != null) {
10091                processPendingInstall(mArgs, mRet);
10092            }
10093        }
10094
10095        @Override
10096        void handleServiceError() {
10097            mArgs = createInstallArgs(this);
10098            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10099        }
10100
10101        public boolean isForwardLocked() {
10102            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10103        }
10104    }
10105
10106    /**
10107     * Used during creation of InstallArgs
10108     *
10109     * @param installFlags package installation flags
10110     * @return true if should be installed on external storage
10111     */
10112    private static boolean installOnExternalAsec(int installFlags) {
10113        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
10114            return false;
10115        }
10116        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
10117            return true;
10118        }
10119        return false;
10120    }
10121
10122    /**
10123     * Used during creation of InstallArgs
10124     *
10125     * @param installFlags package installation flags
10126     * @return true if should be installed as forward locked
10127     */
10128    private static boolean installForwardLocked(int installFlags) {
10129        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10130    }
10131
10132    private InstallArgs createInstallArgs(InstallParams params) {
10133        if (params.move != null) {
10134            return new MoveInstallArgs(params);
10135        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
10136            return new AsecInstallArgs(params);
10137        } else {
10138            return new FileInstallArgs(params);
10139        }
10140    }
10141
10142    /**
10143     * Create args that describe an existing installed package. Typically used
10144     * when cleaning up old installs, or used as a move source.
10145     */
10146    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
10147            String resourcePath, String[] instructionSets) {
10148        final boolean isInAsec;
10149        if (installOnExternalAsec(installFlags)) {
10150            /* Apps on SD card are always in ASEC containers. */
10151            isInAsec = true;
10152        } else if (installForwardLocked(installFlags)
10153                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
10154            /*
10155             * Forward-locked apps are only in ASEC containers if they're the
10156             * new style
10157             */
10158            isInAsec = true;
10159        } else {
10160            isInAsec = false;
10161        }
10162
10163        if (isInAsec) {
10164            return new AsecInstallArgs(codePath, instructionSets,
10165                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
10166        } else {
10167            return new FileInstallArgs(codePath, resourcePath, instructionSets);
10168        }
10169    }
10170
10171    static abstract class InstallArgs {
10172        /** @see InstallParams#origin */
10173        final OriginInfo origin;
10174        /** @see InstallParams#move */
10175        final MoveInfo move;
10176
10177        final IPackageInstallObserver2 observer;
10178        // Always refers to PackageManager flags only
10179        final int installFlags;
10180        final String installerPackageName;
10181        final String volumeUuid;
10182        final ManifestDigest manifestDigest;
10183        final UserHandle user;
10184        final String abiOverride;
10185
10186        // The list of instruction sets supported by this app. This is currently
10187        // only used during the rmdex() phase to clean up resources. We can get rid of this
10188        // if we move dex files under the common app path.
10189        /* nullable */ String[] instructionSets;
10190
10191        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10192                int installFlags, String installerPackageName, String volumeUuid,
10193                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
10194                String abiOverride) {
10195            this.origin = origin;
10196            this.move = move;
10197            this.installFlags = installFlags;
10198            this.observer = observer;
10199            this.installerPackageName = installerPackageName;
10200            this.volumeUuid = volumeUuid;
10201            this.manifestDigest = manifestDigest;
10202            this.user = user;
10203            this.instructionSets = instructionSets;
10204            this.abiOverride = abiOverride;
10205        }
10206
10207        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
10208        abstract int doPreInstall(int status);
10209
10210        /**
10211         * Rename package into final resting place. All paths on the given
10212         * scanned package should be updated to reflect the rename.
10213         */
10214        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
10215        abstract int doPostInstall(int status, int uid);
10216
10217        /** @see PackageSettingBase#codePathString */
10218        abstract String getCodePath();
10219        /** @see PackageSettingBase#resourcePathString */
10220        abstract String getResourcePath();
10221
10222        // Need installer lock especially for dex file removal.
10223        abstract void cleanUpResourcesLI();
10224        abstract boolean doPostDeleteLI(boolean delete);
10225
10226        /**
10227         * Called before the source arguments are copied. This is used mostly
10228         * for MoveParams when it needs to read the source file to put it in the
10229         * destination.
10230         */
10231        int doPreCopy() {
10232            return PackageManager.INSTALL_SUCCEEDED;
10233        }
10234
10235        /**
10236         * Called after the source arguments are copied. This is used mostly for
10237         * MoveParams when it needs to read the source file to put it in the
10238         * destination.
10239         *
10240         * @return
10241         */
10242        int doPostCopy(int uid) {
10243            return PackageManager.INSTALL_SUCCEEDED;
10244        }
10245
10246        protected boolean isFwdLocked() {
10247            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10248        }
10249
10250        protected boolean isExternalAsec() {
10251            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10252        }
10253
10254        UserHandle getUser() {
10255            return user;
10256        }
10257    }
10258
10259    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
10260        if (!allCodePaths.isEmpty()) {
10261            if (instructionSets == null) {
10262                throw new IllegalStateException("instructionSet == null");
10263            }
10264            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
10265            for (String codePath : allCodePaths) {
10266                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
10267                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
10268                    if (retCode < 0) {
10269                        Slog.w(TAG, "Couldn't remove dex file for package: "
10270                                + " at location " + codePath + ", retcode=" + retCode);
10271                        // we don't consider this to be a failure of the core package deletion
10272                    }
10273                }
10274            }
10275        }
10276    }
10277
10278    /**
10279     * Logic to handle installation of non-ASEC applications, including copying
10280     * and renaming logic.
10281     */
10282    class FileInstallArgs extends InstallArgs {
10283        private File codeFile;
10284        private File resourceFile;
10285
10286        // Example topology:
10287        // /data/app/com.example/base.apk
10288        // /data/app/com.example/split_foo.apk
10289        // /data/app/com.example/lib/arm/libfoo.so
10290        // /data/app/com.example/lib/arm64/libfoo.so
10291        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
10292
10293        /** New install */
10294        FileInstallArgs(InstallParams params) {
10295            super(params.origin, params.move, params.observer, params.installFlags,
10296                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10297                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10298            if (isFwdLocked()) {
10299                throw new IllegalArgumentException("Forward locking only supported in ASEC");
10300            }
10301        }
10302
10303        /** Existing install */
10304        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
10305            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
10306                    null);
10307            this.codeFile = (codePath != null) ? new File(codePath) : null;
10308            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
10309        }
10310
10311        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10312            if (origin.staged) {
10313                Slog.d(TAG, origin.file + " already staged; skipping copy");
10314                codeFile = origin.file;
10315                resourceFile = origin.file;
10316                return PackageManager.INSTALL_SUCCEEDED;
10317            }
10318
10319            try {
10320                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
10321                codeFile = tempDir;
10322                resourceFile = tempDir;
10323            } catch (IOException e) {
10324                Slog.w(TAG, "Failed to create copy file: " + e);
10325                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10326            }
10327
10328            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
10329                @Override
10330                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
10331                    if (!FileUtils.isValidExtFilename(name)) {
10332                        throw new IllegalArgumentException("Invalid filename: " + name);
10333                    }
10334                    try {
10335                        final File file = new File(codeFile, name);
10336                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
10337                                O_RDWR | O_CREAT, 0644);
10338                        Os.chmod(file.getAbsolutePath(), 0644);
10339                        return new ParcelFileDescriptor(fd);
10340                    } catch (ErrnoException e) {
10341                        throw new RemoteException("Failed to open: " + e.getMessage());
10342                    }
10343                }
10344            };
10345
10346            int ret = PackageManager.INSTALL_SUCCEEDED;
10347            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
10348            if (ret != PackageManager.INSTALL_SUCCEEDED) {
10349                Slog.e(TAG, "Failed to copy package");
10350                return ret;
10351            }
10352
10353            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
10354            NativeLibraryHelper.Handle handle = null;
10355            try {
10356                handle = NativeLibraryHelper.Handle.create(codeFile);
10357                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
10358                        abiOverride);
10359            } catch (IOException e) {
10360                Slog.e(TAG, "Copying native libraries failed", e);
10361                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10362            } finally {
10363                IoUtils.closeQuietly(handle);
10364            }
10365
10366            return ret;
10367        }
10368
10369        int doPreInstall(int status) {
10370            if (status != PackageManager.INSTALL_SUCCEEDED) {
10371                cleanUp();
10372            }
10373            return status;
10374        }
10375
10376        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10377            if (status != PackageManager.INSTALL_SUCCEEDED) {
10378                cleanUp();
10379                return false;
10380            }
10381
10382            final File targetDir = codeFile.getParentFile();
10383            final File beforeCodeFile = codeFile;
10384            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
10385
10386            Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
10387            try {
10388                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
10389            } catch (ErrnoException e) {
10390                Slog.d(TAG, "Failed to rename", e);
10391                return false;
10392            }
10393
10394            if (!SELinux.restoreconRecursive(afterCodeFile)) {
10395                Slog.d(TAG, "Failed to restorecon");
10396                return false;
10397            }
10398
10399            // Reflect the rename internally
10400            codeFile = afterCodeFile;
10401            resourceFile = afterCodeFile;
10402
10403            // Reflect the rename in scanned details
10404            pkg.codePath = afterCodeFile.getAbsolutePath();
10405            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10406                    pkg.baseCodePath);
10407            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10408                    pkg.splitCodePaths);
10409
10410            // Reflect the rename in app info
10411            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10412            pkg.applicationInfo.setCodePath(pkg.codePath);
10413            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10414            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10415            pkg.applicationInfo.setResourcePath(pkg.codePath);
10416            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10417            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10418
10419            return true;
10420        }
10421
10422        int doPostInstall(int status, int uid) {
10423            if (status != PackageManager.INSTALL_SUCCEEDED) {
10424                cleanUp();
10425            }
10426            return status;
10427        }
10428
10429        @Override
10430        String getCodePath() {
10431            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
10432        }
10433
10434        @Override
10435        String getResourcePath() {
10436            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
10437        }
10438
10439        private boolean cleanUp() {
10440            if (codeFile == null || !codeFile.exists()) {
10441                return false;
10442            }
10443
10444            if (codeFile.isDirectory()) {
10445                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
10446            } else {
10447                codeFile.delete();
10448            }
10449
10450            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
10451                resourceFile.delete();
10452            }
10453
10454            return true;
10455        }
10456
10457        void cleanUpResourcesLI() {
10458            // Try enumerating all code paths before deleting
10459            List<String> allCodePaths = Collections.EMPTY_LIST;
10460            if (codeFile != null && codeFile.exists()) {
10461                try {
10462                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
10463                    allCodePaths = pkg.getAllCodePaths();
10464                } catch (PackageParserException e) {
10465                    // Ignored; we tried our best
10466                }
10467            }
10468
10469            cleanUp();
10470            removeDexFiles(allCodePaths, instructionSets);
10471        }
10472
10473        boolean doPostDeleteLI(boolean delete) {
10474            // XXX err, shouldn't we respect the delete flag?
10475            cleanUpResourcesLI();
10476            return true;
10477        }
10478    }
10479
10480    private boolean isAsecExternal(String cid) {
10481        final String asecPath = PackageHelper.getSdFilesystem(cid);
10482        return !asecPath.startsWith(mAsecInternalPath);
10483    }
10484
10485    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
10486            PackageManagerException {
10487        if (copyRet < 0) {
10488            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
10489                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
10490                throw new PackageManagerException(copyRet, message);
10491            }
10492        }
10493    }
10494
10495    /**
10496     * Extract the MountService "container ID" from the full code path of an
10497     * .apk.
10498     */
10499    static String cidFromCodePath(String fullCodePath) {
10500        int eidx = fullCodePath.lastIndexOf("/");
10501        String subStr1 = fullCodePath.substring(0, eidx);
10502        int sidx = subStr1.lastIndexOf("/");
10503        return subStr1.substring(sidx+1, eidx);
10504    }
10505
10506    /**
10507     * Logic to handle installation of ASEC applications, including copying and
10508     * renaming logic.
10509     */
10510    class AsecInstallArgs extends InstallArgs {
10511        static final String RES_FILE_NAME = "pkg.apk";
10512        static final String PUBLIC_RES_FILE_NAME = "res.zip";
10513
10514        String cid;
10515        String packagePath;
10516        String resourcePath;
10517
10518        /** New install */
10519        AsecInstallArgs(InstallParams params) {
10520            super(params.origin, params.move, params.observer, params.installFlags,
10521                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10522                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10523        }
10524
10525        /** Existing install */
10526        AsecInstallArgs(String fullCodePath, String[] instructionSets,
10527                        boolean isExternal, boolean isForwardLocked) {
10528            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
10529                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
10530                    instructionSets, null);
10531            // Hackily pretend we're still looking at a full code path
10532            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
10533                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
10534            }
10535
10536            // Extract cid from fullCodePath
10537            int eidx = fullCodePath.lastIndexOf("/");
10538            String subStr1 = fullCodePath.substring(0, eidx);
10539            int sidx = subStr1.lastIndexOf("/");
10540            cid = subStr1.substring(sidx+1, eidx);
10541            setMountPath(subStr1);
10542        }
10543
10544        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
10545            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
10546                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
10547                    instructionSets, null);
10548            this.cid = cid;
10549            setMountPath(PackageHelper.getSdDir(cid));
10550        }
10551
10552        void createCopyFile() {
10553            cid = mInstallerService.allocateExternalStageCidLegacy();
10554        }
10555
10556        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10557            if (origin.staged) {
10558                Slog.d(TAG, origin.cid + " already staged; skipping copy");
10559                cid = origin.cid;
10560                setMountPath(PackageHelper.getSdDir(cid));
10561                return PackageManager.INSTALL_SUCCEEDED;
10562            }
10563
10564            if (temp) {
10565                createCopyFile();
10566            } else {
10567                /*
10568                 * Pre-emptively destroy the container since it's destroyed if
10569                 * copying fails due to it existing anyway.
10570                 */
10571                PackageHelper.destroySdDir(cid);
10572            }
10573
10574            final String newMountPath = imcs.copyPackageToContainer(
10575                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
10576                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
10577
10578            if (newMountPath != null) {
10579                setMountPath(newMountPath);
10580                return PackageManager.INSTALL_SUCCEEDED;
10581            } else {
10582                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10583            }
10584        }
10585
10586        @Override
10587        String getCodePath() {
10588            return packagePath;
10589        }
10590
10591        @Override
10592        String getResourcePath() {
10593            return resourcePath;
10594        }
10595
10596        int doPreInstall(int status) {
10597            if (status != PackageManager.INSTALL_SUCCEEDED) {
10598                // Destroy container
10599                PackageHelper.destroySdDir(cid);
10600            } else {
10601                boolean mounted = PackageHelper.isContainerMounted(cid);
10602                if (!mounted) {
10603                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
10604                            Process.SYSTEM_UID);
10605                    if (newMountPath != null) {
10606                        setMountPath(newMountPath);
10607                    } else {
10608                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10609                    }
10610                }
10611            }
10612            return status;
10613        }
10614
10615        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10616            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
10617            String newMountPath = null;
10618            if (PackageHelper.isContainerMounted(cid)) {
10619                // Unmount the container
10620                if (!PackageHelper.unMountSdDir(cid)) {
10621                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
10622                    return false;
10623                }
10624            }
10625            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
10626                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
10627                        " which might be stale. Will try to clean up.");
10628                // Clean up the stale container and proceed to recreate.
10629                if (!PackageHelper.destroySdDir(newCacheId)) {
10630                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
10631                    return false;
10632                }
10633                // Successfully cleaned up stale container. Try to rename again.
10634                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
10635                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
10636                            + " inspite of cleaning it up.");
10637                    return false;
10638                }
10639            }
10640            if (!PackageHelper.isContainerMounted(newCacheId)) {
10641                Slog.w(TAG, "Mounting container " + newCacheId);
10642                newMountPath = PackageHelper.mountSdDir(newCacheId,
10643                        getEncryptKey(), Process.SYSTEM_UID);
10644            } else {
10645                newMountPath = PackageHelper.getSdDir(newCacheId);
10646            }
10647            if (newMountPath == null) {
10648                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
10649                return false;
10650            }
10651            Log.i(TAG, "Succesfully renamed " + cid +
10652                    " to " + newCacheId +
10653                    " at new path: " + newMountPath);
10654            cid = newCacheId;
10655
10656            final File beforeCodeFile = new File(packagePath);
10657            setMountPath(newMountPath);
10658            final File afterCodeFile = new File(packagePath);
10659
10660            // Reflect the rename in scanned details
10661            pkg.codePath = afterCodeFile.getAbsolutePath();
10662            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10663                    pkg.baseCodePath);
10664            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10665                    pkg.splitCodePaths);
10666
10667            // Reflect the rename in app info
10668            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10669            pkg.applicationInfo.setCodePath(pkg.codePath);
10670            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10671            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10672            pkg.applicationInfo.setResourcePath(pkg.codePath);
10673            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10674            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10675
10676            return true;
10677        }
10678
10679        private void setMountPath(String mountPath) {
10680            final File mountFile = new File(mountPath);
10681
10682            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
10683            if (monolithicFile.exists()) {
10684                packagePath = monolithicFile.getAbsolutePath();
10685                if (isFwdLocked()) {
10686                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
10687                } else {
10688                    resourcePath = packagePath;
10689                }
10690            } else {
10691                packagePath = mountFile.getAbsolutePath();
10692                resourcePath = packagePath;
10693            }
10694        }
10695
10696        int doPostInstall(int status, int uid) {
10697            if (status != PackageManager.INSTALL_SUCCEEDED) {
10698                cleanUp();
10699            } else {
10700                final int groupOwner;
10701                final String protectedFile;
10702                if (isFwdLocked()) {
10703                    groupOwner = UserHandle.getSharedAppGid(uid);
10704                    protectedFile = RES_FILE_NAME;
10705                } else {
10706                    groupOwner = -1;
10707                    protectedFile = null;
10708                }
10709
10710                if (uid < Process.FIRST_APPLICATION_UID
10711                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
10712                    Slog.e(TAG, "Failed to finalize " + cid);
10713                    PackageHelper.destroySdDir(cid);
10714                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10715                }
10716
10717                boolean mounted = PackageHelper.isContainerMounted(cid);
10718                if (!mounted) {
10719                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
10720                }
10721            }
10722            return status;
10723        }
10724
10725        private void cleanUp() {
10726            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
10727
10728            // Destroy secure container
10729            PackageHelper.destroySdDir(cid);
10730        }
10731
10732        private List<String> getAllCodePaths() {
10733            final File codeFile = new File(getCodePath());
10734            if (codeFile != null && codeFile.exists()) {
10735                try {
10736                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
10737                    return pkg.getAllCodePaths();
10738                } catch (PackageParserException e) {
10739                    // Ignored; we tried our best
10740                }
10741            }
10742            return Collections.EMPTY_LIST;
10743        }
10744
10745        void cleanUpResourcesLI() {
10746            // Enumerate all code paths before deleting
10747            cleanUpResourcesLI(getAllCodePaths());
10748        }
10749
10750        private void cleanUpResourcesLI(List<String> allCodePaths) {
10751            cleanUp();
10752            removeDexFiles(allCodePaths, instructionSets);
10753        }
10754
10755        String getPackageName() {
10756            return getAsecPackageName(cid);
10757        }
10758
10759        boolean doPostDeleteLI(boolean delete) {
10760            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
10761            final List<String> allCodePaths = getAllCodePaths();
10762            boolean mounted = PackageHelper.isContainerMounted(cid);
10763            if (mounted) {
10764                // Unmount first
10765                if (PackageHelper.unMountSdDir(cid)) {
10766                    mounted = false;
10767                }
10768            }
10769            if (!mounted && delete) {
10770                cleanUpResourcesLI(allCodePaths);
10771            }
10772            return !mounted;
10773        }
10774
10775        @Override
10776        int doPreCopy() {
10777            if (isFwdLocked()) {
10778                if (!PackageHelper.fixSdPermissions(cid,
10779                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
10780                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10781                }
10782            }
10783
10784            return PackageManager.INSTALL_SUCCEEDED;
10785        }
10786
10787        @Override
10788        int doPostCopy(int uid) {
10789            if (isFwdLocked()) {
10790                if (uid < Process.FIRST_APPLICATION_UID
10791                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
10792                                RES_FILE_NAME)) {
10793                    Slog.e(TAG, "Failed to finalize " + cid);
10794                    PackageHelper.destroySdDir(cid);
10795                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10796                }
10797            }
10798
10799            return PackageManager.INSTALL_SUCCEEDED;
10800        }
10801    }
10802
10803    /**
10804     * Logic to handle movement of existing installed applications.
10805     */
10806    class MoveInstallArgs extends InstallArgs {
10807        private File codeFile;
10808        private File resourceFile;
10809
10810        /** New install */
10811        MoveInstallArgs(InstallParams params) {
10812            super(params.origin, params.move, params.observer, params.installFlags,
10813                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10814                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10815        }
10816
10817        int copyApk(IMediaContainerService imcs, boolean temp) {
10818            Slog.d(TAG, "Moving " + move.packageName + " from " + move.fromUuid + " to "
10819                    + move.toUuid);
10820            synchronized (mInstaller) {
10821                if (mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
10822                        move.dataAppName, move.appId, move.seinfo) != 0) {
10823                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10824                }
10825            }
10826
10827            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
10828            resourceFile = codeFile;
10829            Slog.d(TAG, "codeFile after move is " + codeFile);
10830
10831            return PackageManager.INSTALL_SUCCEEDED;
10832        }
10833
10834        int doPreInstall(int status) {
10835            if (status != PackageManager.INSTALL_SUCCEEDED) {
10836                cleanUp();
10837            }
10838            return status;
10839        }
10840
10841        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10842            if (status != PackageManager.INSTALL_SUCCEEDED) {
10843                cleanUp();
10844                return false;
10845            }
10846
10847            // Reflect the move in app info
10848            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10849            pkg.applicationInfo.setCodePath(pkg.codePath);
10850            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10851            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10852            pkg.applicationInfo.setResourcePath(pkg.codePath);
10853            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10854            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10855
10856            return true;
10857        }
10858
10859        int doPostInstall(int status, int uid) {
10860            if (status != PackageManager.INSTALL_SUCCEEDED) {
10861                cleanUp();
10862            }
10863            return status;
10864        }
10865
10866        @Override
10867        String getCodePath() {
10868            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
10869        }
10870
10871        @Override
10872        String getResourcePath() {
10873            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
10874        }
10875
10876        private boolean cleanUp() {
10877            if (codeFile == null || !codeFile.exists()) {
10878                return false;
10879            }
10880
10881            if (codeFile.isDirectory()) {
10882                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
10883            } else {
10884                codeFile.delete();
10885            }
10886
10887            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
10888                resourceFile.delete();
10889            }
10890
10891            return true;
10892        }
10893
10894        void cleanUpResourcesLI() {
10895            cleanUp();
10896        }
10897
10898        boolean doPostDeleteLI(boolean delete) {
10899            // XXX err, shouldn't we respect the delete flag?
10900            cleanUpResourcesLI();
10901            return true;
10902        }
10903    }
10904
10905    static String getAsecPackageName(String packageCid) {
10906        int idx = packageCid.lastIndexOf("-");
10907        if (idx == -1) {
10908            return packageCid;
10909        }
10910        return packageCid.substring(0, idx);
10911    }
10912
10913    // Utility method used to create code paths based on package name and available index.
10914    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
10915        String idxStr = "";
10916        int idx = 1;
10917        // Fall back to default value of idx=1 if prefix is not
10918        // part of oldCodePath
10919        if (oldCodePath != null) {
10920            String subStr = oldCodePath;
10921            // Drop the suffix right away
10922            if (suffix != null && subStr.endsWith(suffix)) {
10923                subStr = subStr.substring(0, subStr.length() - suffix.length());
10924            }
10925            // If oldCodePath already contains prefix find out the
10926            // ending index to either increment or decrement.
10927            int sidx = subStr.lastIndexOf(prefix);
10928            if (sidx != -1) {
10929                subStr = subStr.substring(sidx + prefix.length());
10930                if (subStr != null) {
10931                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
10932                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
10933                    }
10934                    try {
10935                        idx = Integer.parseInt(subStr);
10936                        if (idx <= 1) {
10937                            idx++;
10938                        } else {
10939                            idx--;
10940                        }
10941                    } catch(NumberFormatException e) {
10942                    }
10943                }
10944            }
10945        }
10946        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
10947        return prefix + idxStr;
10948    }
10949
10950    private File getNextCodePath(File targetDir, String packageName) {
10951        int suffix = 1;
10952        File result;
10953        do {
10954            result = new File(targetDir, packageName + "-" + suffix);
10955            suffix++;
10956        } while (result.exists());
10957        return result;
10958    }
10959
10960    // Utility method that returns the relative package path with respect
10961    // to the installation directory. Like say for /data/data/com.test-1.apk
10962    // string com.test-1 is returned.
10963    static String deriveCodePathName(String codePath) {
10964        if (codePath == null) {
10965            return null;
10966        }
10967        final File codeFile = new File(codePath);
10968        final String name = codeFile.getName();
10969        if (codeFile.isDirectory()) {
10970            return name;
10971        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
10972            final int lastDot = name.lastIndexOf('.');
10973            return name.substring(0, lastDot);
10974        } else {
10975            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
10976            return null;
10977        }
10978    }
10979
10980    class PackageInstalledInfo {
10981        String name;
10982        int uid;
10983        // The set of users that originally had this package installed.
10984        int[] origUsers;
10985        // The set of users that now have this package installed.
10986        int[] newUsers;
10987        PackageParser.Package pkg;
10988        int returnCode;
10989        String returnMsg;
10990        PackageRemovedInfo removedInfo;
10991
10992        public void setError(int code, String msg) {
10993            returnCode = code;
10994            returnMsg = msg;
10995            Slog.w(TAG, msg);
10996        }
10997
10998        public void setError(String msg, PackageParserException e) {
10999            returnCode = e.error;
11000            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11001            Slog.w(TAG, msg, e);
11002        }
11003
11004        public void setError(String msg, PackageManagerException e) {
11005            returnCode = e.error;
11006            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11007            Slog.w(TAG, msg, e);
11008        }
11009
11010        // In some error cases we want to convey more info back to the observer
11011        String origPackage;
11012        String origPermission;
11013    }
11014
11015    /*
11016     * Install a non-existing package.
11017     */
11018    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11019            UserHandle user, String installerPackageName, String volumeUuid,
11020            PackageInstalledInfo res) {
11021        // Remember this for later, in case we need to rollback this install
11022        String pkgName = pkg.packageName;
11023
11024        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
11025        final boolean dataDirExists = PackageManager.getDataDirForUser(volumeUuid, pkgName,
11026                UserHandle.USER_OWNER).exists();
11027        synchronized(mPackages) {
11028            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
11029                // A package with the same name is already installed, though
11030                // it has been renamed to an older name.  The package we
11031                // are trying to install should be installed as an update to
11032                // the existing one, but that has not been requested, so bail.
11033                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11034                        + " without first uninstalling package running as "
11035                        + mSettings.mRenamedPackages.get(pkgName));
11036                return;
11037            }
11038            if (mPackages.containsKey(pkgName)) {
11039                // Don't allow installation over an existing package with the same name.
11040                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11041                        + " without first uninstalling.");
11042                return;
11043            }
11044        }
11045
11046        try {
11047            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
11048                    System.currentTimeMillis(), user);
11049
11050            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
11051            // delete the partially installed application. the data directory will have to be
11052            // restored if it was already existing
11053            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11054                // remove package from internal structures.  Note that we want deletePackageX to
11055                // delete the package data and cache directories that it created in
11056                // scanPackageLocked, unless those directories existed before we even tried to
11057                // install.
11058                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
11059                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
11060                                res.removedInfo, true);
11061            }
11062
11063        } catch (PackageManagerException e) {
11064            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11065        }
11066    }
11067
11068    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
11069        // Upgrade keysets are being used.  Determine if new package has a superset of the
11070        // required keys.
11071        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
11072        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11073        for (int i = 0; i < upgradeKeySets.length; i++) {
11074            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
11075            if (newPkg.mSigningKeys.containsAll(upgradeSet)) {
11076                return true;
11077            }
11078        }
11079        return false;
11080    }
11081
11082    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11083            UserHandle user, String installerPackageName, String volumeUuid,
11084            PackageInstalledInfo res) {
11085        final PackageParser.Package oldPackage;
11086        final String pkgName = pkg.packageName;
11087        final int[] allUsers;
11088        final boolean[] perUserInstalled;
11089        final boolean weFroze;
11090
11091        // First find the old package info and check signatures
11092        synchronized(mPackages) {
11093            oldPackage = mPackages.get(pkgName);
11094            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
11095            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11096            if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
11097                // default to original signature matching
11098                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
11099                    != PackageManager.SIGNATURE_MATCH) {
11100                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11101                            "New package has a different signature: " + pkgName);
11102                    return;
11103                }
11104            } else {
11105                if(!checkUpgradeKeySetLP(ps, pkg)) {
11106                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11107                            "New package not signed by keys specified by upgrade-keysets: "
11108                            + pkgName);
11109                    return;
11110                }
11111            }
11112
11113            // In case of rollback, remember per-user/profile install state
11114            allUsers = sUserManager.getUserIds();
11115            perUserInstalled = new boolean[allUsers.length];
11116            for (int i = 0; i < allUsers.length; i++) {
11117                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11118            }
11119
11120            // Mark the app as frozen to prevent launching during the upgrade
11121            // process, and then kill all running instances
11122            if (!ps.frozen) {
11123                ps.frozen = true;
11124                weFroze = true;
11125            } else {
11126                weFroze = false;
11127            }
11128        }
11129
11130        // Now that we're guarded by frozen state, kill app during upgrade
11131        killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg");
11132
11133        try {
11134            boolean sysPkg = (isSystemApp(oldPackage));
11135            if (sysPkg) {
11136                replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11137                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11138            } else {
11139                replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11140                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11141            }
11142        } finally {
11143            // Regardless of success or failure of upgrade steps above, always
11144            // unfreeze the package if we froze it
11145            if (weFroze) {
11146                unfreezePackage(pkgName);
11147            }
11148        }
11149    }
11150
11151    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
11152            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11153            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11154            String volumeUuid, PackageInstalledInfo res) {
11155        String pkgName = deletedPackage.packageName;
11156        boolean deletedPkg = true;
11157        boolean updatedSettings = false;
11158
11159        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
11160                + deletedPackage);
11161        long origUpdateTime;
11162        if (pkg.mExtras != null) {
11163            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
11164        } else {
11165            origUpdateTime = 0;
11166        }
11167
11168        // First delete the existing package while retaining the data directory
11169        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
11170                res.removedInfo, true)) {
11171            // If the existing package wasn't successfully deleted
11172            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
11173            deletedPkg = false;
11174        } else {
11175            // Successfully deleted the old package; proceed with replace.
11176
11177            // If deleted package lived in a container, give users a chance to
11178            // relinquish resources before killing.
11179            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
11180                if (DEBUG_INSTALL) {
11181                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
11182                }
11183                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
11184                final ArrayList<String> pkgList = new ArrayList<String>(1);
11185                pkgList.add(deletedPackage.applicationInfo.packageName);
11186                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
11187            }
11188
11189            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
11190            try {
11191                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
11192                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
11193                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11194                        perUserInstalled, res, user);
11195                updatedSettings = true;
11196            } catch (PackageManagerException e) {
11197                res.setError("Package couldn't be installed in " + pkg.codePath, e);
11198            }
11199        }
11200
11201        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11202            // remove package from internal structures.  Note that we want deletePackageX to
11203            // delete the package data and cache directories that it created in
11204            // scanPackageLocked, unless those directories existed before we even tried to
11205            // install.
11206            if(updatedSettings) {
11207                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
11208                deletePackageLI(
11209                        pkgName, null, true, allUsers, perUserInstalled,
11210                        PackageManager.DELETE_KEEP_DATA,
11211                                res.removedInfo, true);
11212            }
11213            // Since we failed to install the new package we need to restore the old
11214            // package that we deleted.
11215            if (deletedPkg) {
11216                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
11217                File restoreFile = new File(deletedPackage.codePath);
11218                // Parse old package
11219                boolean oldExternal = isExternal(deletedPackage);
11220                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
11221                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
11222                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11223                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
11224                try {
11225                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
11226                } catch (PackageManagerException e) {
11227                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
11228                            + e.getMessage());
11229                    return;
11230                }
11231                // Restore of old package succeeded. Update permissions.
11232                // writer
11233                synchronized (mPackages) {
11234                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
11235                            UPDATE_PERMISSIONS_ALL);
11236                    // can downgrade to reader
11237                    mSettings.writeLPr();
11238                }
11239                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
11240            }
11241        }
11242    }
11243
11244    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
11245            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11246            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11247            String volumeUuid, PackageInstalledInfo res) {
11248        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
11249                + ", old=" + deletedPackage);
11250        boolean disabledSystem = false;
11251        boolean updatedSettings = false;
11252        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
11253        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
11254                != 0) {
11255            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11256        }
11257        String packageName = deletedPackage.packageName;
11258        if (packageName == null) {
11259            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11260                    "Attempt to delete null packageName.");
11261            return;
11262        }
11263        PackageParser.Package oldPkg;
11264        PackageSetting oldPkgSetting;
11265        // reader
11266        synchronized (mPackages) {
11267            oldPkg = mPackages.get(packageName);
11268            oldPkgSetting = mSettings.mPackages.get(packageName);
11269            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
11270                    (oldPkgSetting == null)) {
11271                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11272                        "Couldn't find package:" + packageName + " information");
11273                return;
11274            }
11275        }
11276
11277        res.removedInfo.uid = oldPkg.applicationInfo.uid;
11278        res.removedInfo.removedPackage = packageName;
11279        // Remove existing system package
11280        removePackageLI(oldPkgSetting, true);
11281        // writer
11282        synchronized (mPackages) {
11283            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
11284            if (!disabledSystem && deletedPackage != null) {
11285                // We didn't need to disable the .apk as a current system package,
11286                // which means we are replacing another update that is already
11287                // installed.  We need to make sure to delete the older one's .apk.
11288                res.removedInfo.args = createInstallArgsForExisting(0,
11289                        deletedPackage.applicationInfo.getCodePath(),
11290                        deletedPackage.applicationInfo.getResourcePath(),
11291                        getAppDexInstructionSets(deletedPackage.applicationInfo));
11292            } else {
11293                res.removedInfo.args = null;
11294            }
11295        }
11296
11297        // Successfully disabled the old package. Now proceed with re-installation
11298        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
11299
11300        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11301        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
11302
11303        PackageParser.Package newPackage = null;
11304        try {
11305            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
11306            if (newPackage.mExtras != null) {
11307                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
11308                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
11309                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
11310
11311                // is the update attempting to change shared user? that isn't going to work...
11312                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
11313                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
11314                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
11315                            + " to " + newPkgSetting.sharedUser);
11316                    updatedSettings = true;
11317                }
11318            }
11319
11320            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11321                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11322                        perUserInstalled, res, user);
11323                updatedSettings = true;
11324            }
11325
11326        } catch (PackageManagerException e) {
11327            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11328        }
11329
11330        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11331            // Re installation failed. Restore old information
11332            // Remove new pkg information
11333            if (newPackage != null) {
11334                removeInstalledPackageLI(newPackage, true);
11335            }
11336            // Add back the old system package
11337            try {
11338                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
11339            } catch (PackageManagerException e) {
11340                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
11341            }
11342            // Restore the old system information in Settings
11343            synchronized (mPackages) {
11344                if (disabledSystem) {
11345                    mSettings.enableSystemPackageLPw(packageName);
11346                }
11347                if (updatedSettings) {
11348                    mSettings.setInstallerPackageName(packageName,
11349                            oldPkgSetting.installerPackageName);
11350                }
11351                mSettings.writeLPr();
11352            }
11353        }
11354    }
11355
11356    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
11357            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
11358            UserHandle user) {
11359        String pkgName = newPackage.packageName;
11360        synchronized (mPackages) {
11361            //write settings. the installStatus will be incomplete at this stage.
11362            //note that the new package setting would have already been
11363            //added to mPackages. It hasn't been persisted yet.
11364            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
11365            mSettings.writeLPr();
11366        }
11367
11368        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
11369
11370        synchronized (mPackages) {
11371            updatePermissionsLPw(newPackage.packageName, newPackage,
11372                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
11373                            ? UPDATE_PERMISSIONS_ALL : 0));
11374            // For system-bundled packages, we assume that installing an upgraded version
11375            // of the package implies that the user actually wants to run that new code,
11376            // so we enable the package.
11377            PackageSetting ps = mSettings.mPackages.get(pkgName);
11378            if (ps != null) {
11379                if (isSystemApp(newPackage)) {
11380                    // NB: implicit assumption that system package upgrades apply to all users
11381                    if (DEBUG_INSTALL) {
11382                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
11383                    }
11384                    if (res.origUsers != null) {
11385                        for (int userHandle : res.origUsers) {
11386                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
11387                                    userHandle, installerPackageName);
11388                        }
11389                    }
11390                    // Also convey the prior install/uninstall state
11391                    if (allUsers != null && perUserInstalled != null) {
11392                        for (int i = 0; i < allUsers.length; i++) {
11393                            if (DEBUG_INSTALL) {
11394                                Slog.d(TAG, "    user " + allUsers[i]
11395                                        + " => " + perUserInstalled[i]);
11396                            }
11397                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
11398                        }
11399                        // these install state changes will be persisted in the
11400                        // upcoming call to mSettings.writeLPr().
11401                    }
11402                }
11403                // It's implied that when a user requests installation, they want the app to be
11404                // installed and enabled.
11405                int userId = user.getIdentifier();
11406                if (userId != UserHandle.USER_ALL) {
11407                    ps.setInstalled(true, userId);
11408                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
11409                }
11410            }
11411            res.name = pkgName;
11412            res.uid = newPackage.applicationInfo.uid;
11413            res.pkg = newPackage;
11414            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
11415            mSettings.setInstallerPackageName(pkgName, installerPackageName);
11416            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11417            //to update install status
11418            mSettings.writeLPr();
11419        }
11420    }
11421
11422    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
11423        final int installFlags = args.installFlags;
11424        final String installerPackageName = args.installerPackageName;
11425        final String volumeUuid = args.volumeUuid;
11426        final File tmpPackageFile = new File(args.getCodePath());
11427        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
11428        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
11429                || (args.volumeUuid != null));
11430        boolean replace = false;
11431        int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE;
11432        // Result object to be returned
11433        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11434
11435        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
11436        // Retrieve PackageSettings and parse package
11437        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
11438                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
11439                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11440        PackageParser pp = new PackageParser();
11441        pp.setSeparateProcesses(mSeparateProcesses);
11442        pp.setDisplayMetrics(mMetrics);
11443
11444        final PackageParser.Package pkg;
11445        try {
11446            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
11447        } catch (PackageParserException e) {
11448            res.setError("Failed parse during installPackageLI", e);
11449            return;
11450        }
11451
11452        // Mark that we have an install time CPU ABI override.
11453        pkg.cpuAbiOverride = args.abiOverride;
11454
11455        String pkgName = res.name = pkg.packageName;
11456        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
11457            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
11458                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
11459                return;
11460            }
11461        }
11462
11463        try {
11464            pp.collectCertificates(pkg, parseFlags);
11465            pp.collectManifestDigest(pkg);
11466        } catch (PackageParserException e) {
11467            res.setError("Failed collect during installPackageLI", e);
11468            return;
11469        }
11470
11471        /* If the installer passed in a manifest digest, compare it now. */
11472        if (args.manifestDigest != null) {
11473            if (DEBUG_INSTALL) {
11474                final String parsedManifest = pkg.manifestDigest == null ? "null"
11475                        : pkg.manifestDigest.toString();
11476                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
11477                        + parsedManifest);
11478            }
11479
11480            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
11481                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
11482                return;
11483            }
11484        } else if (DEBUG_INSTALL) {
11485            final String parsedManifest = pkg.manifestDigest == null
11486                    ? "null" : pkg.manifestDigest.toString();
11487            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
11488        }
11489
11490        // Get rid of all references to package scan path via parser.
11491        pp = null;
11492        String oldCodePath = null;
11493        boolean systemApp = false;
11494        synchronized (mPackages) {
11495            // Check if installing already existing package
11496            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
11497                String oldName = mSettings.mRenamedPackages.get(pkgName);
11498                if (pkg.mOriginalPackages != null
11499                        && pkg.mOriginalPackages.contains(oldName)
11500                        && mPackages.containsKey(oldName)) {
11501                    // This package is derived from an original package,
11502                    // and this device has been updating from that original
11503                    // name.  We must continue using the original name, so
11504                    // rename the new package here.
11505                    pkg.setPackageName(oldName);
11506                    pkgName = pkg.packageName;
11507                    replace = true;
11508                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
11509                            + oldName + " pkgName=" + pkgName);
11510                } else if (mPackages.containsKey(pkgName)) {
11511                    // This package, under its official name, already exists
11512                    // on the device; we should replace it.
11513                    replace = true;
11514                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
11515                }
11516
11517                // Prevent apps opting out from runtime permissions
11518                if (replace) {
11519                    PackageParser.Package oldPackage = mPackages.get(pkgName);
11520                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
11521                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
11522                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
11523                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
11524                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
11525                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
11526                                        + " doesn't support runtime permissions but the old"
11527                                        + " target SDK " + oldTargetSdk + " does.");
11528                        return;
11529                    }
11530                }
11531            }
11532
11533            PackageSetting ps = mSettings.mPackages.get(pkgName);
11534            if (ps != null) {
11535                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
11536
11537                // Quick sanity check that we're signed correctly if updating;
11538                // we'll check this again later when scanning, but we want to
11539                // bail early here before tripping over redefined permissions.
11540                if (!ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
11541                    try {
11542                        verifySignaturesLP(ps, pkg);
11543                    } catch (PackageManagerException e) {
11544                        res.setError(e.error, e.getMessage());
11545                        return;
11546                    }
11547                } else {
11548                    if (!checkUpgradeKeySetLP(ps, pkg)) {
11549                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
11550                                + pkg.packageName + " upgrade keys do not match the "
11551                                + "previously installed version");
11552                        return;
11553                    }
11554                }
11555
11556                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
11557                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
11558                    systemApp = (ps.pkg.applicationInfo.flags &
11559                            ApplicationInfo.FLAG_SYSTEM) != 0;
11560                }
11561                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
11562            }
11563
11564            // Check whether the newly-scanned package wants to define an already-defined perm
11565            int N = pkg.permissions.size();
11566            for (int i = N-1; i >= 0; i--) {
11567                PackageParser.Permission perm = pkg.permissions.get(i);
11568                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
11569                if (bp != null) {
11570                    // If the defining package is signed with our cert, it's okay.  This
11571                    // also includes the "updating the same package" case, of course.
11572                    // "updating same package" could also involve key-rotation.
11573                    final boolean sigsOk;
11574                    if (!bp.sourcePackage.equals(pkg.packageName)
11575                            || !(bp.packageSetting instanceof PackageSetting)
11576                            || !bp.packageSetting.keySetData.isUsingUpgradeKeySets()
11577                            || ((PackageSetting) bp.packageSetting).sharedUser != null) {
11578                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
11579                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
11580                    } else {
11581                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
11582                    }
11583                    if (!sigsOk) {
11584                        // If the owning package is the system itself, we log but allow
11585                        // install to proceed; we fail the install on all other permission
11586                        // redefinitions.
11587                        if (!bp.sourcePackage.equals("android")) {
11588                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
11589                                    + pkg.packageName + " attempting to redeclare permission "
11590                                    + perm.info.name + " already owned by " + bp.sourcePackage);
11591                            res.origPermission = perm.info.name;
11592                            res.origPackage = bp.sourcePackage;
11593                            return;
11594                        } else {
11595                            Slog.w(TAG, "Package " + pkg.packageName
11596                                    + " attempting to redeclare system permission "
11597                                    + perm.info.name + "; ignoring new declaration");
11598                            pkg.permissions.remove(i);
11599                        }
11600                    }
11601                }
11602            }
11603
11604        }
11605
11606        if (systemApp && onExternal) {
11607            // Disable updates to system apps on sdcard
11608            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
11609                    "Cannot install updates to system apps on sdcard");
11610            return;
11611        }
11612
11613        if (args.move != null) {
11614            // We did an in-place move, so dex is ready to roll
11615            scanFlags |= SCAN_NO_DEX;
11616        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
11617            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
11618            scanFlags |= SCAN_NO_DEX;
11619
11620            try {
11621                deriveNonSystemPackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
11622                        true /* extract libs */);
11623            } catch (PackageManagerException pme) {
11624                Slog.e(TAG, "Error deriving application ABI", pme);
11625                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error ");
11626                return;
11627            }
11628
11629            // Run dexopt before old package gets removed, to minimize time when app is unavailable
11630            int result = mPackageDexOptimizer
11631                    .performDexOpt(pkg, null /* instruction sets */, true /* forceDex */,
11632                            false /* defer */, false /* inclDependencies */);
11633            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
11634                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
11635                return;
11636            }
11637        }
11638
11639        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
11640            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
11641            return;
11642        }
11643
11644        startIntentFilterVerifications(args.user.getIdentifier(), pkg);
11645
11646        if (replace) {
11647            replacePackageLI(pkg, parseFlags, scanFlags, args.user,
11648                    installerPackageName, volumeUuid, res);
11649        } else {
11650            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
11651                    args.user, installerPackageName, volumeUuid, res);
11652        }
11653        synchronized (mPackages) {
11654            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11655            if (ps != null) {
11656                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
11657            }
11658        }
11659    }
11660
11661    private void startIntentFilterVerifications(int userId, PackageParser.Package pkg) {
11662        if (mIntentFilterVerifierComponent == null) {
11663            Slog.d(TAG, "No IntentFilter verification will not be done as "
11664                    + "there is no IntentFilterVerifier available!");
11665            return;
11666        }
11667
11668        final int verifierUid = getPackageUid(
11669                mIntentFilterVerifierComponent.getPackageName(),
11670                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
11671
11672        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
11673        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
11674        msg.obj = pkg;
11675        msg.arg1 = userId;
11676        msg.arg2 = verifierUid;
11677
11678        mHandler.sendMessage(msg);
11679    }
11680
11681    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid,
11682            PackageParser.Package pkg) {
11683        int size = pkg.activities.size();
11684        if (size == 0) {
11685            Slog.d(TAG, "No activity, so no need to verify any IntentFilter!");
11686            return;
11687        }
11688
11689        final boolean hasDomainURLs = hasDomainURLs(pkg);
11690        if (!hasDomainURLs) {
11691            Slog.d(TAG, "No domain URLs, so no need to verify any IntentFilter!");
11692            return;
11693        }
11694
11695        Slog.d(TAG, "Checking for userId:" + userId + " if any IntentFilter from the " + size
11696                + " Activities needs verification ...");
11697
11698        final int verificationId = mIntentFilterVerificationToken++;
11699        int count = 0;
11700        final String packageName = pkg.packageName;
11701        ArrayList<String> allHosts = new ArrayList<>();
11702
11703        synchronized (mPackages) {
11704            for (PackageParser.Activity a : pkg.activities) {
11705                for (ActivityIntentInfo filter : a.intents) {
11706                    boolean needsFilterVerification = filter.needsVerification();
11707                    if (needsFilterVerification && needsNetworkVerificationLPr(filter)) {
11708                        Slog.d(TAG, "Verification needed for IntentFilter:" + filter.toString());
11709                        mIntentFilterVerifier.addOneIntentFilterVerification(
11710                                verifierUid, userId, verificationId, filter, packageName);
11711                        count++;
11712                    } else if (!needsFilterVerification) {
11713                        Slog.d(TAG, "No verification needed for IntentFilter:" + filter.toString());
11714                        if (hasValidDomains(filter)) {
11715                            ArrayList<String> hosts = filter.getHostsList();
11716                            if (hosts.size() > 0) {
11717                                allHosts.addAll(hosts);
11718                            } else {
11719                                if (allHosts.isEmpty()) {
11720                                    allHosts.add("*");
11721                                }
11722                            }
11723                        }
11724                    } else {
11725                        Slog.d(TAG, "Verification already done for IntentFilter:"
11726                                + filter.toString());
11727                    }
11728                }
11729            }
11730        }
11731
11732        if (count > 0) {
11733            mIntentFilterVerifier.startVerifications(userId);
11734            Slog.d(TAG, "Started " + count + " IntentFilter verification"
11735                    + (count > 1 ? "s" : "") +  " for userId:" + userId + "!");
11736        } else {
11737            Slog.d(TAG, "No need to start any IntentFilter verification!");
11738            if (allHosts.size() > 0 && mSettings.createIntentFilterVerificationIfNeededLPw(
11739                    packageName, allHosts) != null) {
11740                scheduleWriteSettingsLocked();
11741            }
11742        }
11743    }
11744
11745    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
11746        final ComponentName cn  = filter.activity.getComponentName();
11747        final String packageName = cn.getPackageName();
11748
11749        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
11750                packageName);
11751        if (ivi == null) {
11752            return true;
11753        }
11754        int status = ivi.getStatus();
11755        switch (status) {
11756            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
11757            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
11758                return true;
11759
11760            default:
11761                // Nothing to do
11762                return false;
11763        }
11764    }
11765
11766    private boolean isSystemComponentOrPersistentPrivApp(PackageParser.Package pkg) {
11767        return UserHandle.getAppId(pkg.applicationInfo.uid) < FIRST_APPLICATION_UID
11768                || ((pkg.applicationInfo.privateFlags
11769                        & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0
11770                && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0);
11771    }
11772
11773    private static boolean isMultiArch(PackageSetting ps) {
11774        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
11775    }
11776
11777    private static boolean isMultiArch(ApplicationInfo info) {
11778        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
11779    }
11780
11781    private static boolean isExternal(PackageParser.Package pkg) {
11782        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
11783    }
11784
11785    private static boolean isExternal(PackageSetting ps) {
11786        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
11787    }
11788
11789    private static boolean isExternal(ApplicationInfo info) {
11790        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
11791    }
11792
11793    private static boolean isSystemApp(PackageParser.Package pkg) {
11794        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
11795    }
11796
11797    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
11798        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
11799    }
11800
11801    private static boolean hasDomainURLs(PackageParser.Package pkg) {
11802        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
11803    }
11804
11805    private static boolean isSystemApp(PackageSetting ps) {
11806        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
11807    }
11808
11809    private static boolean isUpdatedSystemApp(PackageSetting ps) {
11810        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
11811    }
11812
11813    private int packageFlagsToInstallFlags(PackageSetting ps) {
11814        int installFlags = 0;
11815        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
11816            // This existing package was an external ASEC install when we have
11817            // the external flag without a UUID
11818            installFlags |= PackageManager.INSTALL_EXTERNAL;
11819        }
11820        if (ps.isForwardLocked()) {
11821            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
11822        }
11823        return installFlags;
11824    }
11825
11826    private void deleteTempPackageFiles() {
11827        final FilenameFilter filter = new FilenameFilter() {
11828            public boolean accept(File dir, String name) {
11829                return name.startsWith("vmdl") && name.endsWith(".tmp");
11830            }
11831        };
11832        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
11833            file.delete();
11834        }
11835    }
11836
11837    @Override
11838    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
11839            int flags) {
11840        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
11841                flags);
11842    }
11843
11844    @Override
11845    public void deletePackage(final String packageName,
11846            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
11847        mContext.enforceCallingOrSelfPermission(
11848                android.Manifest.permission.DELETE_PACKAGES, null);
11849        final int uid = Binder.getCallingUid();
11850        if (UserHandle.getUserId(uid) != userId) {
11851            mContext.enforceCallingPermission(
11852                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
11853                    "deletePackage for user " + userId);
11854        }
11855        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
11856            try {
11857                observer.onPackageDeleted(packageName,
11858                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
11859            } catch (RemoteException re) {
11860            }
11861            return;
11862        }
11863
11864        boolean uninstallBlocked = false;
11865        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
11866            int[] users = sUserManager.getUserIds();
11867            for (int i = 0; i < users.length; ++i) {
11868                if (getBlockUninstallForUser(packageName, users[i])) {
11869                    uninstallBlocked = true;
11870                    break;
11871                }
11872            }
11873        } else {
11874            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
11875        }
11876        if (uninstallBlocked) {
11877            try {
11878                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
11879                        null);
11880            } catch (RemoteException re) {
11881            }
11882            return;
11883        }
11884
11885        if (DEBUG_REMOVE) {
11886            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
11887        }
11888        // Queue up an async operation since the package deletion may take a little while.
11889        mHandler.post(new Runnable() {
11890            public void run() {
11891                mHandler.removeCallbacks(this);
11892                final int returnCode = deletePackageX(packageName, userId, flags);
11893                if (observer != null) {
11894                    try {
11895                        observer.onPackageDeleted(packageName, returnCode, null);
11896                    } catch (RemoteException e) {
11897                        Log.i(TAG, "Observer no longer exists.");
11898                    } //end catch
11899                } //end if
11900            } //end run
11901        });
11902    }
11903
11904    private boolean isPackageDeviceAdmin(String packageName, int userId) {
11905        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
11906                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
11907        try {
11908            if (dpm != null) {
11909                if (dpm.isDeviceOwner(packageName)) {
11910                    return true;
11911                }
11912                int[] users;
11913                if (userId == UserHandle.USER_ALL) {
11914                    users = sUserManager.getUserIds();
11915                } else {
11916                    users = new int[]{userId};
11917                }
11918                for (int i = 0; i < users.length; ++i) {
11919                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
11920                        return true;
11921                    }
11922                }
11923            }
11924        } catch (RemoteException e) {
11925        }
11926        return false;
11927    }
11928
11929    /**
11930     *  This method is an internal method that could be get invoked either
11931     *  to delete an installed package or to clean up a failed installation.
11932     *  After deleting an installed package, a broadcast is sent to notify any
11933     *  listeners that the package has been installed. For cleaning up a failed
11934     *  installation, the broadcast is not necessary since the package's
11935     *  installation wouldn't have sent the initial broadcast either
11936     *  The key steps in deleting a package are
11937     *  deleting the package information in internal structures like mPackages,
11938     *  deleting the packages base directories through installd
11939     *  updating mSettings to reflect current status
11940     *  persisting settings for later use
11941     *  sending a broadcast if necessary
11942     */
11943    private int deletePackageX(String packageName, int userId, int flags) {
11944        final PackageRemovedInfo info = new PackageRemovedInfo();
11945        final boolean res;
11946
11947        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
11948                ? UserHandle.ALL : new UserHandle(userId);
11949
11950        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
11951            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
11952            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
11953        }
11954
11955        boolean removedForAllUsers = false;
11956        boolean systemUpdate = false;
11957
11958        // for the uninstall-updates case and restricted profiles, remember the per-
11959        // userhandle installed state
11960        int[] allUsers;
11961        boolean[] perUserInstalled;
11962        synchronized (mPackages) {
11963            PackageSetting ps = mSettings.mPackages.get(packageName);
11964            allUsers = sUserManager.getUserIds();
11965            perUserInstalled = new boolean[allUsers.length];
11966            for (int i = 0; i < allUsers.length; i++) {
11967                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11968            }
11969        }
11970
11971        synchronized (mInstallLock) {
11972            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
11973            res = deletePackageLI(packageName, removeForUser,
11974                    true, allUsers, perUserInstalled,
11975                    flags | REMOVE_CHATTY, info, true);
11976            systemUpdate = info.isRemovedPackageSystemUpdate;
11977            if (res && !systemUpdate && mPackages.get(packageName) == null) {
11978                removedForAllUsers = true;
11979            }
11980            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
11981                    + " removedForAllUsers=" + removedForAllUsers);
11982        }
11983
11984        if (res) {
11985            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
11986
11987            // If the removed package was a system update, the old system package
11988            // was re-enabled; we need to broadcast this information
11989            if (systemUpdate) {
11990                Bundle extras = new Bundle(1);
11991                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
11992                        ? info.removedAppId : info.uid);
11993                extras.putBoolean(Intent.EXTRA_REPLACING, true);
11994
11995                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
11996                        extras, null, null, null);
11997                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
11998                        extras, null, null, null);
11999                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
12000                        null, packageName, null, null);
12001            }
12002        }
12003        // Force a gc here.
12004        Runtime.getRuntime().gc();
12005        // Delete the resources here after sending the broadcast to let
12006        // other processes clean up before deleting resources.
12007        if (info.args != null) {
12008            synchronized (mInstallLock) {
12009                info.args.doPostDeleteLI(true);
12010            }
12011        }
12012
12013        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
12014    }
12015
12016    class PackageRemovedInfo {
12017        String removedPackage;
12018        int uid = -1;
12019        int removedAppId = -1;
12020        int[] removedUsers = null;
12021        boolean isRemovedPackageSystemUpdate = false;
12022        // Clean up resources deleted packages.
12023        InstallArgs args = null;
12024
12025        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
12026            Bundle extras = new Bundle(1);
12027            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
12028            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
12029            if (replacing) {
12030                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12031            }
12032            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
12033            if (removedPackage != null) {
12034                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
12035                        extras, null, null, removedUsers);
12036                if (fullRemove && !replacing) {
12037                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
12038                            extras, null, null, removedUsers);
12039                }
12040            }
12041            if (removedAppId >= 0) {
12042                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
12043                        removedUsers);
12044            }
12045        }
12046    }
12047
12048    /*
12049     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
12050     * flag is not set, the data directory is removed as well.
12051     * make sure this flag is set for partially installed apps. If not its meaningless to
12052     * delete a partially installed application.
12053     */
12054    private void removePackageDataLI(PackageSetting ps,
12055            int[] allUserHandles, boolean[] perUserInstalled,
12056            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
12057        String packageName = ps.name;
12058        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
12059        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
12060        // Retrieve object to delete permissions for shared user later on
12061        final PackageSetting deletedPs;
12062        // reader
12063        synchronized (mPackages) {
12064            deletedPs = mSettings.mPackages.get(packageName);
12065            if (outInfo != null) {
12066                outInfo.removedPackage = packageName;
12067                outInfo.removedUsers = deletedPs != null
12068                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
12069                        : null;
12070            }
12071        }
12072        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12073            removeDataDirsLI(ps.volumeUuid, packageName);
12074            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
12075        }
12076        // writer
12077        synchronized (mPackages) {
12078            if (deletedPs != null) {
12079                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12080                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
12081                    clearDefaultBrowserIfNeeded(packageName);
12082                    if (outInfo != null) {
12083                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
12084                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
12085                    }
12086                    updatePermissionsLPw(deletedPs.name, null, 0);
12087                    if (deletedPs.sharedUser != null) {
12088                        // Remove permissions associated with package. Since runtime
12089                        // permissions are per user we have to kill the removed package
12090                        // or packages running under the shared user of the removed
12091                        // package if revoking the permissions requested only by the removed
12092                        // package is successful and this causes a change in gids.
12093                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12094                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
12095                                    userId);
12096                            if (userIdToKill == UserHandle.USER_ALL
12097                                    || userIdToKill >= UserHandle.USER_OWNER) {
12098                                // If gids changed for this user, kill all affected packages.
12099                                mHandler.post(new Runnable() {
12100                                    @Override
12101                                    public void run() {
12102                                        // This has to happen with no lock held.
12103                                        killSettingPackagesForUser(deletedPs, userIdToKill,
12104                                                KILL_APP_REASON_GIDS_CHANGED);
12105                                    }
12106                                });
12107                            break;
12108                            }
12109                        }
12110                    }
12111                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
12112                }
12113                // make sure to preserve per-user disabled state if this removal was just
12114                // a downgrade of a system app to the factory package
12115                if (allUserHandles != null && perUserInstalled != null) {
12116                    if (DEBUG_REMOVE) {
12117                        Slog.d(TAG, "Propagating install state across downgrade");
12118                    }
12119                    for (int i = 0; i < allUserHandles.length; i++) {
12120                        if (DEBUG_REMOVE) {
12121                            Slog.d(TAG, "    user " + allUserHandles[i]
12122                                    + " => " + perUserInstalled[i]);
12123                        }
12124                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12125                    }
12126                }
12127            }
12128            // can downgrade to reader
12129            if (writeSettings) {
12130                // Save settings now
12131                mSettings.writeLPr();
12132            }
12133        }
12134        if (outInfo != null) {
12135            // A user ID was deleted here. Go through all users and remove it
12136            // from KeyStore.
12137            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
12138        }
12139    }
12140
12141    static boolean locationIsPrivileged(File path) {
12142        try {
12143            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
12144                    .getCanonicalPath();
12145            return path.getCanonicalPath().startsWith(privilegedAppDir);
12146        } catch (IOException e) {
12147            Slog.e(TAG, "Unable to access code path " + path);
12148        }
12149        return false;
12150    }
12151
12152    /*
12153     * Tries to delete system package.
12154     */
12155    private boolean deleteSystemPackageLI(PackageSetting newPs,
12156            int[] allUserHandles, boolean[] perUserInstalled,
12157            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
12158        final boolean applyUserRestrictions
12159                = (allUserHandles != null) && (perUserInstalled != null);
12160        PackageSetting disabledPs = null;
12161        // Confirm if the system package has been updated
12162        // An updated system app can be deleted. This will also have to restore
12163        // the system pkg from system partition
12164        // reader
12165        synchronized (mPackages) {
12166            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
12167        }
12168        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
12169                + " disabledPs=" + disabledPs);
12170        if (disabledPs == null) {
12171            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
12172            return false;
12173        } else if (DEBUG_REMOVE) {
12174            Slog.d(TAG, "Deleting system pkg from data partition");
12175        }
12176        if (DEBUG_REMOVE) {
12177            if (applyUserRestrictions) {
12178                Slog.d(TAG, "Remembering install states:");
12179                for (int i = 0; i < allUserHandles.length; i++) {
12180                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
12181                }
12182            }
12183        }
12184        // Delete the updated package
12185        outInfo.isRemovedPackageSystemUpdate = true;
12186        if (disabledPs.versionCode < newPs.versionCode) {
12187            // Delete data for downgrades
12188            flags &= ~PackageManager.DELETE_KEEP_DATA;
12189        } else {
12190            // Preserve data by setting flag
12191            flags |= PackageManager.DELETE_KEEP_DATA;
12192        }
12193        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
12194                allUserHandles, perUserInstalled, outInfo, writeSettings);
12195        if (!ret) {
12196            return false;
12197        }
12198        // writer
12199        synchronized (mPackages) {
12200            // Reinstate the old system package
12201            mSettings.enableSystemPackageLPw(newPs.name);
12202            // Remove any native libraries from the upgraded package.
12203            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
12204        }
12205        // Install the system package
12206        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
12207        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
12208        if (locationIsPrivileged(disabledPs.codePath)) {
12209            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12210        }
12211
12212        final PackageParser.Package newPkg;
12213        try {
12214            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
12215        } catch (PackageManagerException e) {
12216            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
12217            return false;
12218        }
12219
12220        // writer
12221        synchronized (mPackages) {
12222            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
12223            updatePermissionsLPw(newPkg.packageName, newPkg,
12224                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
12225            if (applyUserRestrictions) {
12226                if (DEBUG_REMOVE) {
12227                    Slog.d(TAG, "Propagating install state across reinstall");
12228                }
12229                for (int i = 0; i < allUserHandles.length; i++) {
12230                    if (DEBUG_REMOVE) {
12231                        Slog.d(TAG, "    user " + allUserHandles[i]
12232                                + " => " + perUserInstalled[i]);
12233                    }
12234                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12235                }
12236                // Regardless of writeSettings we need to ensure that this restriction
12237                // state propagation is persisted
12238                mSettings.writeAllUsersPackageRestrictionsLPr();
12239            }
12240            // can downgrade to reader here
12241            if (writeSettings) {
12242                mSettings.writeLPr();
12243            }
12244        }
12245        return true;
12246    }
12247
12248    private boolean deleteInstalledPackageLI(PackageSetting ps,
12249            boolean deleteCodeAndResources, int flags,
12250            int[] allUserHandles, boolean[] perUserInstalled,
12251            PackageRemovedInfo outInfo, boolean writeSettings) {
12252        if (outInfo != null) {
12253            outInfo.uid = ps.appId;
12254        }
12255
12256        // Delete package data from internal structures and also remove data if flag is set
12257        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
12258
12259        // Delete application code and resources
12260        if (deleteCodeAndResources && (outInfo != null)) {
12261            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
12262                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
12263            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
12264        }
12265        return true;
12266    }
12267
12268    @Override
12269    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
12270            int userId) {
12271        mContext.enforceCallingOrSelfPermission(
12272                android.Manifest.permission.DELETE_PACKAGES, null);
12273        synchronized (mPackages) {
12274            PackageSetting ps = mSettings.mPackages.get(packageName);
12275            if (ps == null) {
12276                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
12277                return false;
12278            }
12279            if (!ps.getInstalled(userId)) {
12280                // Can't block uninstall for an app that is not installed or enabled.
12281                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
12282                return false;
12283            }
12284            ps.setBlockUninstall(blockUninstall, userId);
12285            mSettings.writePackageRestrictionsLPr(userId);
12286        }
12287        return true;
12288    }
12289
12290    @Override
12291    public boolean getBlockUninstallForUser(String packageName, int userId) {
12292        synchronized (mPackages) {
12293            PackageSetting ps = mSettings.mPackages.get(packageName);
12294            if (ps == null) {
12295                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
12296                return false;
12297            }
12298            return ps.getBlockUninstall(userId);
12299        }
12300    }
12301
12302    /*
12303     * This method handles package deletion in general
12304     */
12305    private boolean deletePackageLI(String packageName, UserHandle user,
12306            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
12307            int flags, PackageRemovedInfo outInfo,
12308            boolean writeSettings) {
12309        if (packageName == null) {
12310            Slog.w(TAG, "Attempt to delete null packageName.");
12311            return false;
12312        }
12313        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
12314        PackageSetting ps;
12315        boolean dataOnly = false;
12316        int removeUser = -1;
12317        int appId = -1;
12318        synchronized (mPackages) {
12319            ps = mSettings.mPackages.get(packageName);
12320            if (ps == null) {
12321                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12322                return false;
12323            }
12324            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
12325                    && user.getIdentifier() != UserHandle.USER_ALL) {
12326                // The caller is asking that the package only be deleted for a single
12327                // user.  To do this, we just mark its uninstalled state and delete
12328                // its data.  If this is a system app, we only allow this to happen if
12329                // they have set the special DELETE_SYSTEM_APP which requests different
12330                // semantics than normal for uninstalling system apps.
12331                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
12332                ps.setUserState(user.getIdentifier(),
12333                        COMPONENT_ENABLED_STATE_DEFAULT,
12334                        false, //installed
12335                        true,  //stopped
12336                        true,  //notLaunched
12337                        false, //hidden
12338                        null, null, null,
12339                        false, // blockUninstall
12340                        INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
12341                if (!isSystemApp(ps)) {
12342                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
12343                        // Other user still have this package installed, so all
12344                        // we need to do is clear this user's data and save that
12345                        // it is uninstalled.
12346                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
12347                        removeUser = user.getIdentifier();
12348                        appId = ps.appId;
12349                        scheduleWritePackageRestrictionsLocked(removeUser);
12350                    } else {
12351                        // We need to set it back to 'installed' so the uninstall
12352                        // broadcasts will be sent correctly.
12353                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
12354                        ps.setInstalled(true, user.getIdentifier());
12355                    }
12356                } else {
12357                    // This is a system app, so we assume that the
12358                    // other users still have this package installed, so all
12359                    // we need to do is clear this user's data and save that
12360                    // it is uninstalled.
12361                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
12362                    removeUser = user.getIdentifier();
12363                    appId = ps.appId;
12364                    scheduleWritePackageRestrictionsLocked(removeUser);
12365                }
12366            }
12367        }
12368
12369        if (removeUser >= 0) {
12370            // From above, we determined that we are deleting this only
12371            // for a single user.  Continue the work here.
12372            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
12373            if (outInfo != null) {
12374                outInfo.removedPackage = packageName;
12375                outInfo.removedAppId = appId;
12376                outInfo.removedUsers = new int[] {removeUser};
12377            }
12378            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
12379            removeKeystoreDataIfNeeded(removeUser, appId);
12380            schedulePackageCleaning(packageName, removeUser, false);
12381            synchronized (mPackages) {
12382                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
12383                    scheduleWritePackageRestrictionsLocked(removeUser);
12384                }
12385            }
12386            return true;
12387        }
12388
12389        if (dataOnly) {
12390            // Delete application data first
12391            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
12392            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
12393            return true;
12394        }
12395
12396        boolean ret = false;
12397        if (isSystemApp(ps)) {
12398            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
12399            // When an updated system application is deleted we delete the existing resources as well and
12400            // fall back to existing code in system partition
12401            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
12402                    flags, outInfo, writeSettings);
12403        } else {
12404            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
12405            // Kill application pre-emptively especially for apps on sd.
12406            killApplication(packageName, ps.appId, "uninstall pkg");
12407            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
12408                    allUserHandles, perUserInstalled,
12409                    outInfo, writeSettings);
12410        }
12411
12412        return ret;
12413    }
12414
12415    private final class ClearStorageConnection implements ServiceConnection {
12416        IMediaContainerService mContainerService;
12417
12418        @Override
12419        public void onServiceConnected(ComponentName name, IBinder service) {
12420            synchronized (this) {
12421                mContainerService = IMediaContainerService.Stub.asInterface(service);
12422                notifyAll();
12423            }
12424        }
12425
12426        @Override
12427        public void onServiceDisconnected(ComponentName name) {
12428        }
12429    }
12430
12431    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
12432        final boolean mounted;
12433        if (Environment.isExternalStorageEmulated()) {
12434            mounted = true;
12435        } else {
12436            final String status = Environment.getExternalStorageState();
12437
12438            mounted = status.equals(Environment.MEDIA_MOUNTED)
12439                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
12440        }
12441
12442        if (!mounted) {
12443            return;
12444        }
12445
12446        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
12447        int[] users;
12448        if (userId == UserHandle.USER_ALL) {
12449            users = sUserManager.getUserIds();
12450        } else {
12451            users = new int[] { userId };
12452        }
12453        final ClearStorageConnection conn = new ClearStorageConnection();
12454        if (mContext.bindServiceAsUser(
12455                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
12456            try {
12457                for (int curUser : users) {
12458                    long timeout = SystemClock.uptimeMillis() + 5000;
12459                    synchronized (conn) {
12460                        long now = SystemClock.uptimeMillis();
12461                        while (conn.mContainerService == null && now < timeout) {
12462                            try {
12463                                conn.wait(timeout - now);
12464                            } catch (InterruptedException e) {
12465                            }
12466                        }
12467                    }
12468                    if (conn.mContainerService == null) {
12469                        return;
12470                    }
12471
12472                    final UserEnvironment userEnv = new UserEnvironment(curUser);
12473                    clearDirectory(conn.mContainerService,
12474                            userEnv.buildExternalStorageAppCacheDirs(packageName));
12475                    if (allData) {
12476                        clearDirectory(conn.mContainerService,
12477                                userEnv.buildExternalStorageAppDataDirs(packageName));
12478                        clearDirectory(conn.mContainerService,
12479                                userEnv.buildExternalStorageAppMediaDirs(packageName));
12480                    }
12481                }
12482            } finally {
12483                mContext.unbindService(conn);
12484            }
12485        }
12486    }
12487
12488    @Override
12489    public void clearApplicationUserData(final String packageName,
12490            final IPackageDataObserver observer, final int userId) {
12491        mContext.enforceCallingOrSelfPermission(
12492                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
12493        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
12494        // Queue up an async operation since the package deletion may take a little while.
12495        mHandler.post(new Runnable() {
12496            public void run() {
12497                mHandler.removeCallbacks(this);
12498                final boolean succeeded;
12499                synchronized (mInstallLock) {
12500                    succeeded = clearApplicationUserDataLI(packageName, userId);
12501                }
12502                clearExternalStorageDataSync(packageName, userId, true);
12503                if (succeeded) {
12504                    // invoke DeviceStorageMonitor's update method to clear any notifications
12505                    DeviceStorageMonitorInternal
12506                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
12507                    if (dsm != null) {
12508                        dsm.checkMemory();
12509                    }
12510                }
12511                if(observer != null) {
12512                    try {
12513                        observer.onRemoveCompleted(packageName, succeeded);
12514                    } catch (RemoteException e) {
12515                        Log.i(TAG, "Observer no longer exists.");
12516                    }
12517                } //end if observer
12518            } //end run
12519        });
12520    }
12521
12522    private boolean clearApplicationUserDataLI(String packageName, int userId) {
12523        if (packageName == null) {
12524            Slog.w(TAG, "Attempt to delete null packageName.");
12525            return false;
12526        }
12527
12528        // Try finding details about the requested package
12529        PackageParser.Package pkg;
12530        synchronized (mPackages) {
12531            pkg = mPackages.get(packageName);
12532            if (pkg == null) {
12533                final PackageSetting ps = mSettings.mPackages.get(packageName);
12534                if (ps != null) {
12535                    pkg = ps.pkg;
12536                }
12537            }
12538        }
12539
12540        if (pkg == null) {
12541            Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12542        }
12543
12544        // Always delete data directories for package, even if we found no other
12545        // record of app. This helps users recover from UID mismatches without
12546        // resorting to a full data wipe.
12547        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
12548        if (retCode < 0) {
12549            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
12550            return false;
12551        }
12552
12553        if (pkg == null) {
12554            return false;
12555        }
12556
12557        if (pkg != null && pkg.applicationInfo != null) {
12558            final int appId = pkg.applicationInfo.uid;
12559            removeKeystoreDataIfNeeded(userId, appId);
12560        }
12561
12562        // Create a native library symlink only if we have native libraries
12563        // and if the native libraries are 32 bit libraries. We do not provide
12564        // this symlink for 64 bit libraries.
12565        if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null &&
12566                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
12567            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
12568            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
12569                    nativeLibPath, userId) < 0) {
12570                Slog.w(TAG, "Failed linking native library dir");
12571                return false;
12572            }
12573        }
12574
12575        return true;
12576    }
12577
12578    /**
12579     * Remove entries from the keystore daemon. Will only remove it if the
12580     * {@code appId} is valid.
12581     */
12582    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
12583        if (appId < 0) {
12584            return;
12585        }
12586
12587        final KeyStore keyStore = KeyStore.getInstance();
12588        if (keyStore != null) {
12589            if (userId == UserHandle.USER_ALL) {
12590                for (final int individual : sUserManager.getUserIds()) {
12591                    keyStore.clearUid(UserHandle.getUid(individual, appId));
12592                }
12593            } else {
12594                keyStore.clearUid(UserHandle.getUid(userId, appId));
12595            }
12596        } else {
12597            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
12598        }
12599    }
12600
12601    @Override
12602    public void deleteApplicationCacheFiles(final String packageName,
12603            final IPackageDataObserver observer) {
12604        mContext.enforceCallingOrSelfPermission(
12605                android.Manifest.permission.DELETE_CACHE_FILES, null);
12606        // Queue up an async operation since the package deletion may take a little while.
12607        final int userId = UserHandle.getCallingUserId();
12608        mHandler.post(new Runnable() {
12609            public void run() {
12610                mHandler.removeCallbacks(this);
12611                final boolean succeded;
12612                synchronized (mInstallLock) {
12613                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
12614                }
12615                clearExternalStorageDataSync(packageName, userId, false);
12616                if (observer != null) {
12617                    try {
12618                        observer.onRemoveCompleted(packageName, succeded);
12619                    } catch (RemoteException e) {
12620                        Log.i(TAG, "Observer no longer exists.");
12621                    }
12622                } //end if observer
12623            } //end run
12624        });
12625    }
12626
12627    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
12628        if (packageName == null) {
12629            Slog.w(TAG, "Attempt to delete null packageName.");
12630            return false;
12631        }
12632        PackageParser.Package p;
12633        synchronized (mPackages) {
12634            p = mPackages.get(packageName);
12635        }
12636        if (p == null) {
12637            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
12638            return false;
12639        }
12640        final ApplicationInfo applicationInfo = p.applicationInfo;
12641        if (applicationInfo == null) {
12642            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
12643            return false;
12644        }
12645        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
12646        if (retCode < 0) {
12647            Slog.w(TAG, "Couldn't remove cache files for package: "
12648                       + packageName + " u" + userId);
12649            return false;
12650        }
12651        return true;
12652    }
12653
12654    @Override
12655    public void getPackageSizeInfo(final String packageName, int userHandle,
12656            final IPackageStatsObserver observer) {
12657        mContext.enforceCallingOrSelfPermission(
12658                android.Manifest.permission.GET_PACKAGE_SIZE, null);
12659        if (packageName == null) {
12660            throw new IllegalArgumentException("Attempt to get size of null packageName");
12661        }
12662
12663        PackageStats stats = new PackageStats(packageName, userHandle);
12664
12665        /*
12666         * Queue up an async operation since the package measurement may take a
12667         * little while.
12668         */
12669        Message msg = mHandler.obtainMessage(INIT_COPY);
12670        msg.obj = new MeasureParams(stats, observer);
12671        mHandler.sendMessage(msg);
12672    }
12673
12674    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
12675            PackageStats pStats) {
12676        if (packageName == null) {
12677            Slog.w(TAG, "Attempt to get size of null packageName.");
12678            return false;
12679        }
12680        PackageParser.Package p;
12681        boolean dataOnly = false;
12682        String libDirRoot = null;
12683        String asecPath = null;
12684        PackageSetting ps = null;
12685        synchronized (mPackages) {
12686            p = mPackages.get(packageName);
12687            ps = mSettings.mPackages.get(packageName);
12688            if(p == null) {
12689                dataOnly = true;
12690                if((ps == null) || (ps.pkg == null)) {
12691                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
12692                    return false;
12693                }
12694                p = ps.pkg;
12695            }
12696            if (ps != null) {
12697                libDirRoot = ps.legacyNativeLibraryPathString;
12698            }
12699            if (p != null && (isExternal(p) || p.isForwardLocked())) {
12700                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
12701                if (secureContainerId != null) {
12702                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
12703                }
12704            }
12705        }
12706        String publicSrcDir = null;
12707        if(!dataOnly) {
12708            final ApplicationInfo applicationInfo = p.applicationInfo;
12709            if (applicationInfo == null) {
12710                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
12711                return false;
12712            }
12713            if (p.isForwardLocked()) {
12714                publicSrcDir = applicationInfo.getBaseResourcePath();
12715            }
12716        }
12717        // TODO: extend to measure size of split APKs
12718        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
12719        // not just the first level.
12720        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
12721        // just the primary.
12722        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
12723        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath,
12724                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
12725        if (res < 0) {
12726            return false;
12727        }
12728
12729        // Fix-up for forward-locked applications in ASEC containers.
12730        if (!isExternal(p)) {
12731            pStats.codeSize += pStats.externalCodeSize;
12732            pStats.externalCodeSize = 0L;
12733        }
12734
12735        return true;
12736    }
12737
12738
12739    @Override
12740    public void addPackageToPreferred(String packageName) {
12741        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
12742    }
12743
12744    @Override
12745    public void removePackageFromPreferred(String packageName) {
12746        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
12747    }
12748
12749    @Override
12750    public List<PackageInfo> getPreferredPackages(int flags) {
12751        return new ArrayList<PackageInfo>();
12752    }
12753
12754    private int getUidTargetSdkVersionLockedLPr(int uid) {
12755        Object obj = mSettings.getUserIdLPr(uid);
12756        if (obj instanceof SharedUserSetting) {
12757            final SharedUserSetting sus = (SharedUserSetting) obj;
12758            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
12759            final Iterator<PackageSetting> it = sus.packages.iterator();
12760            while (it.hasNext()) {
12761                final PackageSetting ps = it.next();
12762                if (ps.pkg != null) {
12763                    int v = ps.pkg.applicationInfo.targetSdkVersion;
12764                    if (v < vers) vers = v;
12765                }
12766            }
12767            return vers;
12768        } else if (obj instanceof PackageSetting) {
12769            final PackageSetting ps = (PackageSetting) obj;
12770            if (ps.pkg != null) {
12771                return ps.pkg.applicationInfo.targetSdkVersion;
12772            }
12773        }
12774        return Build.VERSION_CODES.CUR_DEVELOPMENT;
12775    }
12776
12777    @Override
12778    public void addPreferredActivity(IntentFilter filter, int match,
12779            ComponentName[] set, ComponentName activity, int userId) {
12780        addPreferredActivityInternal(filter, match, set, activity, true, userId,
12781                "Adding preferred");
12782    }
12783
12784    private void addPreferredActivityInternal(IntentFilter filter, int match,
12785            ComponentName[] set, ComponentName activity, boolean always, int userId,
12786            String opname) {
12787        // writer
12788        int callingUid = Binder.getCallingUid();
12789        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
12790        if (filter.countActions() == 0) {
12791            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
12792            return;
12793        }
12794        synchronized (mPackages) {
12795            if (mContext.checkCallingOrSelfPermission(
12796                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
12797                    != PackageManager.PERMISSION_GRANTED) {
12798                if (getUidTargetSdkVersionLockedLPr(callingUid)
12799                        < Build.VERSION_CODES.FROYO) {
12800                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
12801                            + callingUid);
12802                    return;
12803                }
12804                mContext.enforceCallingOrSelfPermission(
12805                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12806            }
12807
12808            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
12809            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
12810                    + userId + ":");
12811            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12812            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
12813            scheduleWritePackageRestrictionsLocked(userId);
12814        }
12815    }
12816
12817    @Override
12818    public void replacePreferredActivity(IntentFilter filter, int match,
12819            ComponentName[] set, ComponentName activity, int userId) {
12820        if (filter.countActions() != 1) {
12821            throw new IllegalArgumentException(
12822                    "replacePreferredActivity expects filter to have only 1 action.");
12823        }
12824        if (filter.countDataAuthorities() != 0
12825                || filter.countDataPaths() != 0
12826                || filter.countDataSchemes() > 1
12827                || filter.countDataTypes() != 0) {
12828            throw new IllegalArgumentException(
12829                    "replacePreferredActivity expects filter to have no data authorities, " +
12830                    "paths, or types; and at most one scheme.");
12831        }
12832
12833        final int callingUid = Binder.getCallingUid();
12834        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
12835        synchronized (mPackages) {
12836            if (mContext.checkCallingOrSelfPermission(
12837                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
12838                    != PackageManager.PERMISSION_GRANTED) {
12839                if (getUidTargetSdkVersionLockedLPr(callingUid)
12840                        < Build.VERSION_CODES.FROYO) {
12841                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
12842                            + Binder.getCallingUid());
12843                    return;
12844                }
12845                mContext.enforceCallingOrSelfPermission(
12846                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12847            }
12848
12849            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
12850            if (pir != null) {
12851                // Get all of the existing entries that exactly match this filter.
12852                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
12853                if (existing != null && existing.size() == 1) {
12854                    PreferredActivity cur = existing.get(0);
12855                    if (DEBUG_PREFERRED) {
12856                        Slog.i(TAG, "Checking replace of preferred:");
12857                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12858                        if (!cur.mPref.mAlways) {
12859                            Slog.i(TAG, "  -- CUR; not mAlways!");
12860                        } else {
12861                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
12862                            Slog.i(TAG, "  -- CUR: mSet="
12863                                    + Arrays.toString(cur.mPref.mSetComponents));
12864                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
12865                            Slog.i(TAG, "  -- NEW: mMatch="
12866                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
12867                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
12868                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
12869                        }
12870                    }
12871                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
12872                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
12873                            && cur.mPref.sameSet(set)) {
12874                        // Setting the preferred activity to what it happens to be already
12875                        if (DEBUG_PREFERRED) {
12876                            Slog.i(TAG, "Replacing with same preferred activity "
12877                                    + cur.mPref.mShortComponent + " for user "
12878                                    + userId + ":");
12879                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12880                        }
12881                        return;
12882                    }
12883                }
12884
12885                if (existing != null) {
12886                    if (DEBUG_PREFERRED) {
12887                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
12888                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12889                    }
12890                    for (int i = 0; i < existing.size(); i++) {
12891                        PreferredActivity pa = existing.get(i);
12892                        if (DEBUG_PREFERRED) {
12893                            Slog.i(TAG, "Removing existing preferred activity "
12894                                    + pa.mPref.mComponent + ":");
12895                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
12896                        }
12897                        pir.removeFilter(pa);
12898                    }
12899                }
12900            }
12901            addPreferredActivityInternal(filter, match, set, activity, true, userId,
12902                    "Replacing preferred");
12903        }
12904    }
12905
12906    @Override
12907    public void clearPackagePreferredActivities(String packageName) {
12908        final int uid = Binder.getCallingUid();
12909        // writer
12910        synchronized (mPackages) {
12911            PackageParser.Package pkg = mPackages.get(packageName);
12912            if (pkg == null || pkg.applicationInfo.uid != uid) {
12913                if (mContext.checkCallingOrSelfPermission(
12914                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
12915                        != PackageManager.PERMISSION_GRANTED) {
12916                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
12917                            < Build.VERSION_CODES.FROYO) {
12918                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
12919                                + Binder.getCallingUid());
12920                        return;
12921                    }
12922                    mContext.enforceCallingOrSelfPermission(
12923                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12924                }
12925            }
12926
12927            int user = UserHandle.getCallingUserId();
12928            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
12929                scheduleWritePackageRestrictionsLocked(user);
12930            }
12931        }
12932    }
12933
12934    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
12935    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
12936        ArrayList<PreferredActivity> removed = null;
12937        boolean changed = false;
12938        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12939            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
12940            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12941            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
12942                continue;
12943            }
12944            Iterator<PreferredActivity> it = pir.filterIterator();
12945            while (it.hasNext()) {
12946                PreferredActivity pa = it.next();
12947                // Mark entry for removal only if it matches the package name
12948                // and the entry is of type "always".
12949                if (packageName == null ||
12950                        (pa.mPref.mComponent.getPackageName().equals(packageName)
12951                                && pa.mPref.mAlways)) {
12952                    if (removed == null) {
12953                        removed = new ArrayList<PreferredActivity>();
12954                    }
12955                    removed.add(pa);
12956                }
12957            }
12958            if (removed != null) {
12959                for (int j=0; j<removed.size(); j++) {
12960                    PreferredActivity pa = removed.get(j);
12961                    pir.removeFilter(pa);
12962                }
12963                changed = true;
12964            }
12965        }
12966        return changed;
12967    }
12968
12969    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
12970    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
12971        if (userId == UserHandle.USER_ALL) {
12972            if (mSettings.removeIntentFilterVerificationLPw(packageName,
12973                    sUserManager.getUserIds())) {
12974                for (int oneUserId : sUserManager.getUserIds()) {
12975                    scheduleWritePackageRestrictionsLocked(oneUserId);
12976                }
12977            }
12978        } else {
12979            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
12980                scheduleWritePackageRestrictionsLocked(userId);
12981            }
12982        }
12983    }
12984
12985
12986    void clearDefaultBrowserIfNeeded(String packageName) {
12987        for (int oneUserId : sUserManager.getUserIds()) {
12988            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
12989            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
12990            if (packageName.equals(defaultBrowserPackageName)) {
12991                setDefaultBrowserPackageName(null, oneUserId);
12992            }
12993        }
12994    }
12995
12996    @Override
12997    public void resetPreferredActivities(int userId) {
12998        /* TODO: Actually use userId. Why is it being passed in? */
12999        mContext.enforceCallingOrSelfPermission(
13000                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13001        // writer
13002        synchronized (mPackages) {
13003            int user = UserHandle.getCallingUserId();
13004            clearPackagePreferredActivitiesLPw(null, user);
13005            mSettings.readDefaultPreferredAppsLPw(this, user);
13006            scheduleWritePackageRestrictionsLocked(user);
13007        }
13008    }
13009
13010    @Override
13011    public int getPreferredActivities(List<IntentFilter> outFilters,
13012            List<ComponentName> outActivities, String packageName) {
13013
13014        int num = 0;
13015        final int userId = UserHandle.getCallingUserId();
13016        // reader
13017        synchronized (mPackages) {
13018            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13019            if (pir != null) {
13020                final Iterator<PreferredActivity> it = pir.filterIterator();
13021                while (it.hasNext()) {
13022                    final PreferredActivity pa = it.next();
13023                    if (packageName == null
13024                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
13025                                    && pa.mPref.mAlways)) {
13026                        if (outFilters != null) {
13027                            outFilters.add(new IntentFilter(pa));
13028                        }
13029                        if (outActivities != null) {
13030                            outActivities.add(pa.mPref.mComponent);
13031                        }
13032                    }
13033                }
13034            }
13035        }
13036
13037        return num;
13038    }
13039
13040    @Override
13041    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
13042            int userId) {
13043        int callingUid = Binder.getCallingUid();
13044        if (callingUid != Process.SYSTEM_UID) {
13045            throw new SecurityException(
13046                    "addPersistentPreferredActivity can only be run by the system");
13047        }
13048        if (filter.countActions() == 0) {
13049            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13050            return;
13051        }
13052        synchronized (mPackages) {
13053            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
13054                    " :");
13055            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13056            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
13057                    new PersistentPreferredActivity(filter, activity));
13058            scheduleWritePackageRestrictionsLocked(userId);
13059        }
13060    }
13061
13062    @Override
13063    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
13064        int callingUid = Binder.getCallingUid();
13065        if (callingUid != Process.SYSTEM_UID) {
13066            throw new SecurityException(
13067                    "clearPackagePersistentPreferredActivities can only be run by the system");
13068        }
13069        ArrayList<PersistentPreferredActivity> removed = null;
13070        boolean changed = false;
13071        synchronized (mPackages) {
13072            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
13073                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
13074                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
13075                        .valueAt(i);
13076                if (userId != thisUserId) {
13077                    continue;
13078                }
13079                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
13080                while (it.hasNext()) {
13081                    PersistentPreferredActivity ppa = it.next();
13082                    // Mark entry for removal only if it matches the package name.
13083                    if (ppa.mComponent.getPackageName().equals(packageName)) {
13084                        if (removed == null) {
13085                            removed = new ArrayList<PersistentPreferredActivity>();
13086                        }
13087                        removed.add(ppa);
13088                    }
13089                }
13090                if (removed != null) {
13091                    for (int j=0; j<removed.size(); j++) {
13092                        PersistentPreferredActivity ppa = removed.get(j);
13093                        ppir.removeFilter(ppa);
13094                    }
13095                    changed = true;
13096                }
13097            }
13098
13099            if (changed) {
13100                scheduleWritePackageRestrictionsLocked(userId);
13101            }
13102        }
13103    }
13104
13105    /**
13106     * Non-Binder method, support for the backup/restore mechanism: write the
13107     * full set of preferred activities in its canonical XML format.  Returns true
13108     * on success; false otherwise.
13109     */
13110    @Override
13111    public byte[] getPreferredActivityBackup(int userId) {
13112        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13113            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
13114        }
13115
13116        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13117        try {
13118            final XmlSerializer serializer = new FastXmlSerializer();
13119            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13120            serializer.startDocument(null, true);
13121            serializer.startTag(null, TAG_PREFERRED_BACKUP);
13122
13123            synchronized (mPackages) {
13124                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
13125            }
13126
13127            serializer.endTag(null, TAG_PREFERRED_BACKUP);
13128            serializer.endDocument();
13129            serializer.flush();
13130        } catch (Exception e) {
13131            if (DEBUG_BACKUP) {
13132                Slog.e(TAG, "Unable to write preferred activities for backup", e);
13133            }
13134            return null;
13135        }
13136
13137        return dataStream.toByteArray();
13138    }
13139
13140    @Override
13141    public void restorePreferredActivities(byte[] backup, int userId) {
13142        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13143            throw new SecurityException("Only the system may call restorePreferredActivities()");
13144        }
13145
13146        try {
13147            final XmlPullParser parser = Xml.newPullParser();
13148            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13149
13150            int type;
13151            while ((type = parser.next()) != XmlPullParser.START_TAG
13152                    && type != XmlPullParser.END_DOCUMENT) {
13153            }
13154            if (type != XmlPullParser.START_TAG) {
13155                // oops didn't find a start tag?!
13156                if (DEBUG_BACKUP) {
13157                    Slog.e(TAG, "Didn't find start tag during restore");
13158                }
13159                return;
13160            }
13161
13162            // this is supposed to be TAG_PREFERRED_BACKUP
13163            if (!TAG_PREFERRED_BACKUP.equals(parser.getName())) {
13164                if (DEBUG_BACKUP) {
13165                    Slog.e(TAG, "Found unexpected tag " + parser.getName());
13166                }
13167                return;
13168            }
13169
13170            // skip interfering stuff, then we're aligned with the backing implementation
13171            while ((type = parser.next()) == XmlPullParser.TEXT) { }
13172            synchronized (mPackages) {
13173                mSettings.readPreferredActivitiesLPw(parser, userId);
13174            }
13175        } catch (Exception e) {
13176            if (DEBUG_BACKUP) {
13177                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
13178            }
13179        }
13180    }
13181
13182    @Override
13183    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
13184            int sourceUserId, int targetUserId, int flags) {
13185        mContext.enforceCallingOrSelfPermission(
13186                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
13187        int callingUid = Binder.getCallingUid();
13188        enforceOwnerRights(ownerPackage, callingUid);
13189        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
13190        if (intentFilter.countActions() == 0) {
13191            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
13192            return;
13193        }
13194        synchronized (mPackages) {
13195            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
13196                    ownerPackage, targetUserId, flags);
13197            CrossProfileIntentResolver resolver =
13198                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
13199            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
13200            // We have all those whose filter is equal. Now checking if the rest is equal as well.
13201            if (existing != null) {
13202                int size = existing.size();
13203                for (int i = 0; i < size; i++) {
13204                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
13205                        return;
13206                    }
13207                }
13208            }
13209            resolver.addFilter(newFilter);
13210            scheduleWritePackageRestrictionsLocked(sourceUserId);
13211        }
13212    }
13213
13214    @Override
13215    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
13216        mContext.enforceCallingOrSelfPermission(
13217                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
13218        int callingUid = Binder.getCallingUid();
13219        enforceOwnerRights(ownerPackage, callingUid);
13220        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
13221        synchronized (mPackages) {
13222            CrossProfileIntentResolver resolver =
13223                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
13224            ArraySet<CrossProfileIntentFilter> set =
13225                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
13226            for (CrossProfileIntentFilter filter : set) {
13227                if (filter.getOwnerPackage().equals(ownerPackage)) {
13228                    resolver.removeFilter(filter);
13229                }
13230            }
13231            scheduleWritePackageRestrictionsLocked(sourceUserId);
13232        }
13233    }
13234
13235    // Enforcing that callingUid is owning pkg on userId
13236    private void enforceOwnerRights(String pkg, int callingUid) {
13237        // The system owns everything.
13238        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
13239            return;
13240        }
13241        int callingUserId = UserHandle.getUserId(callingUid);
13242        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
13243        if (pi == null) {
13244            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
13245                    + callingUserId);
13246        }
13247        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
13248            throw new SecurityException("Calling uid " + callingUid
13249                    + " does not own package " + pkg);
13250        }
13251    }
13252
13253    @Override
13254    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
13255        Intent intent = new Intent(Intent.ACTION_MAIN);
13256        intent.addCategory(Intent.CATEGORY_HOME);
13257
13258        final int callingUserId = UserHandle.getCallingUserId();
13259        List<ResolveInfo> list = queryIntentActivities(intent, null,
13260                PackageManager.GET_META_DATA, callingUserId);
13261        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
13262                true, false, false, callingUserId);
13263
13264        allHomeCandidates.clear();
13265        if (list != null) {
13266            for (ResolveInfo ri : list) {
13267                allHomeCandidates.add(ri);
13268            }
13269        }
13270        return (preferred == null || preferred.activityInfo == null)
13271                ? null
13272                : new ComponentName(preferred.activityInfo.packageName,
13273                        preferred.activityInfo.name);
13274    }
13275
13276    @Override
13277    public void setApplicationEnabledSetting(String appPackageName,
13278            int newState, int flags, int userId, String callingPackage) {
13279        if (!sUserManager.exists(userId)) return;
13280        if (callingPackage == null) {
13281            callingPackage = Integer.toString(Binder.getCallingUid());
13282        }
13283        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
13284    }
13285
13286    @Override
13287    public void setComponentEnabledSetting(ComponentName componentName,
13288            int newState, int flags, int userId) {
13289        if (!sUserManager.exists(userId)) return;
13290        setEnabledSetting(componentName.getPackageName(),
13291                componentName.getClassName(), newState, flags, userId, null);
13292    }
13293
13294    private void setEnabledSetting(final String packageName, String className, int newState,
13295            final int flags, int userId, String callingPackage) {
13296        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
13297              || newState == COMPONENT_ENABLED_STATE_ENABLED
13298              || newState == COMPONENT_ENABLED_STATE_DISABLED
13299              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
13300              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
13301            throw new IllegalArgumentException("Invalid new component state: "
13302                    + newState);
13303        }
13304        PackageSetting pkgSetting;
13305        final int uid = Binder.getCallingUid();
13306        final int permission = mContext.checkCallingOrSelfPermission(
13307                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
13308        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
13309        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
13310        boolean sendNow = false;
13311        boolean isApp = (className == null);
13312        String componentName = isApp ? packageName : className;
13313        int packageUid = -1;
13314        ArrayList<String> components;
13315
13316        // writer
13317        synchronized (mPackages) {
13318            pkgSetting = mSettings.mPackages.get(packageName);
13319            if (pkgSetting == null) {
13320                if (className == null) {
13321                    throw new IllegalArgumentException(
13322                            "Unknown package: " + packageName);
13323                }
13324                throw new IllegalArgumentException(
13325                        "Unknown component: " + packageName
13326                        + "/" + className);
13327            }
13328            // Allow root and verify that userId is not being specified by a different user
13329            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
13330                throw new SecurityException(
13331                        "Permission Denial: attempt to change component state from pid="
13332                        + Binder.getCallingPid()
13333                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
13334            }
13335            if (className == null) {
13336                // We're dealing with an application/package level state change
13337                if (pkgSetting.getEnabled(userId) == newState) {
13338                    // Nothing to do
13339                    return;
13340                }
13341                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
13342                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
13343                    // Don't care about who enables an app.
13344                    callingPackage = null;
13345                }
13346                pkgSetting.setEnabled(newState, userId, callingPackage);
13347                // pkgSetting.pkg.mSetEnabled = newState;
13348            } else {
13349                // We're dealing with a component level state change
13350                // First, verify that this is a valid class name.
13351                PackageParser.Package pkg = pkgSetting.pkg;
13352                if (pkg == null || !pkg.hasComponentClassName(className)) {
13353                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
13354                        throw new IllegalArgumentException("Component class " + className
13355                                + " does not exist in " + packageName);
13356                    } else {
13357                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
13358                                + className + " does not exist in " + packageName);
13359                    }
13360                }
13361                switch (newState) {
13362                case COMPONENT_ENABLED_STATE_ENABLED:
13363                    if (!pkgSetting.enableComponentLPw(className, userId)) {
13364                        return;
13365                    }
13366                    break;
13367                case COMPONENT_ENABLED_STATE_DISABLED:
13368                    if (!pkgSetting.disableComponentLPw(className, userId)) {
13369                        return;
13370                    }
13371                    break;
13372                case COMPONENT_ENABLED_STATE_DEFAULT:
13373                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
13374                        return;
13375                    }
13376                    break;
13377                default:
13378                    Slog.e(TAG, "Invalid new component state: " + newState);
13379                    return;
13380                }
13381            }
13382            scheduleWritePackageRestrictionsLocked(userId);
13383            components = mPendingBroadcasts.get(userId, packageName);
13384            final boolean newPackage = components == null;
13385            if (newPackage) {
13386                components = new ArrayList<String>();
13387            }
13388            if (!components.contains(componentName)) {
13389                components.add(componentName);
13390            }
13391            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
13392                sendNow = true;
13393                // Purge entry from pending broadcast list if another one exists already
13394                // since we are sending one right away.
13395                mPendingBroadcasts.remove(userId, packageName);
13396            } else {
13397                if (newPackage) {
13398                    mPendingBroadcasts.put(userId, packageName, components);
13399                }
13400                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
13401                    // Schedule a message
13402                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
13403                }
13404            }
13405        }
13406
13407        long callingId = Binder.clearCallingIdentity();
13408        try {
13409            if (sendNow) {
13410                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
13411                sendPackageChangedBroadcast(packageName,
13412                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
13413            }
13414        } finally {
13415            Binder.restoreCallingIdentity(callingId);
13416        }
13417    }
13418
13419    private void sendPackageChangedBroadcast(String packageName,
13420            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
13421        if (DEBUG_INSTALL)
13422            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
13423                    + componentNames);
13424        Bundle extras = new Bundle(4);
13425        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
13426        String nameList[] = new String[componentNames.size()];
13427        componentNames.toArray(nameList);
13428        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
13429        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
13430        extras.putInt(Intent.EXTRA_UID, packageUid);
13431        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
13432                new int[] {UserHandle.getUserId(packageUid)});
13433    }
13434
13435    @Override
13436    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
13437        if (!sUserManager.exists(userId)) return;
13438        final int uid = Binder.getCallingUid();
13439        final int permission = mContext.checkCallingOrSelfPermission(
13440                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
13441        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
13442        enforceCrossUserPermission(uid, userId, true, true, "stop package");
13443        // writer
13444        synchronized (mPackages) {
13445            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
13446                    allowedByPermission, uid, userId)) {
13447                scheduleWritePackageRestrictionsLocked(userId);
13448            }
13449        }
13450    }
13451
13452    @Override
13453    public String getInstallerPackageName(String packageName) {
13454        // reader
13455        synchronized (mPackages) {
13456            return mSettings.getInstallerPackageNameLPr(packageName);
13457        }
13458    }
13459
13460    @Override
13461    public int getApplicationEnabledSetting(String packageName, int userId) {
13462        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
13463        int uid = Binder.getCallingUid();
13464        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
13465        // reader
13466        synchronized (mPackages) {
13467            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
13468        }
13469    }
13470
13471    @Override
13472    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
13473        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
13474        int uid = Binder.getCallingUid();
13475        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
13476        // reader
13477        synchronized (mPackages) {
13478            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
13479        }
13480    }
13481
13482    @Override
13483    public void enterSafeMode() {
13484        enforceSystemOrRoot("Only the system can request entering safe mode");
13485
13486        if (!mSystemReady) {
13487            mSafeMode = true;
13488        }
13489    }
13490
13491    @Override
13492    public void systemReady() {
13493        mSystemReady = true;
13494
13495        // Read the compatibilty setting when the system is ready.
13496        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
13497                mContext.getContentResolver(),
13498                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
13499        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
13500        if (DEBUG_SETTINGS) {
13501            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
13502        }
13503
13504        synchronized (mPackages) {
13505            // Verify that all of the preferred activity components actually
13506            // exist.  It is possible for applications to be updated and at
13507            // that point remove a previously declared activity component that
13508            // had been set as a preferred activity.  We try to clean this up
13509            // the next time we encounter that preferred activity, but it is
13510            // possible for the user flow to never be able to return to that
13511            // situation so here we do a sanity check to make sure we haven't
13512            // left any junk around.
13513            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
13514            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13515                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13516                removed.clear();
13517                for (PreferredActivity pa : pir.filterSet()) {
13518                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
13519                        removed.add(pa);
13520                    }
13521                }
13522                if (removed.size() > 0) {
13523                    for (int r=0; r<removed.size(); r++) {
13524                        PreferredActivity pa = removed.get(r);
13525                        Slog.w(TAG, "Removing dangling preferred activity: "
13526                                + pa.mPref.mComponent);
13527                        pir.removeFilter(pa);
13528                    }
13529                    mSettings.writePackageRestrictionsLPr(
13530                            mSettings.mPreferredActivities.keyAt(i));
13531                }
13532            }
13533        }
13534        sUserManager.systemReady();
13535
13536        // Kick off any messages waiting for system ready
13537        if (mPostSystemReadyMessages != null) {
13538            for (Message msg : mPostSystemReadyMessages) {
13539                msg.sendToTarget();
13540            }
13541            mPostSystemReadyMessages = null;
13542        }
13543
13544        // Watch for external volumes that come and go over time
13545        final StorageManager storage = mContext.getSystemService(StorageManager.class);
13546        storage.registerListener(mStorageListener);
13547
13548        mInstallerService.systemReady();
13549        mPackageDexOptimizer.systemReady();
13550    }
13551
13552    @Override
13553    public boolean isSafeMode() {
13554        return mSafeMode;
13555    }
13556
13557    @Override
13558    public boolean hasSystemUidErrors() {
13559        return mHasSystemUidErrors;
13560    }
13561
13562    static String arrayToString(int[] array) {
13563        StringBuffer buf = new StringBuffer(128);
13564        buf.append('[');
13565        if (array != null) {
13566            for (int i=0; i<array.length; i++) {
13567                if (i > 0) buf.append(", ");
13568                buf.append(array[i]);
13569            }
13570        }
13571        buf.append(']');
13572        return buf.toString();
13573    }
13574
13575    static class DumpState {
13576        public static final int DUMP_LIBS = 1 << 0;
13577        public static final int DUMP_FEATURES = 1 << 1;
13578        public static final int DUMP_RESOLVERS = 1 << 2;
13579        public static final int DUMP_PERMISSIONS = 1 << 3;
13580        public static final int DUMP_PACKAGES = 1 << 4;
13581        public static final int DUMP_SHARED_USERS = 1 << 5;
13582        public static final int DUMP_MESSAGES = 1 << 6;
13583        public static final int DUMP_PROVIDERS = 1 << 7;
13584        public static final int DUMP_VERIFIERS = 1 << 8;
13585        public static final int DUMP_PREFERRED = 1 << 9;
13586        public static final int DUMP_PREFERRED_XML = 1 << 10;
13587        public static final int DUMP_KEYSETS = 1 << 11;
13588        public static final int DUMP_VERSION = 1 << 12;
13589        public static final int DUMP_INSTALLS = 1 << 13;
13590        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
13591        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
13592
13593        public static final int OPTION_SHOW_FILTERS = 1 << 0;
13594
13595        private int mTypes;
13596
13597        private int mOptions;
13598
13599        private boolean mTitlePrinted;
13600
13601        private SharedUserSetting mSharedUser;
13602
13603        public boolean isDumping(int type) {
13604            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
13605                return true;
13606            }
13607
13608            return (mTypes & type) != 0;
13609        }
13610
13611        public void setDump(int type) {
13612            mTypes |= type;
13613        }
13614
13615        public boolean isOptionEnabled(int option) {
13616            return (mOptions & option) != 0;
13617        }
13618
13619        public void setOptionEnabled(int option) {
13620            mOptions |= option;
13621        }
13622
13623        public boolean onTitlePrinted() {
13624            final boolean printed = mTitlePrinted;
13625            mTitlePrinted = true;
13626            return printed;
13627        }
13628
13629        public boolean getTitlePrinted() {
13630            return mTitlePrinted;
13631        }
13632
13633        public void setTitlePrinted(boolean enabled) {
13634            mTitlePrinted = enabled;
13635        }
13636
13637        public SharedUserSetting getSharedUser() {
13638            return mSharedUser;
13639        }
13640
13641        public void setSharedUser(SharedUserSetting user) {
13642            mSharedUser = user;
13643        }
13644    }
13645
13646    @Override
13647    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
13648        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
13649                != PackageManager.PERMISSION_GRANTED) {
13650            pw.println("Permission Denial: can't dump ActivityManager from from pid="
13651                    + Binder.getCallingPid()
13652                    + ", uid=" + Binder.getCallingUid()
13653                    + " without permission "
13654                    + android.Manifest.permission.DUMP);
13655            return;
13656        }
13657
13658        DumpState dumpState = new DumpState();
13659        boolean fullPreferred = false;
13660        boolean checkin = false;
13661
13662        String packageName = null;
13663
13664        int opti = 0;
13665        while (opti < args.length) {
13666            String opt = args[opti];
13667            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
13668                break;
13669            }
13670            opti++;
13671
13672            if ("-a".equals(opt)) {
13673                // Right now we only know how to print all.
13674            } else if ("-h".equals(opt)) {
13675                pw.println("Package manager dump options:");
13676                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
13677                pw.println("    --checkin: dump for a checkin");
13678                pw.println("    -f: print details of intent filters");
13679                pw.println("    -h: print this help");
13680                pw.println("  cmd may be one of:");
13681                pw.println("    l[ibraries]: list known shared libraries");
13682                pw.println("    f[ibraries]: list device features");
13683                pw.println("    k[eysets]: print known keysets");
13684                pw.println("    r[esolvers]: dump intent resolvers");
13685                pw.println("    perm[issions]: dump permissions");
13686                pw.println("    pref[erred]: print preferred package settings");
13687                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
13688                pw.println("    prov[iders]: dump content providers");
13689                pw.println("    p[ackages]: dump installed packages");
13690                pw.println("    s[hared-users]: dump shared user IDs");
13691                pw.println("    m[essages]: print collected runtime messages");
13692                pw.println("    v[erifiers]: print package verifier info");
13693                pw.println("    version: print database version info");
13694                pw.println("    write: write current settings now");
13695                pw.println("    <package.name>: info about given package");
13696                pw.println("    installs: details about install sessions");
13697                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
13698                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
13699                return;
13700            } else if ("--checkin".equals(opt)) {
13701                checkin = true;
13702            } else if ("-f".equals(opt)) {
13703                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
13704            } else {
13705                pw.println("Unknown argument: " + opt + "; use -h for help");
13706            }
13707        }
13708
13709        // Is the caller requesting to dump a particular piece of data?
13710        if (opti < args.length) {
13711            String cmd = args[opti];
13712            opti++;
13713            // Is this a package name?
13714            if ("android".equals(cmd) || cmd.contains(".")) {
13715                packageName = cmd;
13716                // When dumping a single package, we always dump all of its
13717                // filter information since the amount of data will be reasonable.
13718                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
13719            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
13720                dumpState.setDump(DumpState.DUMP_LIBS);
13721            } else if ("f".equals(cmd) || "features".equals(cmd)) {
13722                dumpState.setDump(DumpState.DUMP_FEATURES);
13723            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
13724                dumpState.setDump(DumpState.DUMP_RESOLVERS);
13725            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
13726                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
13727            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
13728                dumpState.setDump(DumpState.DUMP_PREFERRED);
13729            } else if ("preferred-xml".equals(cmd)) {
13730                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
13731                if (opti < args.length && "--full".equals(args[opti])) {
13732                    fullPreferred = true;
13733                    opti++;
13734                }
13735            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
13736                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
13737            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
13738                dumpState.setDump(DumpState.DUMP_PACKAGES);
13739            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
13740                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
13741            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
13742                dumpState.setDump(DumpState.DUMP_PROVIDERS);
13743            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
13744                dumpState.setDump(DumpState.DUMP_MESSAGES);
13745            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
13746                dumpState.setDump(DumpState.DUMP_VERIFIERS);
13747            } else if ("i".equals(cmd) || "ifv".equals(cmd)
13748                    || "intent-filter-verifiers".equals(cmd)) {
13749                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
13750            } else if ("version".equals(cmd)) {
13751                dumpState.setDump(DumpState.DUMP_VERSION);
13752            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
13753                dumpState.setDump(DumpState.DUMP_KEYSETS);
13754            } else if ("installs".equals(cmd)) {
13755                dumpState.setDump(DumpState.DUMP_INSTALLS);
13756            } else if ("write".equals(cmd)) {
13757                synchronized (mPackages) {
13758                    mSettings.writeLPr();
13759                    pw.println("Settings written.");
13760                    return;
13761                }
13762            }
13763        }
13764
13765        if (checkin) {
13766            pw.println("vers,1");
13767        }
13768
13769        // reader
13770        synchronized (mPackages) {
13771            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
13772                if (!checkin) {
13773                    if (dumpState.onTitlePrinted())
13774                        pw.println();
13775                    pw.println("Database versions:");
13776                    pw.print("  SDK Version:");
13777                    pw.print(" internal=");
13778                    pw.print(mSettings.mInternalSdkPlatform);
13779                    pw.print(" external=");
13780                    pw.println(mSettings.mExternalSdkPlatform);
13781                    pw.print("  DB Version:");
13782                    pw.print(" internal=");
13783                    pw.print(mSettings.mInternalDatabaseVersion);
13784                    pw.print(" external=");
13785                    pw.println(mSettings.mExternalDatabaseVersion);
13786                }
13787            }
13788
13789            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
13790                if (!checkin) {
13791                    if (dumpState.onTitlePrinted())
13792                        pw.println();
13793                    pw.println("Verifiers:");
13794                    pw.print("  Required: ");
13795                    pw.print(mRequiredVerifierPackage);
13796                    pw.print(" (uid=");
13797                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
13798                    pw.println(")");
13799                } else if (mRequiredVerifierPackage != null) {
13800                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
13801                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
13802                }
13803            }
13804
13805            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
13806                    packageName == null) {
13807                if (mIntentFilterVerifierComponent != null) {
13808                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
13809                    if (!checkin) {
13810                        if (dumpState.onTitlePrinted())
13811                            pw.println();
13812                        pw.println("Intent Filter Verifier:");
13813                        pw.print("  Using: ");
13814                        pw.print(verifierPackageName);
13815                        pw.print(" (uid=");
13816                        pw.print(getPackageUid(verifierPackageName, 0));
13817                        pw.println(")");
13818                    } else if (verifierPackageName != null) {
13819                        pw.print("ifv,"); pw.print(verifierPackageName);
13820                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
13821                    }
13822                } else {
13823                    pw.println();
13824                    pw.println("No Intent Filter Verifier available!");
13825                }
13826            }
13827
13828            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
13829                boolean printedHeader = false;
13830                final Iterator<String> it = mSharedLibraries.keySet().iterator();
13831                while (it.hasNext()) {
13832                    String name = it.next();
13833                    SharedLibraryEntry ent = mSharedLibraries.get(name);
13834                    if (!checkin) {
13835                        if (!printedHeader) {
13836                            if (dumpState.onTitlePrinted())
13837                                pw.println();
13838                            pw.println("Libraries:");
13839                            printedHeader = true;
13840                        }
13841                        pw.print("  ");
13842                    } else {
13843                        pw.print("lib,");
13844                    }
13845                    pw.print(name);
13846                    if (!checkin) {
13847                        pw.print(" -> ");
13848                    }
13849                    if (ent.path != null) {
13850                        if (!checkin) {
13851                            pw.print("(jar) ");
13852                            pw.print(ent.path);
13853                        } else {
13854                            pw.print(",jar,");
13855                            pw.print(ent.path);
13856                        }
13857                    } else {
13858                        if (!checkin) {
13859                            pw.print("(apk) ");
13860                            pw.print(ent.apk);
13861                        } else {
13862                            pw.print(",apk,");
13863                            pw.print(ent.apk);
13864                        }
13865                    }
13866                    pw.println();
13867                }
13868            }
13869
13870            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
13871                if (dumpState.onTitlePrinted())
13872                    pw.println();
13873                if (!checkin) {
13874                    pw.println("Features:");
13875                }
13876                Iterator<String> it = mAvailableFeatures.keySet().iterator();
13877                while (it.hasNext()) {
13878                    String name = it.next();
13879                    if (!checkin) {
13880                        pw.print("  ");
13881                    } else {
13882                        pw.print("feat,");
13883                    }
13884                    pw.println(name);
13885                }
13886            }
13887
13888            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
13889                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
13890                        : "Activity Resolver Table:", "  ", packageName,
13891                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
13892                    dumpState.setTitlePrinted(true);
13893                }
13894                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
13895                        : "Receiver Resolver Table:", "  ", packageName,
13896                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
13897                    dumpState.setTitlePrinted(true);
13898                }
13899                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
13900                        : "Service Resolver Table:", "  ", packageName,
13901                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
13902                    dumpState.setTitlePrinted(true);
13903                }
13904                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
13905                        : "Provider Resolver Table:", "  ", packageName,
13906                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
13907                    dumpState.setTitlePrinted(true);
13908                }
13909            }
13910
13911            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
13912                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13913                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13914                    int user = mSettings.mPreferredActivities.keyAt(i);
13915                    if (pir.dump(pw,
13916                            dumpState.getTitlePrinted()
13917                                ? "\nPreferred Activities User " + user + ":"
13918                                : "Preferred Activities User " + user + ":", "  ",
13919                            packageName, true, false)) {
13920                        dumpState.setTitlePrinted(true);
13921                    }
13922                }
13923            }
13924
13925            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
13926                pw.flush();
13927                FileOutputStream fout = new FileOutputStream(fd);
13928                BufferedOutputStream str = new BufferedOutputStream(fout);
13929                XmlSerializer serializer = new FastXmlSerializer();
13930                try {
13931                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
13932                    serializer.startDocument(null, true);
13933                    serializer.setFeature(
13934                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
13935                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
13936                    serializer.endDocument();
13937                    serializer.flush();
13938                } catch (IllegalArgumentException e) {
13939                    pw.println("Failed writing: " + e);
13940                } catch (IllegalStateException e) {
13941                    pw.println("Failed writing: " + e);
13942                } catch (IOException e) {
13943                    pw.println("Failed writing: " + e);
13944                }
13945            }
13946
13947            if (!checkin && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)) {
13948                pw.println();
13949                int count = mSettings.mPackages.size();
13950                if (count == 0) {
13951                    pw.println("No domain preferred apps!");
13952                    pw.println();
13953                } else {
13954                    final String prefix = "  ";
13955                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
13956                    if (allPackageSettings.size() == 0) {
13957                        pw.println("No domain preferred apps!");
13958                        pw.println();
13959                    } else {
13960                        pw.println("Domain preferred apps status:");
13961                        pw.println();
13962                        count = 0;
13963                        for (PackageSetting ps : allPackageSettings) {
13964                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
13965                            if (ivi == null || ivi.getPackageName() == null) continue;
13966                            pw.println(prefix + "Package Name: " + ivi.getPackageName());
13967                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
13968                            pw.println(prefix + "Status: " + ivi.getStatusString());
13969                            pw.println();
13970                            count++;
13971                        }
13972                        if (count == 0) {
13973                            pw.println(prefix + "No domain preferred app status!");
13974                            pw.println();
13975                        }
13976                        for (int userId : sUserManager.getUserIds()) {
13977                            pw.println("Domain preferred apps for User " + userId + ":");
13978                            pw.println();
13979                            count = 0;
13980                            for (PackageSetting ps : allPackageSettings) {
13981                                IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
13982                                if (ivi == null || ivi.getPackageName() == null) {
13983                                    continue;
13984                                }
13985                                final int status = ps.getDomainVerificationStatusForUser(userId);
13986                                if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
13987                                    continue;
13988                                }
13989                                pw.println(prefix + "Package Name: " + ivi.getPackageName());
13990                                pw.println(prefix + "Domains: " + ivi.getDomainsString());
13991                                String statusStr = IntentFilterVerificationInfo.
13992                                        getStatusStringFromValue(status);
13993                                pw.println(prefix + "Status: " + statusStr);
13994                                pw.println();
13995                                count++;
13996                            }
13997                            if (count == 0) {
13998                                pw.println(prefix + "No domain preferred apps!");
13999                                pw.println();
14000                            }
14001                        }
14002                    }
14003                }
14004            }
14005
14006            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
14007                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
14008                if (packageName == null) {
14009                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
14010                        if (iperm == 0) {
14011                            if (dumpState.onTitlePrinted())
14012                                pw.println();
14013                            pw.println("AppOp Permissions:");
14014                        }
14015                        pw.print("  AppOp Permission ");
14016                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
14017                        pw.println(":");
14018                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
14019                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
14020                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
14021                        }
14022                    }
14023                }
14024            }
14025
14026            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
14027                boolean printedSomething = false;
14028                for (PackageParser.Provider p : mProviders.mProviders.values()) {
14029                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14030                        continue;
14031                    }
14032                    if (!printedSomething) {
14033                        if (dumpState.onTitlePrinted())
14034                            pw.println();
14035                        pw.println("Registered ContentProviders:");
14036                        printedSomething = true;
14037                    }
14038                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
14039                    pw.print("    "); pw.println(p.toString());
14040                }
14041                printedSomething = false;
14042                for (Map.Entry<String, PackageParser.Provider> entry :
14043                        mProvidersByAuthority.entrySet()) {
14044                    PackageParser.Provider p = entry.getValue();
14045                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14046                        continue;
14047                    }
14048                    if (!printedSomething) {
14049                        if (dumpState.onTitlePrinted())
14050                            pw.println();
14051                        pw.println("ContentProvider Authorities:");
14052                        printedSomething = true;
14053                    }
14054                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
14055                    pw.print("    "); pw.println(p.toString());
14056                    if (p.info != null && p.info.applicationInfo != null) {
14057                        final String appInfo = p.info.applicationInfo.toString();
14058                        pw.print("      applicationInfo="); pw.println(appInfo);
14059                    }
14060                }
14061            }
14062
14063            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
14064                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
14065            }
14066
14067            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
14068                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
14069            }
14070
14071            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
14072                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin);
14073            }
14074
14075            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
14076                // XXX should handle packageName != null by dumping only install data that
14077                // the given package is involved with.
14078                if (dumpState.onTitlePrinted()) pw.println();
14079                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
14080            }
14081
14082            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
14083                if (dumpState.onTitlePrinted()) pw.println();
14084                mSettings.dumpReadMessagesLPr(pw, dumpState);
14085
14086                pw.println();
14087                pw.println("Package warning messages:");
14088                BufferedReader in = null;
14089                String line = null;
14090                try {
14091                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
14092                    while ((line = in.readLine()) != null) {
14093                        if (line.contains("ignored: updated version")) continue;
14094                        pw.println(line);
14095                    }
14096                } catch (IOException ignored) {
14097                } finally {
14098                    IoUtils.closeQuietly(in);
14099                }
14100            }
14101
14102            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
14103                BufferedReader in = null;
14104                String line = null;
14105                try {
14106                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
14107                    while ((line = in.readLine()) != null) {
14108                        if (line.contains("ignored: updated version")) continue;
14109                        pw.print("msg,");
14110                        pw.println(line);
14111                    }
14112                } catch (IOException ignored) {
14113                } finally {
14114                    IoUtils.closeQuietly(in);
14115                }
14116            }
14117        }
14118    }
14119
14120    // ------- apps on sdcard specific code -------
14121    static final boolean DEBUG_SD_INSTALL = false;
14122
14123    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
14124
14125    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
14126
14127    private boolean mMediaMounted = false;
14128
14129    static String getEncryptKey() {
14130        try {
14131            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
14132                    SD_ENCRYPTION_KEYSTORE_NAME);
14133            if (sdEncKey == null) {
14134                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
14135                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
14136                if (sdEncKey == null) {
14137                    Slog.e(TAG, "Failed to create encryption keys");
14138                    return null;
14139                }
14140            }
14141            return sdEncKey;
14142        } catch (NoSuchAlgorithmException nsae) {
14143            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
14144            return null;
14145        } catch (IOException ioe) {
14146            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
14147            return null;
14148        }
14149    }
14150
14151    /*
14152     * Update media status on PackageManager.
14153     */
14154    @Override
14155    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
14156        int callingUid = Binder.getCallingUid();
14157        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
14158            throw new SecurityException("Media status can only be updated by the system");
14159        }
14160        // reader; this apparently protects mMediaMounted, but should probably
14161        // be a different lock in that case.
14162        synchronized (mPackages) {
14163            Log.i(TAG, "Updating external media status from "
14164                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
14165                    + (mediaStatus ? "mounted" : "unmounted"));
14166            if (DEBUG_SD_INSTALL)
14167                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
14168                        + ", mMediaMounted=" + mMediaMounted);
14169            if (mediaStatus == mMediaMounted) {
14170                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
14171                        : 0, -1);
14172                mHandler.sendMessage(msg);
14173                return;
14174            }
14175            mMediaMounted = mediaStatus;
14176        }
14177        // Queue up an async operation since the package installation may take a
14178        // little while.
14179        mHandler.post(new Runnable() {
14180            public void run() {
14181                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
14182            }
14183        });
14184    }
14185
14186    /**
14187     * Called by MountService when the initial ASECs to scan are available.
14188     * Should block until all the ASEC containers are finished being scanned.
14189     */
14190    public void scanAvailableAsecs() {
14191        updateExternalMediaStatusInner(true, false, false);
14192        if (mShouldRestoreconData) {
14193            SELinuxMMAC.setRestoreconDone();
14194            mShouldRestoreconData = false;
14195        }
14196    }
14197
14198    /*
14199     * Collect information of applications on external media, map them against
14200     * existing containers and update information based on current mount status.
14201     * Please note that we always have to report status if reportStatus has been
14202     * set to true especially when unloading packages.
14203     */
14204    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
14205            boolean externalStorage) {
14206        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
14207        int[] uidArr = EmptyArray.INT;
14208
14209        final String[] list = PackageHelper.getSecureContainerList();
14210        if (ArrayUtils.isEmpty(list)) {
14211            Log.i(TAG, "No secure containers found");
14212        } else {
14213            // Process list of secure containers and categorize them
14214            // as active or stale based on their package internal state.
14215
14216            // reader
14217            synchronized (mPackages) {
14218                for (String cid : list) {
14219                    // Leave stages untouched for now; installer service owns them
14220                    if (PackageInstallerService.isStageName(cid)) continue;
14221
14222                    if (DEBUG_SD_INSTALL)
14223                        Log.i(TAG, "Processing container " + cid);
14224                    String pkgName = getAsecPackageName(cid);
14225                    if (pkgName == null) {
14226                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
14227                        continue;
14228                    }
14229                    if (DEBUG_SD_INSTALL)
14230                        Log.i(TAG, "Looking for pkg : " + pkgName);
14231
14232                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
14233                    if (ps == null) {
14234                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
14235                        continue;
14236                    }
14237
14238                    /*
14239                     * Skip packages that are not external if we're unmounting
14240                     * external storage.
14241                     */
14242                    if (externalStorage && !isMounted && !isExternal(ps)) {
14243                        continue;
14244                    }
14245
14246                    final AsecInstallArgs args = new AsecInstallArgs(cid,
14247                            getAppDexInstructionSets(ps), ps.isForwardLocked());
14248                    // The package status is changed only if the code path
14249                    // matches between settings and the container id.
14250                    if (ps.codePathString != null
14251                            && ps.codePathString.startsWith(args.getCodePath())) {
14252                        if (DEBUG_SD_INSTALL) {
14253                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
14254                                    + " at code path: " + ps.codePathString);
14255                        }
14256
14257                        // We do have a valid package installed on sdcard
14258                        processCids.put(args, ps.codePathString);
14259                        final int uid = ps.appId;
14260                        if (uid != -1) {
14261                            uidArr = ArrayUtils.appendInt(uidArr, uid);
14262                        }
14263                    } else {
14264                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
14265                                + ps.codePathString);
14266                    }
14267                }
14268            }
14269
14270            Arrays.sort(uidArr);
14271        }
14272
14273        // Process packages with valid entries.
14274        if (isMounted) {
14275            if (DEBUG_SD_INSTALL)
14276                Log.i(TAG, "Loading packages");
14277            loadMediaPackages(processCids, uidArr);
14278            startCleaningPackages();
14279            mInstallerService.onSecureContainersAvailable();
14280        } else {
14281            if (DEBUG_SD_INSTALL)
14282                Log.i(TAG, "Unloading packages");
14283            unloadMediaPackages(processCids, uidArr, reportStatus);
14284        }
14285    }
14286
14287    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14288            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
14289        final int size = infos.size();
14290        final String[] packageNames = new String[size];
14291        final int[] packageUids = new int[size];
14292        for (int i = 0; i < size; i++) {
14293            final ApplicationInfo info = infos.get(i);
14294            packageNames[i] = info.packageName;
14295            packageUids[i] = info.uid;
14296        }
14297        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
14298                finishedReceiver);
14299    }
14300
14301    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14302            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
14303        sendResourcesChangedBroadcast(mediaStatus, replacing,
14304                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
14305    }
14306
14307    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14308            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
14309        int size = pkgList.length;
14310        if (size > 0) {
14311            // Send broadcasts here
14312            Bundle extras = new Bundle();
14313            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14314            if (uidArr != null) {
14315                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
14316            }
14317            if (replacing) {
14318                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
14319            }
14320            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
14321                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
14322            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
14323        }
14324    }
14325
14326   /*
14327     * Look at potentially valid container ids from processCids If package
14328     * information doesn't match the one on record or package scanning fails,
14329     * the cid is added to list of removeCids. We currently don't delete stale
14330     * containers.
14331     */
14332    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
14333        ArrayList<String> pkgList = new ArrayList<String>();
14334        Set<AsecInstallArgs> keys = processCids.keySet();
14335
14336        for (AsecInstallArgs args : keys) {
14337            String codePath = processCids.get(args);
14338            if (DEBUG_SD_INSTALL)
14339                Log.i(TAG, "Loading container : " + args.cid);
14340            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14341            try {
14342                // Make sure there are no container errors first.
14343                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
14344                    Slog.e(TAG, "Failed to mount cid : " + args.cid
14345                            + " when installing from sdcard");
14346                    continue;
14347                }
14348                // Check code path here.
14349                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
14350                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
14351                            + " does not match one in settings " + codePath);
14352                    continue;
14353                }
14354                // Parse package
14355                int parseFlags = mDefParseFlags;
14356                if (args.isExternalAsec()) {
14357                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
14358                }
14359                if (args.isFwdLocked()) {
14360                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
14361                }
14362
14363                synchronized (mInstallLock) {
14364                    PackageParser.Package pkg = null;
14365                    try {
14366                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
14367                    } catch (PackageManagerException e) {
14368                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
14369                    }
14370                    // Scan the package
14371                    if (pkg != null) {
14372                        /*
14373                         * TODO why is the lock being held? doPostInstall is
14374                         * called in other places without the lock. This needs
14375                         * to be straightened out.
14376                         */
14377                        // writer
14378                        synchronized (mPackages) {
14379                            retCode = PackageManager.INSTALL_SUCCEEDED;
14380                            pkgList.add(pkg.packageName);
14381                            // Post process args
14382                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
14383                                    pkg.applicationInfo.uid);
14384                        }
14385                    } else {
14386                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
14387                    }
14388                }
14389
14390            } finally {
14391                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
14392                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
14393                }
14394            }
14395        }
14396        // writer
14397        synchronized (mPackages) {
14398            // If the platform SDK has changed since the last time we booted,
14399            // we need to re-grant app permission to catch any new ones that
14400            // appear. This is really a hack, and means that apps can in some
14401            // cases get permissions that the user didn't initially explicitly
14402            // allow... it would be nice to have some better way to handle
14403            // this situation.
14404            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
14405            if (regrantPermissions)
14406                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
14407                        + mSdkVersion + "; regranting permissions for external storage");
14408            mSettings.mExternalSdkPlatform = mSdkVersion;
14409
14410            // Make sure group IDs have been assigned, and any permission
14411            // changes in other apps are accounted for
14412            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
14413                    | (regrantPermissions
14414                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
14415                            : 0));
14416
14417            mSettings.updateExternalDatabaseVersion();
14418
14419            // can downgrade to reader
14420            // Persist settings
14421            mSettings.writeLPr();
14422        }
14423        // Send a broadcast to let everyone know we are done processing
14424        if (pkgList.size() > 0) {
14425            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
14426        }
14427    }
14428
14429   /*
14430     * Utility method to unload a list of specified containers
14431     */
14432    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
14433        // Just unmount all valid containers.
14434        for (AsecInstallArgs arg : cidArgs) {
14435            synchronized (mInstallLock) {
14436                arg.doPostDeleteLI(false);
14437           }
14438       }
14439   }
14440
14441    /*
14442     * Unload packages mounted on external media. This involves deleting package
14443     * data from internal structures, sending broadcasts about diabled packages,
14444     * gc'ing to free up references, unmounting all secure containers
14445     * corresponding to packages on external media, and posting a
14446     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
14447     * that we always have to post this message if status has been requested no
14448     * matter what.
14449     */
14450    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
14451            final boolean reportStatus) {
14452        if (DEBUG_SD_INSTALL)
14453            Log.i(TAG, "unloading media packages");
14454        ArrayList<String> pkgList = new ArrayList<String>();
14455        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
14456        final Set<AsecInstallArgs> keys = processCids.keySet();
14457        for (AsecInstallArgs args : keys) {
14458            String pkgName = args.getPackageName();
14459            if (DEBUG_SD_INSTALL)
14460                Log.i(TAG, "Trying to unload pkg : " + pkgName);
14461            // Delete package internally
14462            PackageRemovedInfo outInfo = new PackageRemovedInfo();
14463            synchronized (mInstallLock) {
14464                boolean res = deletePackageLI(pkgName, null, false, null, null,
14465                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
14466                if (res) {
14467                    pkgList.add(pkgName);
14468                } else {
14469                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
14470                    failedList.add(args);
14471                }
14472            }
14473        }
14474
14475        // reader
14476        synchronized (mPackages) {
14477            // We didn't update the settings after removing each package;
14478            // write them now for all packages.
14479            mSettings.writeLPr();
14480        }
14481
14482        // We have to absolutely send UPDATED_MEDIA_STATUS only
14483        // after confirming that all the receivers processed the ordered
14484        // broadcast when packages get disabled, force a gc to clean things up.
14485        // and unload all the containers.
14486        if (pkgList.size() > 0) {
14487            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
14488                    new IIntentReceiver.Stub() {
14489                public void performReceive(Intent intent, int resultCode, String data,
14490                        Bundle extras, boolean ordered, boolean sticky,
14491                        int sendingUser) throws RemoteException {
14492                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
14493                            reportStatus ? 1 : 0, 1, keys);
14494                    mHandler.sendMessage(msg);
14495                }
14496            });
14497        } else {
14498            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
14499                    keys);
14500            mHandler.sendMessage(msg);
14501        }
14502    }
14503
14504    private void loadPrivatePackages(VolumeInfo vol) {
14505        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
14506        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
14507        synchronized (mInstallLock) {
14508        synchronized (mPackages) {
14509            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
14510            for (PackageSetting ps : packages) {
14511                final PackageParser.Package pkg;
14512                try {
14513                    pkg = scanPackageLI(ps.codePath, parseFlags, 0, 0, null);
14514                    loaded.add(pkg.applicationInfo);
14515                } catch (PackageManagerException e) {
14516                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
14517                }
14518            }
14519
14520            // TODO: regrant any permissions that changed based since original install
14521
14522            mSettings.writeLPr();
14523        }
14524        }
14525
14526        Slog.d(TAG, "Loaded packages " + loaded);
14527        sendResourcesChangedBroadcast(true, false, loaded, null);
14528    }
14529
14530    private void unloadPrivatePackages(VolumeInfo vol) {
14531        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
14532        synchronized (mInstallLock) {
14533        synchronized (mPackages) {
14534            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
14535            for (PackageSetting ps : packages) {
14536                if (ps.pkg == null) continue;
14537
14538                final ApplicationInfo info = ps.pkg.applicationInfo;
14539                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
14540                if (deletePackageLI(ps.name, null, false, null, null,
14541                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
14542                    unloaded.add(info);
14543                } else {
14544                    Slog.w(TAG, "Failed to unload " + ps.codePath);
14545                }
14546            }
14547
14548            mSettings.writeLPr();
14549        }
14550        }
14551
14552        Slog.d(TAG, "Unloaded packages " + unloaded);
14553        sendResourcesChangedBroadcast(false, false, unloaded, null);
14554    }
14555
14556    private void unfreezePackage(String packageName) {
14557        synchronized (mPackages) {
14558            final PackageSetting ps = mSettings.mPackages.get(packageName);
14559            if (ps != null) {
14560                ps.frozen = false;
14561            }
14562        }
14563    }
14564
14565    @Override
14566    public int movePackage(final String packageName, final String volumeUuid) {
14567        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
14568
14569        final int moveId = mNextMoveId.getAndIncrement();
14570        try {
14571            movePackageInternal(packageName, volumeUuid, moveId);
14572        } catch (PackageManagerException e) {
14573            Slog.d(TAG, "Failed to move " + packageName, e);
14574            mMoveCallbacks.notifyStatusChanged(moveId,
14575                    PackageManager.MOVE_FAILED_INTERNAL_ERROR);
14576        }
14577        return moveId;
14578    }
14579
14580    private void movePackageInternal(final String packageName, final String volumeUuid,
14581            final int moveId) throws PackageManagerException {
14582        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
14583        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14584        final PackageManager pm = mContext.getPackageManager();
14585
14586        final boolean currentAsec;
14587        final String currentVolumeUuid;
14588        final File codeFile;
14589        final String installerPackageName;
14590        final String packageAbiOverride;
14591        final int appId;
14592        final String seinfo;
14593        final String label;
14594
14595        // reader
14596        synchronized (mPackages) {
14597            final PackageParser.Package pkg = mPackages.get(packageName);
14598            final PackageSetting ps = mSettings.mPackages.get(packageName);
14599            if (pkg == null || ps == null) {
14600                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
14601            }
14602
14603            if (pkg.applicationInfo.isSystemApp()) {
14604                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
14605                        "Cannot move system application");
14606            }
14607
14608            if (Objects.equals(ps.volumeUuid, volumeUuid)) {
14609                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14610                        "Package already moved to " + volumeUuid);
14611            }
14612
14613            final File probe = new File(pkg.codePath);
14614            final File probeOat = new File(probe, "oat");
14615            if (!probe.isDirectory() || !probeOat.isDirectory()) {
14616                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14617                        "Move only supported for modern cluster style installs");
14618            }
14619
14620            if (ps.frozen) {
14621                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
14622                        "Failed to move already frozen package");
14623            }
14624            ps.frozen = true;
14625
14626            currentAsec = pkg.applicationInfo.isForwardLocked()
14627                    || pkg.applicationInfo.isExternalAsec();
14628            currentVolumeUuid = ps.volumeUuid;
14629            codeFile = new File(pkg.codePath);
14630            installerPackageName = ps.installerPackageName;
14631            packageAbiOverride = ps.cpuAbiOverrideString;
14632            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
14633            seinfo = pkg.applicationInfo.seinfo;
14634            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
14635        }
14636
14637        // Now that we're guarded by frozen state, kill app during move
14638        killApplication(packageName, appId, "move pkg");
14639
14640        final Bundle extras = new Bundle();
14641        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
14642        extras.putString(Intent.EXTRA_TITLE, label);
14643        mMoveCallbacks.notifyCreated(moveId, extras);
14644
14645        int installFlags;
14646        final boolean moveCompleteApp;
14647        final File measurePath;
14648
14649        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
14650            installFlags = INSTALL_INTERNAL;
14651            moveCompleteApp = !currentAsec;
14652            measurePath = Environment.getDataAppDirectory(volumeUuid);
14653        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
14654            installFlags = INSTALL_EXTERNAL;
14655            moveCompleteApp = false;
14656            measurePath = storage.getPrimaryPhysicalVolume().getPath();
14657        } else {
14658            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
14659            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
14660                    || !volume.isMountedWritable()) {
14661                unfreezePackage(packageName);
14662                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14663                        "Move location not mounted private volume");
14664            }
14665
14666            Preconditions.checkState(!currentAsec);
14667
14668            installFlags = INSTALL_INTERNAL;
14669            moveCompleteApp = true;
14670            measurePath = Environment.getDataAppDirectory(volumeUuid);
14671        }
14672
14673        final PackageStats stats = new PackageStats(null, -1);
14674        synchronized (mInstaller) {
14675            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
14676                unfreezePackage(packageName);
14677                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14678                        "Failed to measure package size");
14679            }
14680        }
14681
14682        Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " + stats.dataSize);
14683
14684        final long startFreeBytes = measurePath.getFreeSpace();
14685        final long sizeBytes;
14686        if (moveCompleteApp) {
14687            sizeBytes = stats.codeSize + stats.dataSize;
14688        } else {
14689            sizeBytes = stats.codeSize;
14690        }
14691
14692        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
14693            unfreezePackage(packageName);
14694            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14695                    "Not enough free space to move");
14696        }
14697
14698        mMoveCallbacks.notifyStatusChanged(moveId, 10);
14699
14700        final CountDownLatch installedLatch = new CountDownLatch(1);
14701        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
14702            @Override
14703            public void onUserActionRequired(Intent intent) throws RemoteException {
14704                throw new IllegalStateException();
14705            }
14706
14707            @Override
14708            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
14709                    Bundle extras) throws RemoteException {
14710                Slog.d(TAG, "Install result for move: "
14711                        + PackageManager.installStatusToString(returnCode, msg));
14712
14713                installedLatch.countDown();
14714
14715                // Regardless of success or failure of the move operation,
14716                // always unfreeze the package
14717                unfreezePackage(packageName);
14718
14719                final int status = PackageManager.installStatusToPublicStatus(returnCode);
14720                switch (status) {
14721                    case PackageInstaller.STATUS_SUCCESS:
14722                        mMoveCallbacks.notifyStatusChanged(moveId,
14723                                PackageManager.MOVE_SUCCEEDED);
14724                        break;
14725                    case PackageInstaller.STATUS_FAILURE_STORAGE:
14726                        mMoveCallbacks.notifyStatusChanged(moveId,
14727                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
14728                        break;
14729                    default:
14730                        mMoveCallbacks.notifyStatusChanged(moveId,
14731                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
14732                        break;
14733                }
14734            }
14735        };
14736
14737        final MoveInfo move;
14738        if (moveCompleteApp) {
14739            // Kick off a thread to report progress estimates
14740            new Thread() {
14741                @Override
14742                public void run() {
14743                    while (true) {
14744                        try {
14745                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
14746                                break;
14747                            }
14748                        } catch (InterruptedException ignored) {
14749                        }
14750
14751                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
14752                        final int progress = 10 + (int) MathUtils.constrain(
14753                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
14754                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
14755                    }
14756                }
14757            }.start();
14758
14759            final String dataAppName = codeFile.getName();
14760            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
14761                    dataAppName, appId, seinfo);
14762        } else {
14763            move = null;
14764        }
14765
14766        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
14767
14768        final Message msg = mHandler.obtainMessage(INIT_COPY);
14769        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
14770        msg.obj = new InstallParams(origin, move, installObserver, installFlags,
14771                installerPackageName, volumeUuid, null, user, packageAbiOverride);
14772        mHandler.sendMessage(msg);
14773    }
14774
14775    @Override
14776    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
14777        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
14778
14779        final int realMoveId = mNextMoveId.getAndIncrement();
14780        final Bundle extras = new Bundle();
14781        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
14782        mMoveCallbacks.notifyCreated(realMoveId, extras);
14783
14784        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
14785            @Override
14786            public void onCreated(int moveId, Bundle extras) {
14787                // Ignored
14788            }
14789
14790            @Override
14791            public void onStatusChanged(int moveId, int status, long estMillis) {
14792                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
14793            }
14794        };
14795
14796        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14797        storage.setPrimaryStorageUuid(volumeUuid, callback);
14798        return realMoveId;
14799    }
14800
14801    @Override
14802    public int getMoveStatus(int moveId) {
14803        mContext.enforceCallingOrSelfPermission(
14804                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
14805        return mMoveCallbacks.mLastStatus.get(moveId);
14806    }
14807
14808    @Override
14809    public void registerMoveCallback(IPackageMoveObserver callback) {
14810        mContext.enforceCallingOrSelfPermission(
14811                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
14812        mMoveCallbacks.register(callback);
14813    }
14814
14815    @Override
14816    public void unregisterMoveCallback(IPackageMoveObserver callback) {
14817        mContext.enforceCallingOrSelfPermission(
14818                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
14819        mMoveCallbacks.unregister(callback);
14820    }
14821
14822    @Override
14823    public boolean setInstallLocation(int loc) {
14824        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
14825                null);
14826        if (getInstallLocation() == loc) {
14827            return true;
14828        }
14829        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
14830                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
14831            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
14832                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
14833            return true;
14834        }
14835        return false;
14836   }
14837
14838    @Override
14839    public int getInstallLocation() {
14840        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14841                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
14842                PackageHelper.APP_INSTALL_AUTO);
14843    }
14844
14845    /** Called by UserManagerService */
14846    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
14847        mDirtyUsers.remove(userHandle);
14848        mSettings.removeUserLPw(userHandle);
14849        mPendingBroadcasts.remove(userHandle);
14850        if (mInstaller != null) {
14851            // Technically, we shouldn't be doing this with the package lock
14852            // held.  However, this is very rare, and there is already so much
14853            // other disk I/O going on, that we'll let it slide for now.
14854            final StorageManager storage = StorageManager.from(mContext);
14855            final List<VolumeInfo> vols = storage.getVolumes();
14856            for (VolumeInfo vol : vols) {
14857                if (vol.getType() == VolumeInfo.TYPE_PRIVATE && vol.isMountedWritable()) {
14858                    final String volumeUuid = vol.getFsUuid();
14859                    Slog.d(TAG, "Removing user data on volume " + volumeUuid);
14860                    mInstaller.removeUserDataDirs(volumeUuid, userHandle);
14861                }
14862            }
14863        }
14864        mUserNeedsBadging.delete(userHandle);
14865        removeUnusedPackagesLILPw(userManager, userHandle);
14866    }
14867
14868    /**
14869     * We're removing userHandle and would like to remove any downloaded packages
14870     * that are no longer in use by any other user.
14871     * @param userHandle the user being removed
14872     */
14873    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
14874        final boolean DEBUG_CLEAN_APKS = false;
14875        int [] users = userManager.getUserIdsLPr();
14876        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
14877        while (psit.hasNext()) {
14878            PackageSetting ps = psit.next();
14879            if (ps.pkg == null) {
14880                continue;
14881            }
14882            final String packageName = ps.pkg.packageName;
14883            // Skip over if system app
14884            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
14885                continue;
14886            }
14887            if (DEBUG_CLEAN_APKS) {
14888                Slog.i(TAG, "Checking package " + packageName);
14889            }
14890            boolean keep = false;
14891            for (int i = 0; i < users.length; i++) {
14892                if (users[i] != userHandle && ps.getInstalled(users[i])) {
14893                    keep = true;
14894                    if (DEBUG_CLEAN_APKS) {
14895                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
14896                                + users[i]);
14897                    }
14898                    break;
14899                }
14900            }
14901            if (!keep) {
14902                if (DEBUG_CLEAN_APKS) {
14903                    Slog.i(TAG, "  Removing package " + packageName);
14904                }
14905                mHandler.post(new Runnable() {
14906                    public void run() {
14907                        deletePackageX(packageName, userHandle, 0);
14908                    } //end run
14909                });
14910            }
14911        }
14912    }
14913
14914    /** Called by UserManagerService */
14915    void createNewUserLILPw(int userHandle, File path) {
14916        if (mInstaller != null) {
14917            mInstaller.createUserConfig(userHandle);
14918            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
14919        }
14920    }
14921
14922    void newUserCreatedLILPw(int userHandle) {
14923        // Adding a user requires updating runtime permissions for system apps.
14924        updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
14925    }
14926
14927    @Override
14928    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
14929        mContext.enforceCallingOrSelfPermission(
14930                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14931                "Only package verification agents can read the verifier device identity");
14932
14933        synchronized (mPackages) {
14934            return mSettings.getVerifierDeviceIdentityLPw();
14935        }
14936    }
14937
14938    @Override
14939    public void setPermissionEnforced(String permission, boolean enforced) {
14940        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
14941        if (READ_EXTERNAL_STORAGE.equals(permission)) {
14942            synchronized (mPackages) {
14943                if (mSettings.mReadExternalStorageEnforced == null
14944                        || mSettings.mReadExternalStorageEnforced != enforced) {
14945                    mSettings.mReadExternalStorageEnforced = enforced;
14946                    mSettings.writeLPr();
14947                }
14948            }
14949            // kill any non-foreground processes so we restart them and
14950            // grant/revoke the GID.
14951            final IActivityManager am = ActivityManagerNative.getDefault();
14952            if (am != null) {
14953                final long token = Binder.clearCallingIdentity();
14954                try {
14955                    am.killProcessesBelowForeground("setPermissionEnforcement");
14956                } catch (RemoteException e) {
14957                } finally {
14958                    Binder.restoreCallingIdentity(token);
14959                }
14960            }
14961        } else {
14962            throw new IllegalArgumentException("No selective enforcement for " + permission);
14963        }
14964    }
14965
14966    @Override
14967    @Deprecated
14968    public boolean isPermissionEnforced(String permission) {
14969        return true;
14970    }
14971
14972    @Override
14973    public boolean isStorageLow() {
14974        final long token = Binder.clearCallingIdentity();
14975        try {
14976            final DeviceStorageMonitorInternal
14977                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
14978            if (dsm != null) {
14979                return dsm.isMemoryLow();
14980            } else {
14981                return false;
14982            }
14983        } finally {
14984            Binder.restoreCallingIdentity(token);
14985        }
14986    }
14987
14988    @Override
14989    public IPackageInstaller getPackageInstaller() {
14990        return mInstallerService;
14991    }
14992
14993    private boolean userNeedsBadging(int userId) {
14994        int index = mUserNeedsBadging.indexOfKey(userId);
14995        if (index < 0) {
14996            final UserInfo userInfo;
14997            final long token = Binder.clearCallingIdentity();
14998            try {
14999                userInfo = sUserManager.getUserInfo(userId);
15000            } finally {
15001                Binder.restoreCallingIdentity(token);
15002            }
15003            final boolean b;
15004            if (userInfo != null && userInfo.isManagedProfile()) {
15005                b = true;
15006            } else {
15007                b = false;
15008            }
15009            mUserNeedsBadging.put(userId, b);
15010            return b;
15011        }
15012        return mUserNeedsBadging.valueAt(index);
15013    }
15014
15015    @Override
15016    public KeySet getKeySetByAlias(String packageName, String alias) {
15017        if (packageName == null || alias == null) {
15018            return null;
15019        }
15020        synchronized(mPackages) {
15021            final PackageParser.Package pkg = mPackages.get(packageName);
15022            if (pkg == null) {
15023                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15024                throw new IllegalArgumentException("Unknown package: " + packageName);
15025            }
15026            KeySetManagerService ksms = mSettings.mKeySetManagerService;
15027            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
15028        }
15029    }
15030
15031    @Override
15032    public KeySet getSigningKeySet(String packageName) {
15033        if (packageName == null) {
15034            return null;
15035        }
15036        synchronized(mPackages) {
15037            final PackageParser.Package pkg = mPackages.get(packageName);
15038            if (pkg == null) {
15039                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15040                throw new IllegalArgumentException("Unknown package: " + packageName);
15041            }
15042            if (pkg.applicationInfo.uid != Binder.getCallingUid()
15043                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
15044                throw new SecurityException("May not access signing KeySet of other apps.");
15045            }
15046            KeySetManagerService ksms = mSettings.mKeySetManagerService;
15047            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
15048        }
15049    }
15050
15051    @Override
15052    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
15053        if (packageName == null || ks == null) {
15054            return false;
15055        }
15056        synchronized(mPackages) {
15057            final PackageParser.Package pkg = mPackages.get(packageName);
15058            if (pkg == null) {
15059                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15060                throw new IllegalArgumentException("Unknown package: " + packageName);
15061            }
15062            IBinder ksh = ks.getToken();
15063            if (ksh instanceof KeySetHandle) {
15064                KeySetManagerService ksms = mSettings.mKeySetManagerService;
15065                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
15066            }
15067            return false;
15068        }
15069    }
15070
15071    @Override
15072    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
15073        if (packageName == null || ks == null) {
15074            return false;
15075        }
15076        synchronized(mPackages) {
15077            final PackageParser.Package pkg = mPackages.get(packageName);
15078            if (pkg == null) {
15079                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15080                throw new IllegalArgumentException("Unknown package: " + packageName);
15081            }
15082            IBinder ksh = ks.getToken();
15083            if (ksh instanceof KeySetHandle) {
15084                KeySetManagerService ksms = mSettings.mKeySetManagerService;
15085                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
15086            }
15087            return false;
15088        }
15089    }
15090
15091    public void getUsageStatsIfNoPackageUsageInfo() {
15092        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
15093            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
15094            if (usm == null) {
15095                throw new IllegalStateException("UsageStatsManager must be initialized");
15096            }
15097            long now = System.currentTimeMillis();
15098            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
15099            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
15100                String packageName = entry.getKey();
15101                PackageParser.Package pkg = mPackages.get(packageName);
15102                if (pkg == null) {
15103                    continue;
15104                }
15105                UsageStats usage = entry.getValue();
15106                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
15107                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
15108            }
15109        }
15110    }
15111
15112    /**
15113     * Check and throw if the given before/after packages would be considered a
15114     * downgrade.
15115     */
15116    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
15117            throws PackageManagerException {
15118        if (after.versionCode < before.mVersionCode) {
15119            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15120                    "Update version code " + after.versionCode + " is older than current "
15121                    + before.mVersionCode);
15122        } else if (after.versionCode == before.mVersionCode) {
15123            if (after.baseRevisionCode < before.baseRevisionCode) {
15124                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15125                        "Update base revision code " + after.baseRevisionCode
15126                        + " is older than current " + before.baseRevisionCode);
15127            }
15128
15129            if (!ArrayUtils.isEmpty(after.splitNames)) {
15130                for (int i = 0; i < after.splitNames.length; i++) {
15131                    final String splitName = after.splitNames[i];
15132                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
15133                    if (j != -1) {
15134                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
15135                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15136                                    "Update split " + splitName + " revision code "
15137                                    + after.splitRevisionCodes[i] + " is older than current "
15138                                    + before.splitRevisionCodes[j]);
15139                        }
15140                    }
15141                }
15142            }
15143        }
15144    }
15145
15146    private static class MoveCallbacks extends Handler {
15147        private static final int MSG_CREATED = 1;
15148        private static final int MSG_STATUS_CHANGED = 2;
15149
15150        private final RemoteCallbackList<IPackageMoveObserver>
15151                mCallbacks = new RemoteCallbackList<>();
15152
15153        private final SparseIntArray mLastStatus = new SparseIntArray();
15154
15155        public MoveCallbacks(Looper looper) {
15156            super(looper);
15157        }
15158
15159        public void register(IPackageMoveObserver callback) {
15160            mCallbacks.register(callback);
15161        }
15162
15163        public void unregister(IPackageMoveObserver callback) {
15164            mCallbacks.unregister(callback);
15165        }
15166
15167        @Override
15168        public void handleMessage(Message msg) {
15169            final SomeArgs args = (SomeArgs) msg.obj;
15170            final int n = mCallbacks.beginBroadcast();
15171            for (int i = 0; i < n; i++) {
15172                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
15173                try {
15174                    invokeCallback(callback, msg.what, args);
15175                } catch (RemoteException ignored) {
15176                }
15177            }
15178            mCallbacks.finishBroadcast();
15179            args.recycle();
15180        }
15181
15182        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
15183                throws RemoteException {
15184            switch (what) {
15185                case MSG_CREATED: {
15186                    callback.onCreated(args.argi1, (Bundle) args.arg2);
15187                    break;
15188                }
15189                case MSG_STATUS_CHANGED: {
15190                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
15191                    break;
15192                }
15193            }
15194        }
15195
15196        private void notifyCreated(int moveId, Bundle extras) {
15197            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
15198
15199            final SomeArgs args = SomeArgs.obtain();
15200            args.argi1 = moveId;
15201            args.arg2 = extras;
15202            obtainMessage(MSG_CREATED, args).sendToTarget();
15203        }
15204
15205        private void notifyStatusChanged(int moveId, int status) {
15206            notifyStatusChanged(moveId, status, -1);
15207        }
15208
15209        private void notifyStatusChanged(int moveId, int status, long estMillis) {
15210            Slog.v(TAG, "Move " + moveId + " status " + status);
15211
15212            final SomeArgs args = SomeArgs.obtain();
15213            args.argi1 = moveId;
15214            args.argi2 = status;
15215            args.arg3 = estMillis;
15216            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
15217
15218            synchronized (mLastStatus) {
15219                mLastStatus.put(moveId, status);
15220            }
15221        }
15222    }
15223}
15224