PackageManagerService.java revision a91a6f68f4c2564f763d28a3cfcd9d8b7a3f5db9
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 codePath = pkg.applicationInfo.getCodePath();
6305        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
6306        if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
6307            setBundledAppAbisAndRoots(pkg, pkgSetting);
6308
6309            // If we haven't found any native libraries for the app, check if it has
6310            // renderscript code. We'll need to force the app to 32 bit if it has
6311            // renderscript bitcode.
6312            if (pkg.applicationInfo.primaryCpuAbi == null
6313                    && pkg.applicationInfo.secondaryCpuAbi == null
6314                    && Build.SUPPORTED_64_BIT_ABIS.length >  0) {
6315                NativeLibraryHelper.Handle handle = null;
6316                try {
6317                    handle = NativeLibraryHelper.Handle.create(scanFile);
6318                    if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
6319                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6320                    }
6321                } catch (IOException ioe) {
6322                    Slog.w(TAG, "Error scanning system app : " + ioe);
6323                } finally {
6324                    IoUtils.closeQuietly(handle);
6325                }
6326            }
6327
6328            setNativeLibraryPaths(pkg);
6329        } else {
6330            // TODO: We can probably be smarter about this stuff. For installed apps,
6331            // we can calculate this information at install time once and for all. For
6332            // system apps, we can probably assume that this information doesn't change
6333            // after the first boot scan. As things stand, we do lots of unnecessary work.
6334
6335            // Give ourselves some initial paths; we'll come back for another
6336            // pass once we've determined ABI below.
6337            setNativeLibraryPaths(pkg);
6338
6339            final boolean isAsec = pkg.isForwardLocked() || isExternal(pkg);
6340            final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
6341            final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
6342
6343            NativeLibraryHelper.Handle handle = null;
6344            try {
6345                handle = NativeLibraryHelper.Handle.create(scanFile);
6346                // TODO(multiArch): This can be null for apps that didn't go through the
6347                // usual installation process. We can calculate it again, like we
6348                // do during install time.
6349                //
6350                // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
6351                // unnecessary.
6352                final File nativeLibraryRoot = new File(nativeLibraryRootStr);
6353
6354                // Null out the abis so that they can be recalculated.
6355                pkg.applicationInfo.primaryCpuAbi = null;
6356                pkg.applicationInfo.secondaryCpuAbi = null;
6357                if (isMultiArch(pkg.applicationInfo)) {
6358                    // Warn if we've set an abiOverride for multi-lib packages..
6359                    // By definition, we need to copy both 32 and 64 bit libraries for
6360                    // such packages.
6361                    if (pkg.cpuAbiOverride != null
6362                            && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
6363                        Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
6364                    }
6365
6366                    int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
6367                    int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
6368                    if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
6369                        if (isAsec) {
6370                            abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
6371                        } else {
6372                            abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
6373                                    nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
6374                                    useIsaSpecificSubdirs);
6375                        }
6376                    }
6377
6378                    maybeThrowExceptionForMultiArchCopy(
6379                            "Error unpackaging 32 bit native libs for multiarch app.", abi32);
6380
6381                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
6382                        if (isAsec) {
6383                            abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
6384                        } else {
6385                            abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
6386                                    nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
6387                                    useIsaSpecificSubdirs);
6388                        }
6389                    }
6390
6391                    maybeThrowExceptionForMultiArchCopy(
6392                            "Error unpackaging 64 bit native libs for multiarch app.", abi64);
6393
6394                    if (abi64 >= 0) {
6395                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
6396                    }
6397
6398                    if (abi32 >= 0) {
6399                        final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
6400                        if (abi64 >= 0) {
6401                            pkg.applicationInfo.secondaryCpuAbi = abi;
6402                        } else {
6403                            pkg.applicationInfo.primaryCpuAbi = abi;
6404                        }
6405                    }
6406                } else {
6407                    String[] abiList = (cpuAbiOverride != null) ?
6408                            new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
6409
6410                    // Enable gross and lame hacks for apps that are built with old
6411                    // SDK tools. We must scan their APKs for renderscript bitcode and
6412                    // not launch them if it's present. Don't bother checking on devices
6413                    // that don't have 64 bit support.
6414                    boolean needsRenderScriptOverride = false;
6415                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
6416                            NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
6417                        abiList = Build.SUPPORTED_32_BIT_ABIS;
6418                        needsRenderScriptOverride = true;
6419                    }
6420
6421                    final int copyRet;
6422                    if (isAsec) {
6423                        copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
6424                    } else {
6425                        copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
6426                                nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
6427                    }
6428
6429                    if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
6430                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
6431                                "Error unpackaging native libs for app, errorCode=" + copyRet);
6432                    }
6433
6434                    if (copyRet >= 0) {
6435                        pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
6436                    } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
6437                        pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
6438                    } else if (needsRenderScriptOverride) {
6439                        pkg.applicationInfo.primaryCpuAbi = abiList[0];
6440                    }
6441                }
6442            } catch (IOException ioe) {
6443                Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
6444            } finally {
6445                IoUtils.closeQuietly(handle);
6446            }
6447
6448            // Now that we've calculated the ABIs and determined if it's an internal app,
6449            // we will go ahead and populate the nativeLibraryPath.
6450            setNativeLibraryPaths(pkg);
6451
6452            if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
6453            final int[] userIds = sUserManager.getUserIds();
6454            synchronized (mInstallLock) {
6455                // Create a native library symlink only if we have native libraries
6456                // and if the native libraries are 32 bit libraries. We do not provide
6457                // this symlink for 64 bit libraries.
6458                if (pkg.applicationInfo.primaryCpuAbi != null &&
6459                        !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
6460                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
6461                    for (int userId : userIds) {
6462                        if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
6463                                nativeLibPath, userId) < 0) {
6464                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
6465                                    "Failed linking native library dir (user=" + userId + ")");
6466                        }
6467                    }
6468                }
6469            }
6470        }
6471
6472        // This is a special case for the "system" package, where the ABI is
6473        // dictated by the zygote configuration (and init.rc). We should keep track
6474        // of this ABI so that we can deal with "normal" applications that run under
6475        // the same UID correctly.
6476        if (mPlatformPackage == pkg) {
6477            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
6478                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
6479        }
6480
6481        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6482        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6483        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
6484        // Copy the derived override back to the parsed package, so that we can
6485        // update the package settings accordingly.
6486        pkg.cpuAbiOverride = cpuAbiOverride;
6487
6488        if (DEBUG_ABI_SELECTION) {
6489            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
6490                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
6491                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
6492        }
6493
6494        // Push the derived path down into PackageSettings so we know what to
6495        // clean up at uninstall time.
6496        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
6497
6498        if (DEBUG_ABI_SELECTION) {
6499            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
6500                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
6501                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
6502        }
6503
6504        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
6505            // We don't do this here during boot because we can do it all
6506            // at once after scanning all existing packages.
6507            //
6508            // We also do this *before* we perform dexopt on this package, so that
6509            // we can avoid redundant dexopts, and also to make sure we've got the
6510            // code and package path correct.
6511            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
6512                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
6513        }
6514
6515        if ((scanFlags & SCAN_NO_DEX) == 0) {
6516            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
6517                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */);
6518            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6519                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
6520            }
6521        }
6522        if (mFactoryTest && pkg.requestedPermissions.contains(
6523                android.Manifest.permission.FACTORY_TEST)) {
6524            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
6525        }
6526
6527        ArrayList<PackageParser.Package> clientLibPkgs = null;
6528
6529        // writer
6530        synchronized (mPackages) {
6531            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6532                // Only system apps can add new shared libraries.
6533                if (pkg.libraryNames != null) {
6534                    for (int i=0; i<pkg.libraryNames.size(); i++) {
6535                        String name = pkg.libraryNames.get(i);
6536                        boolean allowed = false;
6537                        if (pkg.isUpdatedSystemApp()) {
6538                            // New library entries can only be added through the
6539                            // system image.  This is important to get rid of a lot
6540                            // of nasty edge cases: for example if we allowed a non-
6541                            // system update of the app to add a library, then uninstalling
6542                            // the update would make the library go away, and assumptions
6543                            // we made such as through app install filtering would now
6544                            // have allowed apps on the device which aren't compatible
6545                            // with it.  Better to just have the restriction here, be
6546                            // conservative, and create many fewer cases that can negatively
6547                            // impact the user experience.
6548                            final PackageSetting sysPs = mSettings
6549                                    .getDisabledSystemPkgLPr(pkg.packageName);
6550                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
6551                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
6552                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
6553                                        allowed = true;
6554                                        allowed = true;
6555                                        break;
6556                                    }
6557                                }
6558                            }
6559                        } else {
6560                            allowed = true;
6561                        }
6562                        if (allowed) {
6563                            if (!mSharedLibraries.containsKey(name)) {
6564                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
6565                            } else if (!name.equals(pkg.packageName)) {
6566                                Slog.w(TAG, "Package " + pkg.packageName + " library "
6567                                        + name + " already exists; skipping");
6568                            }
6569                        } else {
6570                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
6571                                    + name + " that is not declared on system image; skipping");
6572                        }
6573                    }
6574                    if ((scanFlags&SCAN_BOOTING) == 0) {
6575                        // If we are not booting, we need to update any applications
6576                        // that are clients of our shared library.  If we are booting,
6577                        // this will all be done once the scan is complete.
6578                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
6579                    }
6580                }
6581            }
6582        }
6583
6584        // We also need to dexopt any apps that are dependent on this library.  Note that
6585        // if these fail, we should abort the install since installing the library will
6586        // result in some apps being broken.
6587        if (clientLibPkgs != null) {
6588            if ((scanFlags & SCAN_NO_DEX) == 0) {
6589                for (int i = 0; i < clientLibPkgs.size(); i++) {
6590                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
6591                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
6592                            null /* instruction sets */, forceDex,
6593                            (scanFlags & SCAN_DEFER_DEX) != 0, false);
6594                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6595                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
6596                                "scanPackageLI failed to dexopt clientLibPkgs");
6597                    }
6598                }
6599            }
6600        }
6601
6602        // Also need to kill any apps that are dependent on the library.
6603        if (clientLibPkgs != null) {
6604            for (int i=0; i<clientLibPkgs.size(); i++) {
6605                PackageParser.Package clientPkg = clientLibPkgs.get(i);
6606                killApplication(clientPkg.applicationInfo.packageName,
6607                        clientPkg.applicationInfo.uid, "update lib");
6608            }
6609        }
6610
6611        // writer
6612        synchronized (mPackages) {
6613            // We don't expect installation to fail beyond this point
6614
6615            // Add the new setting to mSettings
6616            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
6617            // Add the new setting to mPackages
6618            mPackages.put(pkg.applicationInfo.packageName, pkg);
6619            // Make sure we don't accidentally delete its data.
6620            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
6621            while (iter.hasNext()) {
6622                PackageCleanItem item = iter.next();
6623                if (pkgName.equals(item.packageName)) {
6624                    iter.remove();
6625                }
6626            }
6627
6628            // Take care of first install / last update times.
6629            if (currentTime != 0) {
6630                if (pkgSetting.firstInstallTime == 0) {
6631                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
6632                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
6633                    pkgSetting.lastUpdateTime = currentTime;
6634                }
6635            } else if (pkgSetting.firstInstallTime == 0) {
6636                // We need *something*.  Take time time stamp of the file.
6637                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
6638            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
6639                if (scanFileTime != pkgSetting.timeStamp) {
6640                    // A package on the system image has changed; consider this
6641                    // to be an update.
6642                    pkgSetting.lastUpdateTime = scanFileTime;
6643                }
6644            }
6645
6646            // Add the package's KeySets to the global KeySetManagerService
6647            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6648            try {
6649                ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys);
6650                if (pkg.mKeySetMapping != null) {
6651                    ksms.addDefinedKeySetsToPackageLPw(pkg.packageName, pkg.mKeySetMapping);
6652                    if (pkg.mUpgradeKeySets != null) {
6653                        ksms.addUpgradeKeySetsToPackageLPw(pkg.packageName, pkg.mUpgradeKeySets);
6654                    }
6655                }
6656            } catch (NullPointerException e) {
6657                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
6658            } catch (IllegalArgumentException e) {
6659                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
6660            }
6661
6662            int N = pkg.providers.size();
6663            StringBuilder r = null;
6664            int i;
6665            for (i=0; i<N; i++) {
6666                PackageParser.Provider p = pkg.providers.get(i);
6667                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
6668                        p.info.processName, pkg.applicationInfo.uid);
6669                mProviders.addProvider(p);
6670                p.syncable = p.info.isSyncable;
6671                if (p.info.authority != null) {
6672                    String names[] = p.info.authority.split(";");
6673                    p.info.authority = null;
6674                    for (int j = 0; j < names.length; j++) {
6675                        if (j == 1 && p.syncable) {
6676                            // We only want the first authority for a provider to possibly be
6677                            // syncable, so if we already added this provider using a different
6678                            // authority clear the syncable flag. We copy the provider before
6679                            // changing it because the mProviders object contains a reference
6680                            // to a provider that we don't want to change.
6681                            // Only do this for the second authority since the resulting provider
6682                            // object can be the same for all future authorities for this provider.
6683                            p = new PackageParser.Provider(p);
6684                            p.syncable = false;
6685                        }
6686                        if (!mProvidersByAuthority.containsKey(names[j])) {
6687                            mProvidersByAuthority.put(names[j], p);
6688                            if (p.info.authority == null) {
6689                                p.info.authority = names[j];
6690                            } else {
6691                                p.info.authority = p.info.authority + ";" + names[j];
6692                            }
6693                            if (DEBUG_PACKAGE_SCANNING) {
6694                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6695                                    Log.d(TAG, "Registered content provider: " + names[j]
6696                                            + ", className = " + p.info.name + ", isSyncable = "
6697                                            + p.info.isSyncable);
6698                            }
6699                        } else {
6700                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6701                            Slog.w(TAG, "Skipping provider name " + names[j] +
6702                                    " (in package " + pkg.applicationInfo.packageName +
6703                                    "): name already used by "
6704                                    + ((other != null && other.getComponentName() != null)
6705                                            ? other.getComponentName().getPackageName() : "?"));
6706                        }
6707                    }
6708                }
6709                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6710                    if (r == null) {
6711                        r = new StringBuilder(256);
6712                    } else {
6713                        r.append(' ');
6714                    }
6715                    r.append(p.info.name);
6716                }
6717            }
6718            if (r != null) {
6719                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
6720            }
6721
6722            N = pkg.services.size();
6723            r = null;
6724            for (i=0; i<N; i++) {
6725                PackageParser.Service s = pkg.services.get(i);
6726                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
6727                        s.info.processName, pkg.applicationInfo.uid);
6728                mServices.addService(s);
6729                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6730                    if (r == null) {
6731                        r = new StringBuilder(256);
6732                    } else {
6733                        r.append(' ');
6734                    }
6735                    r.append(s.info.name);
6736                }
6737            }
6738            if (r != null) {
6739                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
6740            }
6741
6742            N = pkg.receivers.size();
6743            r = null;
6744            for (i=0; i<N; i++) {
6745                PackageParser.Activity a = pkg.receivers.get(i);
6746                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6747                        a.info.processName, pkg.applicationInfo.uid);
6748                mReceivers.addActivity(a, "receiver");
6749                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6750                    if (r == null) {
6751                        r = new StringBuilder(256);
6752                    } else {
6753                        r.append(' ');
6754                    }
6755                    r.append(a.info.name);
6756                }
6757            }
6758            if (r != null) {
6759                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
6760            }
6761
6762            N = pkg.activities.size();
6763            r = null;
6764            for (i=0; i<N; i++) {
6765                PackageParser.Activity a = pkg.activities.get(i);
6766                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6767                        a.info.processName, pkg.applicationInfo.uid);
6768                mActivities.addActivity(a, "activity");
6769                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6770                    if (r == null) {
6771                        r = new StringBuilder(256);
6772                    } else {
6773                        r.append(' ');
6774                    }
6775                    r.append(a.info.name);
6776                }
6777            }
6778            if (r != null) {
6779                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
6780            }
6781
6782            N = pkg.permissionGroups.size();
6783            r = null;
6784            for (i=0; i<N; i++) {
6785                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
6786                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
6787                if (cur == null) {
6788                    mPermissionGroups.put(pg.info.name, pg);
6789                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6790                        if (r == null) {
6791                            r = new StringBuilder(256);
6792                        } else {
6793                            r.append(' ');
6794                        }
6795                        r.append(pg.info.name);
6796                    }
6797                } else {
6798                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
6799                            + pg.info.packageName + " ignored: original from "
6800                            + cur.info.packageName);
6801                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6802                        if (r == null) {
6803                            r = new StringBuilder(256);
6804                        } else {
6805                            r.append(' ');
6806                        }
6807                        r.append("DUP:");
6808                        r.append(pg.info.name);
6809                    }
6810                }
6811            }
6812            if (r != null) {
6813                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
6814            }
6815
6816            N = pkg.permissions.size();
6817            r = null;
6818            for (i=0; i<N; i++) {
6819                PackageParser.Permission p = pkg.permissions.get(i);
6820
6821                // Now that permission groups have a special meaning, we ignore permission
6822                // groups for legacy apps to prevent unexpected behavior. In particular,
6823                // permissions for one app being granted to someone just becuase they happen
6824                // to be in a group defined by another app (before this had no implications).
6825                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
6826                    p.group = mPermissionGroups.get(p.info.group);
6827                    // Warn for a permission in an unknown group.
6828                    if (p.info.group != null && p.group == null) {
6829                        Slog.w(TAG, "Permission " + p.info.name + " from package "
6830                                + p.info.packageName + " in an unknown group " + p.info.group);
6831                    }
6832                }
6833
6834                ArrayMap<String, BasePermission> permissionMap =
6835                        p.tree ? mSettings.mPermissionTrees
6836                                : mSettings.mPermissions;
6837                BasePermission bp = permissionMap.get(p.info.name);
6838
6839                // Allow system apps to redefine non-system permissions
6840                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
6841                    final boolean currentOwnerIsSystem = (bp.perm != null
6842                            && isSystemApp(bp.perm.owner));
6843                    if (isSystemApp(p.owner)) {
6844                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
6845                            // It's a built-in permission and no owner, take ownership now
6846                            bp.packageSetting = pkgSetting;
6847                            bp.perm = p;
6848                            bp.uid = pkg.applicationInfo.uid;
6849                            bp.sourcePackage = p.info.packageName;
6850                        } else if (!currentOwnerIsSystem) {
6851                            String msg = "New decl " + p.owner + " of permission  "
6852                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
6853                            reportSettingsProblem(Log.WARN, msg);
6854                            bp = null;
6855                        }
6856                    }
6857                }
6858
6859                if (bp == null) {
6860                    bp = new BasePermission(p.info.name, p.info.packageName,
6861                            BasePermission.TYPE_NORMAL);
6862                    permissionMap.put(p.info.name, bp);
6863                }
6864
6865                if (bp.perm == null) {
6866                    if (bp.sourcePackage == null
6867                            || bp.sourcePackage.equals(p.info.packageName)) {
6868                        BasePermission tree = findPermissionTreeLP(p.info.name);
6869                        if (tree == null
6870                                || tree.sourcePackage.equals(p.info.packageName)) {
6871                            bp.packageSetting = pkgSetting;
6872                            bp.perm = p;
6873                            bp.uid = pkg.applicationInfo.uid;
6874                            bp.sourcePackage = p.info.packageName;
6875                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6876                                if (r == null) {
6877                                    r = new StringBuilder(256);
6878                                } else {
6879                                    r.append(' ');
6880                                }
6881                                r.append(p.info.name);
6882                            }
6883                        } else {
6884                            Slog.w(TAG, "Permission " + p.info.name + " from package "
6885                                    + p.info.packageName + " ignored: base tree "
6886                                    + tree.name + " is from package "
6887                                    + tree.sourcePackage);
6888                        }
6889                    } else {
6890                        Slog.w(TAG, "Permission " + p.info.name + " from package "
6891                                + p.info.packageName + " ignored: original from "
6892                                + bp.sourcePackage);
6893                    }
6894                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6895                    if (r == null) {
6896                        r = new StringBuilder(256);
6897                    } else {
6898                        r.append(' ');
6899                    }
6900                    r.append("DUP:");
6901                    r.append(p.info.name);
6902                }
6903                if (bp.perm == p) {
6904                    bp.protectionLevel = p.info.protectionLevel;
6905                }
6906            }
6907
6908            if (r != null) {
6909                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
6910            }
6911
6912            N = pkg.instrumentation.size();
6913            r = null;
6914            for (i=0; i<N; i++) {
6915                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6916                a.info.packageName = pkg.applicationInfo.packageName;
6917                a.info.sourceDir = pkg.applicationInfo.sourceDir;
6918                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
6919                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
6920                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
6921                a.info.dataDir = pkg.applicationInfo.dataDir;
6922
6923                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
6924                // need other information about the application, like the ABI and what not ?
6925                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
6926                mInstrumentation.put(a.getComponentName(), a);
6927                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6928                    if (r == null) {
6929                        r = new StringBuilder(256);
6930                    } else {
6931                        r.append(' ');
6932                    }
6933                    r.append(a.info.name);
6934                }
6935            }
6936            if (r != null) {
6937                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
6938            }
6939
6940            if (pkg.protectedBroadcasts != null) {
6941                N = pkg.protectedBroadcasts.size();
6942                for (i=0; i<N; i++) {
6943                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
6944                }
6945            }
6946
6947            pkgSetting.setTimeStamp(scanFileTime);
6948
6949            // Create idmap files for pairs of (packages, overlay packages).
6950            // Note: "android", ie framework-res.apk, is handled by native layers.
6951            if (pkg.mOverlayTarget != null) {
6952                // This is an overlay package.
6953                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
6954                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
6955                        mOverlays.put(pkg.mOverlayTarget,
6956                                new ArrayMap<String, PackageParser.Package>());
6957                    }
6958                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
6959                    map.put(pkg.packageName, pkg);
6960                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
6961                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
6962                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6963                                "scanPackageLI failed to createIdmap");
6964                    }
6965                }
6966            } else if (mOverlays.containsKey(pkg.packageName) &&
6967                    !pkg.packageName.equals("android")) {
6968                // This is a regular package, with one or more known overlay packages.
6969                createIdmapsForPackageLI(pkg);
6970            }
6971        }
6972
6973        return pkg;
6974    }
6975
6976    /**
6977     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
6978     * i.e, so that all packages can be run inside a single process if required.
6979     *
6980     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
6981     * this function will either try and make the ABI for all packages in {@code packagesForUser}
6982     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
6983     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
6984     * updating a package that belongs to a shared user.
6985     *
6986     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
6987     * adds unnecessary complexity.
6988     */
6989    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
6990            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
6991        String requiredInstructionSet = null;
6992        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
6993            requiredInstructionSet = VMRuntime.getInstructionSet(
6994                     scannedPackage.applicationInfo.primaryCpuAbi);
6995        }
6996
6997        PackageSetting requirer = null;
6998        for (PackageSetting ps : packagesForUser) {
6999            // If packagesForUser contains scannedPackage, we skip it. This will happen
7000            // when scannedPackage is an update of an existing package. Without this check,
7001            // we will never be able to change the ABI of any package belonging to a shared
7002            // user, even if it's compatible with other packages.
7003            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7004                if (ps.primaryCpuAbiString == null) {
7005                    continue;
7006                }
7007
7008                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7009                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7010                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7011                    // this but there's not much we can do.
7012                    String errorMessage = "Instruction set mismatch, "
7013                            + ((requirer == null) ? "[caller]" : requirer)
7014                            + " requires " + requiredInstructionSet + " whereas " + ps
7015                            + " requires " + instructionSet;
7016                    Slog.w(TAG, errorMessage);
7017                }
7018
7019                if (requiredInstructionSet == null) {
7020                    requiredInstructionSet = instructionSet;
7021                    requirer = ps;
7022                }
7023            }
7024        }
7025
7026        if (requiredInstructionSet != null) {
7027            String adjustedAbi;
7028            if (requirer != null) {
7029                // requirer != null implies that either scannedPackage was null or that scannedPackage
7030                // did not require an ABI, in which case we have to adjust scannedPackage to match
7031                // the ABI of the set (which is the same as requirer's ABI)
7032                adjustedAbi = requirer.primaryCpuAbiString;
7033                if (scannedPackage != null) {
7034                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7035                }
7036            } else {
7037                // requirer == null implies that we're updating all ABIs in the set to
7038                // match scannedPackage.
7039                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7040            }
7041
7042            for (PackageSetting ps : packagesForUser) {
7043                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7044                    if (ps.primaryCpuAbiString != null) {
7045                        continue;
7046                    }
7047
7048                    ps.primaryCpuAbiString = adjustedAbi;
7049                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7050                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7051                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7052
7053                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
7054                                null /* instruction sets */, forceDexOpt, deferDexOpt, true);
7055                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7056                            ps.primaryCpuAbiString = null;
7057                            ps.pkg.applicationInfo.primaryCpuAbi = null;
7058                            return;
7059                        } else {
7060                            mInstaller.rmdex(ps.codePathString,
7061                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
7062                        }
7063                    }
7064                }
7065            }
7066        }
7067    }
7068
7069    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7070        synchronized (mPackages) {
7071            mResolverReplaced = true;
7072            // Set up information for custom user intent resolution activity.
7073            mResolveActivity.applicationInfo = pkg.applicationInfo;
7074            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7075            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7076            mResolveActivity.processName = pkg.applicationInfo.packageName;
7077            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7078            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7079                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7080            mResolveActivity.theme = 0;
7081            mResolveActivity.exported = true;
7082            mResolveActivity.enabled = true;
7083            mResolveInfo.activityInfo = mResolveActivity;
7084            mResolveInfo.priority = 0;
7085            mResolveInfo.preferredOrder = 0;
7086            mResolveInfo.match = 0;
7087            mResolveComponentName = mCustomResolverComponentName;
7088            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7089                    mResolveComponentName);
7090        }
7091    }
7092
7093    private static String calculateBundledApkRoot(final String codePathString) {
7094        final File codePath = new File(codePathString);
7095        final File codeRoot;
7096        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7097            codeRoot = Environment.getRootDirectory();
7098        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7099            codeRoot = Environment.getOemDirectory();
7100        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7101            codeRoot = Environment.getVendorDirectory();
7102        } else {
7103            // Unrecognized code path; take its top real segment as the apk root:
7104            // e.g. /something/app/blah.apk => /something
7105            try {
7106                File f = codePath.getCanonicalFile();
7107                File parent = f.getParentFile();    // non-null because codePath is a file
7108                File tmp;
7109                while ((tmp = parent.getParentFile()) != null) {
7110                    f = parent;
7111                    parent = tmp;
7112                }
7113                codeRoot = f;
7114                Slog.w(TAG, "Unrecognized code path "
7115                        + codePath + " - using " + codeRoot);
7116            } catch (IOException e) {
7117                // Can't canonicalize the code path -- shenanigans?
7118                Slog.w(TAG, "Can't canonicalize code path " + codePath);
7119                return Environment.getRootDirectory().getPath();
7120            }
7121        }
7122        return codeRoot.getPath();
7123    }
7124
7125    /**
7126     * Derive and set the location of native libraries for the given package,
7127     * which varies depending on where and how the package was installed.
7128     */
7129    private void setNativeLibraryPaths(PackageParser.Package pkg) {
7130        final ApplicationInfo info = pkg.applicationInfo;
7131        final String codePath = pkg.codePath;
7132        final File codeFile = new File(codePath);
7133        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7134        final boolean asecApp = info.isForwardLocked() || isExternal(info);
7135
7136        info.nativeLibraryRootDir = null;
7137        info.nativeLibraryRootRequiresIsa = false;
7138        info.nativeLibraryDir = null;
7139        info.secondaryNativeLibraryDir = null;
7140
7141        if (isApkFile(codeFile)) {
7142            // Monolithic install
7143            if (bundledApp) {
7144                // If "/system/lib64/apkname" exists, assume that is the per-package
7145                // native library directory to use; otherwise use "/system/lib/apkname".
7146                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
7147                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
7148                        getPrimaryInstructionSet(info));
7149
7150                // This is a bundled system app so choose the path based on the ABI.
7151                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
7152                // is just the default path.
7153                final String apkName = deriveCodePathName(codePath);
7154                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
7155                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
7156                        apkName).getAbsolutePath();
7157
7158                if (info.secondaryCpuAbi != null) {
7159                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7160                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7161                            secondaryLibDir, apkName).getAbsolutePath();
7162                }
7163            } else if (asecApp) {
7164                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
7165                        .getAbsolutePath();
7166            } else {
7167                final String apkName = deriveCodePathName(codePath);
7168                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
7169                        .getAbsolutePath();
7170            }
7171
7172            info.nativeLibraryRootRequiresIsa = false;
7173            info.nativeLibraryDir = info.nativeLibraryRootDir;
7174        } else {
7175            // Cluster install
7176            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7177            info.nativeLibraryRootRequiresIsa = true;
7178
7179            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7180                    getPrimaryInstructionSet(info)).getAbsolutePath();
7181
7182            if (info.secondaryCpuAbi != null) {
7183                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7184                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7185            }
7186        }
7187    }
7188
7189    /**
7190     * Calculate the abis and roots for a bundled app. These can uniquely
7191     * be determined from the contents of the system partition, i.e whether
7192     * it contains 64 or 32 bit shared libraries etc. We do not validate any
7193     * of this information, and instead assume that the system was built
7194     * sensibly.
7195     */
7196    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
7197                                           PackageSetting pkgSetting) {
7198        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
7199
7200        // If "/system/lib64/apkname" exists, assume that is the per-package
7201        // native library directory to use; otherwise use "/system/lib/apkname".
7202        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
7203        setBundledAppAbi(pkg, apkRoot, apkName);
7204        // pkgSetting might be null during rescan following uninstall of updates
7205        // to a bundled app, so accommodate that possibility.  The settings in
7206        // that case will be established later from the parsed package.
7207        //
7208        // If the settings aren't null, sync them up with what we've just derived.
7209        // note that apkRoot isn't stored in the package settings.
7210        if (pkgSetting != null) {
7211            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7212            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7213        }
7214    }
7215
7216    /**
7217     * Deduces the ABI of a bundled app and sets the relevant fields on the
7218     * parsed pkg object.
7219     *
7220     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
7221     *        under which system libraries are installed.
7222     * @param apkName the name of the installed package.
7223     */
7224    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7225        final File codeFile = new File(pkg.codePath);
7226
7227        final boolean has64BitLibs;
7228        final boolean has32BitLibs;
7229        if (isApkFile(codeFile)) {
7230            // Monolithic install
7231            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7232            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7233        } else {
7234            // Cluster install
7235            final File rootDir = new File(codeFile, LIB_DIR_NAME);
7236            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7237                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7238                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7239                has64BitLibs = (new File(rootDir, isa)).exists();
7240            } else {
7241                has64BitLibs = false;
7242            }
7243            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7244                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7245                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7246                has32BitLibs = (new File(rootDir, isa)).exists();
7247            } else {
7248                has32BitLibs = false;
7249            }
7250        }
7251
7252        if (has64BitLibs && !has32BitLibs) {
7253            // The package has 64 bit libs, but not 32 bit libs. Its primary
7254            // ABI should be 64 bit. We can safely assume here that the bundled
7255            // native libraries correspond to the most preferred ABI in the list.
7256
7257            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7258            pkg.applicationInfo.secondaryCpuAbi = null;
7259        } else if (has32BitLibs && !has64BitLibs) {
7260            // The package has 32 bit libs but not 64 bit libs. Its primary
7261            // ABI should be 32 bit.
7262
7263            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7264            pkg.applicationInfo.secondaryCpuAbi = null;
7265        } else if (has32BitLibs && has64BitLibs) {
7266            // The application has both 64 and 32 bit bundled libraries. We check
7267            // here that the app declares multiArch support, and warn if it doesn't.
7268            //
7269            // We will be lenient here and record both ABIs. The primary will be the
7270            // ABI that's higher on the list, i.e, a device that's configured to prefer
7271            // 64 bit apps will see a 64 bit primary ABI,
7272
7273            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
7274                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
7275            }
7276
7277            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
7278                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7279                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7280            } else {
7281                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7282                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7283            }
7284        } else {
7285            pkg.applicationInfo.primaryCpuAbi = null;
7286            pkg.applicationInfo.secondaryCpuAbi = null;
7287        }
7288    }
7289
7290    private void killApplication(String pkgName, int appId, String reason) {
7291        // Request the ActivityManager to kill the process(only for existing packages)
7292        // so that we do not end up in a confused state while the user is still using the older
7293        // version of the application while the new one gets installed.
7294        IActivityManager am = ActivityManagerNative.getDefault();
7295        if (am != null) {
7296            try {
7297                am.killApplicationWithAppId(pkgName, appId, reason);
7298            } catch (RemoteException e) {
7299            }
7300        }
7301    }
7302
7303    void removePackageLI(PackageSetting ps, boolean chatty) {
7304        if (DEBUG_INSTALL) {
7305            if (chatty)
7306                Log.d(TAG, "Removing package " + ps.name);
7307        }
7308
7309        // writer
7310        synchronized (mPackages) {
7311            mPackages.remove(ps.name);
7312            final PackageParser.Package pkg = ps.pkg;
7313            if (pkg != null) {
7314                cleanPackageDataStructuresLILPw(pkg, chatty);
7315            }
7316        }
7317    }
7318
7319    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
7320        if (DEBUG_INSTALL) {
7321            if (chatty)
7322                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
7323        }
7324
7325        // writer
7326        synchronized (mPackages) {
7327            mPackages.remove(pkg.applicationInfo.packageName);
7328            cleanPackageDataStructuresLILPw(pkg, chatty);
7329        }
7330    }
7331
7332    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
7333        int N = pkg.providers.size();
7334        StringBuilder r = null;
7335        int i;
7336        for (i=0; i<N; i++) {
7337            PackageParser.Provider p = pkg.providers.get(i);
7338            mProviders.removeProvider(p);
7339            if (p.info.authority == null) {
7340
7341                /* There was another ContentProvider with this authority when
7342                 * this app was installed so this authority is null,
7343                 * Ignore it as we don't have to unregister the provider.
7344                 */
7345                continue;
7346            }
7347            String names[] = p.info.authority.split(";");
7348            for (int j = 0; j < names.length; j++) {
7349                if (mProvidersByAuthority.get(names[j]) == p) {
7350                    mProvidersByAuthority.remove(names[j]);
7351                    if (DEBUG_REMOVE) {
7352                        if (chatty)
7353                            Log.d(TAG, "Unregistered content provider: " + names[j]
7354                                    + ", className = " + p.info.name + ", isSyncable = "
7355                                    + p.info.isSyncable);
7356                    }
7357                }
7358            }
7359            if (DEBUG_REMOVE && chatty) {
7360                if (r == null) {
7361                    r = new StringBuilder(256);
7362                } else {
7363                    r.append(' ');
7364                }
7365                r.append(p.info.name);
7366            }
7367        }
7368        if (r != null) {
7369            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
7370        }
7371
7372        N = pkg.services.size();
7373        r = null;
7374        for (i=0; i<N; i++) {
7375            PackageParser.Service s = pkg.services.get(i);
7376            mServices.removeService(s);
7377            if (chatty) {
7378                if (r == null) {
7379                    r = new StringBuilder(256);
7380                } else {
7381                    r.append(' ');
7382                }
7383                r.append(s.info.name);
7384            }
7385        }
7386        if (r != null) {
7387            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
7388        }
7389
7390        N = pkg.receivers.size();
7391        r = null;
7392        for (i=0; i<N; i++) {
7393            PackageParser.Activity a = pkg.receivers.get(i);
7394            mReceivers.removeActivity(a, "receiver");
7395            if (DEBUG_REMOVE && chatty) {
7396                if (r == null) {
7397                    r = new StringBuilder(256);
7398                } else {
7399                    r.append(' ');
7400                }
7401                r.append(a.info.name);
7402            }
7403        }
7404        if (r != null) {
7405            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
7406        }
7407
7408        N = pkg.activities.size();
7409        r = null;
7410        for (i=0; i<N; i++) {
7411            PackageParser.Activity a = pkg.activities.get(i);
7412            mActivities.removeActivity(a, "activity");
7413            if (DEBUG_REMOVE && chatty) {
7414                if (r == null) {
7415                    r = new StringBuilder(256);
7416                } else {
7417                    r.append(' ');
7418                }
7419                r.append(a.info.name);
7420            }
7421        }
7422        if (r != null) {
7423            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
7424        }
7425
7426        N = pkg.permissions.size();
7427        r = null;
7428        for (i=0; i<N; i++) {
7429            PackageParser.Permission p = pkg.permissions.get(i);
7430            BasePermission bp = mSettings.mPermissions.get(p.info.name);
7431            if (bp == null) {
7432                bp = mSettings.mPermissionTrees.get(p.info.name);
7433            }
7434            if (bp != null && bp.perm == p) {
7435                bp.perm = null;
7436                if (DEBUG_REMOVE && chatty) {
7437                    if (r == null) {
7438                        r = new StringBuilder(256);
7439                    } else {
7440                        r.append(' ');
7441                    }
7442                    r.append(p.info.name);
7443                }
7444            }
7445            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7446                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
7447                if (appOpPerms != null) {
7448                    appOpPerms.remove(pkg.packageName);
7449                }
7450            }
7451        }
7452        if (r != null) {
7453            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
7454        }
7455
7456        N = pkg.requestedPermissions.size();
7457        r = null;
7458        for (i=0; i<N; i++) {
7459            String perm = pkg.requestedPermissions.get(i);
7460            BasePermission bp = mSettings.mPermissions.get(perm);
7461            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7462                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
7463                if (appOpPerms != null) {
7464                    appOpPerms.remove(pkg.packageName);
7465                    if (appOpPerms.isEmpty()) {
7466                        mAppOpPermissionPackages.remove(perm);
7467                    }
7468                }
7469            }
7470        }
7471        if (r != null) {
7472            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
7473        }
7474
7475        N = pkg.instrumentation.size();
7476        r = null;
7477        for (i=0; i<N; i++) {
7478            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7479            mInstrumentation.remove(a.getComponentName());
7480            if (DEBUG_REMOVE && chatty) {
7481                if (r == null) {
7482                    r = new StringBuilder(256);
7483                } else {
7484                    r.append(' ');
7485                }
7486                r.append(a.info.name);
7487            }
7488        }
7489        if (r != null) {
7490            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
7491        }
7492
7493        r = null;
7494        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7495            // Only system apps can hold shared libraries.
7496            if (pkg.libraryNames != null) {
7497                for (i=0; i<pkg.libraryNames.size(); i++) {
7498                    String name = pkg.libraryNames.get(i);
7499                    SharedLibraryEntry cur = mSharedLibraries.get(name);
7500                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
7501                        mSharedLibraries.remove(name);
7502                        if (DEBUG_REMOVE && chatty) {
7503                            if (r == null) {
7504                                r = new StringBuilder(256);
7505                            } else {
7506                                r.append(' ');
7507                            }
7508                            r.append(name);
7509                        }
7510                    }
7511                }
7512            }
7513        }
7514        if (r != null) {
7515            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
7516        }
7517    }
7518
7519    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
7520        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
7521            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
7522                return true;
7523            }
7524        }
7525        return false;
7526    }
7527
7528    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
7529    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
7530    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
7531
7532    private void updatePermissionsLPw(String changingPkg,
7533            PackageParser.Package pkgInfo, int flags) {
7534        // Make sure there are no dangling permission trees.
7535        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
7536        while (it.hasNext()) {
7537            final BasePermission bp = it.next();
7538            if (bp.packageSetting == null) {
7539                // We may not yet have parsed the package, so just see if
7540                // we still know about its settings.
7541                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
7542            }
7543            if (bp.packageSetting == null) {
7544                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
7545                        + " from package " + bp.sourcePackage);
7546                it.remove();
7547            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
7548                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
7549                    Slog.i(TAG, "Removing old permission tree: " + bp.name
7550                            + " from package " + bp.sourcePackage);
7551                    flags |= UPDATE_PERMISSIONS_ALL;
7552                    it.remove();
7553                }
7554            }
7555        }
7556
7557        // Make sure all dynamic permissions have been assigned to a package,
7558        // and make sure there are no dangling permissions.
7559        it = mSettings.mPermissions.values().iterator();
7560        while (it.hasNext()) {
7561            final BasePermission bp = it.next();
7562            if (bp.type == BasePermission.TYPE_DYNAMIC) {
7563                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
7564                        + bp.name + " pkg=" + bp.sourcePackage
7565                        + " info=" + bp.pendingInfo);
7566                if (bp.packageSetting == null && bp.pendingInfo != null) {
7567                    final BasePermission tree = findPermissionTreeLP(bp.name);
7568                    if (tree != null && tree.perm != null) {
7569                        bp.packageSetting = tree.packageSetting;
7570                        bp.perm = new PackageParser.Permission(tree.perm.owner,
7571                                new PermissionInfo(bp.pendingInfo));
7572                        bp.perm.info.packageName = tree.perm.info.packageName;
7573                        bp.perm.info.name = bp.name;
7574                        bp.uid = tree.uid;
7575                    }
7576                }
7577            }
7578            if (bp.packageSetting == null) {
7579                // We may not yet have parsed the package, so just see if
7580                // we still know about its settings.
7581                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
7582            }
7583            if (bp.packageSetting == null) {
7584                Slog.w(TAG, "Removing dangling permission: " + bp.name
7585                        + " from package " + bp.sourcePackage);
7586                it.remove();
7587            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
7588                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
7589                    Slog.i(TAG, "Removing old permission: " + bp.name
7590                            + " from package " + bp.sourcePackage);
7591                    flags |= UPDATE_PERMISSIONS_ALL;
7592                    it.remove();
7593                }
7594            }
7595        }
7596
7597        // Now update the permissions for all packages, in particular
7598        // replace the granted permissions of the system packages.
7599        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
7600            for (PackageParser.Package pkg : mPackages.values()) {
7601                if (pkg != pkgInfo) {
7602                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
7603                            changingPkg);
7604                }
7605            }
7606        }
7607
7608        if (pkgInfo != null) {
7609            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
7610        }
7611    }
7612
7613    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
7614            String packageOfInterest) {
7615        // IMPORTANT: There are two types of permissions: install and runtime.
7616        // Install time permissions are granted when the app is installed to
7617        // all device users and users added in the future. Runtime permissions
7618        // are granted at runtime explicitly to specific users. Normal and signature
7619        // protected permissions are install time permissions. Dangerous permissions
7620        // are install permissions if the app's target SDK is Lollipop MR1 or older,
7621        // otherwise they are runtime permissions. This function does not manage
7622        // runtime permissions except for the case an app targeting Lollipop MR1
7623        // being upgraded to target a newer SDK, in which case dangerous permissions
7624        // are transformed from install time to runtime ones.
7625
7626        final PackageSetting ps = (PackageSetting) pkg.mExtras;
7627        if (ps == null) {
7628            return;
7629        }
7630
7631        PermissionsState permissionsState = ps.getPermissionsState();
7632        PermissionsState origPermissions = permissionsState;
7633
7634        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
7635
7636        int[] upgradeUserIds = EMPTY_INT_ARRAY;
7637        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
7638
7639        boolean changedInstallPermission = false;
7640
7641        if (replace) {
7642            ps.installPermissionsFixed = false;
7643            if (!ps.isSharedUser()) {
7644                origPermissions = new PermissionsState(permissionsState);
7645                permissionsState.reset();
7646            }
7647        }
7648
7649        permissionsState.setGlobalGids(mGlobalGids);
7650
7651        final int N = pkg.requestedPermissions.size();
7652        for (int i=0; i<N; i++) {
7653            final String name = pkg.requestedPermissions.get(i);
7654            final BasePermission bp = mSettings.mPermissions.get(name);
7655
7656            if (DEBUG_INSTALL) {
7657                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
7658            }
7659
7660            if (bp == null || bp.packageSetting == null) {
7661                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7662                    Slog.w(TAG, "Unknown permission " + name
7663                            + " in package " + pkg.packageName);
7664                }
7665                continue;
7666            }
7667
7668            final String perm = bp.name;
7669            boolean allowedSig = false;
7670            int grant = GRANT_DENIED;
7671
7672            // Keep track of app op permissions.
7673            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7674                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
7675                if (pkgs == null) {
7676                    pkgs = new ArraySet<>();
7677                    mAppOpPermissionPackages.put(bp.name, pkgs);
7678                }
7679                pkgs.add(pkg.packageName);
7680            }
7681
7682            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
7683            switch (level) {
7684                case PermissionInfo.PROTECTION_NORMAL: {
7685                    // For all apps normal permissions are install time ones.
7686                    grant = GRANT_INSTALL;
7687                } break;
7688
7689                case PermissionInfo.PROTECTION_DANGEROUS: {
7690                    if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
7691                        // For legacy apps dangerous permissions are install time ones.
7692                        grant = GRANT_INSTALL;
7693                    } else if (ps.isSystem()) {
7694                        final int[] updatedUserIds = ps.getPermissionsUpdatedForUserIds();
7695                        if (origPermissions.hasInstallPermission(bp.name)) {
7696                            // If a system app had an install permission, then the app was
7697                            // upgraded and we grant the permissions as runtime to all users.
7698                            grant = GRANT_UPGRADE;
7699                            upgradeUserIds = currentUserIds;
7700                        } else if (!Arrays.equals(updatedUserIds, currentUserIds)) {
7701                            // If users changed since the last permissions update for a
7702                            // system app, we grant the permission as runtime to the new users.
7703                            grant = GRANT_UPGRADE;
7704                            upgradeUserIds = currentUserIds;
7705                            for (int userId : updatedUserIds) {
7706                                upgradeUserIds = ArrayUtils.removeInt(upgradeUserIds, userId);
7707                            }
7708                        } else {
7709                            // Otherwise, we grant the permission as runtime if the app
7710                            // already had it, i.e. we preserve runtime permissions.
7711                            grant = GRANT_RUNTIME;
7712                        }
7713                    } else if (origPermissions.hasInstallPermission(bp.name)) {
7714                        // For legacy apps that became modern, install becomes runtime.
7715                        grant = GRANT_UPGRADE;
7716                        upgradeUserIds = currentUserIds;
7717                    } else if (replace) {
7718                        // For upgraded modern apps keep runtime permissions unchanged.
7719                        grant = GRANT_RUNTIME;
7720                    }
7721                } break;
7722
7723                case PermissionInfo.PROTECTION_SIGNATURE: {
7724                    // For all apps signature permissions are install time ones.
7725                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
7726                    if (allowedSig) {
7727                        grant = GRANT_INSTALL;
7728                    }
7729                } break;
7730            }
7731
7732            if (DEBUG_INSTALL) {
7733                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
7734            }
7735
7736            if (grant != GRANT_DENIED) {
7737                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
7738                    // If this is an existing, non-system package, then
7739                    // we can't add any new permissions to it.
7740                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
7741                        // Except...  if this is a permission that was added
7742                        // to the platform (note: need to only do this when
7743                        // updating the platform).
7744                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
7745                            grant = GRANT_DENIED;
7746                        }
7747                    }
7748                }
7749
7750                switch (grant) {
7751                    case GRANT_INSTALL: {
7752                        // Grant an install permission.
7753                        if (permissionsState.grantInstallPermission(bp) !=
7754                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
7755                            changedInstallPermission = true;
7756                        }
7757                    } break;
7758
7759                    case GRANT_RUNTIME: {
7760                        // Grant previously granted runtime permissions.
7761                        for (int userId : UserManagerService.getInstance().getUserIds()) {
7762                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
7763                                PermissionState permissionState = origPermissions
7764                                        .getRuntimePermissionState(bp.name, userId);
7765                                final int flags = permissionState.getFlags();
7766                                if (permissionsState.grantRuntimePermission(bp, userId) ==
7767                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
7768                                    // If we cannot put the permission as it was, we have to write.
7769                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
7770                                            changedRuntimePermissionUserIds, userId);
7771                                } else {
7772                                    // System components not only get the permissions but
7773                                    // they are also fixed, so nothing can change that.
7774                                    final int newFlags = !isSystemComponentOrPersistentPrivApp(pkg)
7775                                            ? flags
7776                                            : flags | PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
7777                                    // Propagate the permission flags.
7778                                    permissionsState.updatePermissionFlags(bp, userId,
7779                                            newFlags, newFlags);
7780                                }
7781                            }
7782                        }
7783                    } break;
7784
7785                    case GRANT_UPGRADE: {
7786                        // Grant runtime permissions for a previously held install permission.
7787                        PermissionState permissionState = origPermissions
7788                                .getInstallPermissionState(bp.name);
7789                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
7790
7791                        origPermissions.revokeInstallPermission(bp);
7792                        // We will be transferring the permission flags, so clear them.
7793                        origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
7794                                PackageManager.MASK_PERMISSION_FLAGS, 0);
7795
7796                        // If the permission is not to be promoted to runtime we ignore it and
7797                        // also its other flags as they are not applicable to install permissions.
7798                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
7799                            for (int userId : upgradeUserIds) {
7800                                if (permissionsState.grantRuntimePermission(bp, userId) !=
7801                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
7802                                    // System components not only get the permissions but
7803                                    // they are also fixed so nothing can change that.
7804                                    final int newFlags = !isSystemComponentOrPersistentPrivApp(pkg)
7805                                            ? flags
7806                                            : flags | PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
7807                                    // Transfer the permission flags.
7808                                    permissionsState.updatePermissionFlags(bp, userId,
7809                                            newFlags, newFlags);
7810                                    // If we granted the permission, we have to write.
7811                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
7812                                            changedRuntimePermissionUserIds, userId);
7813                                }
7814                            }
7815                        }
7816                    } break;
7817
7818                    default: {
7819                        if (packageOfInterest == null
7820                                || packageOfInterest.equals(pkg.packageName)) {
7821                            Slog.w(TAG, "Not granting permission " + perm
7822                                    + " to package " + pkg.packageName
7823                                    + " because it was previously installed without");
7824                        }
7825                    } break;
7826                }
7827            } else {
7828                if (permissionsState.revokeInstallPermission(bp) !=
7829                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
7830                    // Also drop the permission flags.
7831                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
7832                            PackageManager.MASK_PERMISSION_FLAGS, 0);
7833                    changedInstallPermission = true;
7834                    Slog.i(TAG, "Un-granting permission " + perm
7835                            + " from package " + pkg.packageName
7836                            + " (protectionLevel=" + bp.protectionLevel
7837                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
7838                            + ")");
7839                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
7840                    // Don't print warning for app op permissions, since it is fine for them
7841                    // not to be granted, there is a UI for the user to decide.
7842                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7843                        Slog.w(TAG, "Not granting permission " + perm
7844                                + " to package " + pkg.packageName
7845                                + " (protectionLevel=" + bp.protectionLevel
7846                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
7847                                + ")");
7848                    }
7849                }
7850            }
7851        }
7852
7853        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
7854                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
7855            // This is the first that we have heard about this package, so the
7856            // permissions we have now selected are fixed until explicitly
7857            // changed.
7858            ps.installPermissionsFixed = true;
7859        }
7860
7861        ps.setPermissionsUpdatedForUserIds(currentUserIds);
7862
7863        // Persist the runtime permissions state for users with changes.
7864        for (int userId : changedRuntimePermissionUserIds) {
7865            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
7866        }
7867    }
7868
7869    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
7870        boolean allowed = false;
7871        final int NP = PackageParser.NEW_PERMISSIONS.length;
7872        for (int ip=0; ip<NP; ip++) {
7873            final PackageParser.NewPermissionInfo npi
7874                    = PackageParser.NEW_PERMISSIONS[ip];
7875            if (npi.name.equals(perm)
7876                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
7877                allowed = true;
7878                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
7879                        + pkg.packageName);
7880                break;
7881            }
7882        }
7883        return allowed;
7884    }
7885
7886    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
7887            BasePermission bp, PermissionsState origPermissions) {
7888        boolean allowed;
7889        allowed = (compareSignatures(
7890                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
7891                        == PackageManager.SIGNATURE_MATCH)
7892                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
7893                        == PackageManager.SIGNATURE_MATCH);
7894        if (!allowed && (bp.protectionLevel
7895                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
7896            if (isSystemApp(pkg)) {
7897                // For updated system applications, a system permission
7898                // is granted only if it had been defined by the original application.
7899                if (pkg.isUpdatedSystemApp()) {
7900                    final PackageSetting sysPs = mSettings
7901                            .getDisabledSystemPkgLPr(pkg.packageName);
7902                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
7903                        // If the original was granted this permission, we take
7904                        // that grant decision as read and propagate it to the
7905                        // update.
7906                        if (sysPs.isPrivileged()) {
7907                            allowed = true;
7908                        }
7909                    } else {
7910                        // The system apk may have been updated with an older
7911                        // version of the one on the data partition, but which
7912                        // granted a new system permission that it didn't have
7913                        // before.  In this case we do want to allow the app to
7914                        // now get the new permission if the ancestral apk is
7915                        // privileged to get it.
7916                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
7917                            for (int j=0;
7918                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
7919                                if (perm.equals(
7920                                        sysPs.pkg.requestedPermissions.get(j))) {
7921                                    allowed = true;
7922                                    break;
7923                                }
7924                            }
7925                        }
7926                    }
7927                } else {
7928                    allowed = isPrivilegedApp(pkg);
7929                }
7930            }
7931        }
7932        if (!allowed && (bp.protectionLevel
7933                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
7934            // For development permissions, a development permission
7935            // is granted only if it was already granted.
7936            allowed = origPermissions.hasInstallPermission(perm);
7937        }
7938        return allowed;
7939    }
7940
7941    final class ActivityIntentResolver
7942            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
7943        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7944                boolean defaultOnly, int userId) {
7945            if (!sUserManager.exists(userId)) return null;
7946            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7947            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7948        }
7949
7950        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7951                int userId) {
7952            if (!sUserManager.exists(userId)) return null;
7953            mFlags = flags;
7954            return super.queryIntent(intent, resolvedType,
7955                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7956        }
7957
7958        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7959                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
7960            if (!sUserManager.exists(userId)) return null;
7961            if (packageActivities == null) {
7962                return null;
7963            }
7964            mFlags = flags;
7965            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7966            final int N = packageActivities.size();
7967            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
7968                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
7969
7970            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
7971            for (int i = 0; i < N; ++i) {
7972                intentFilters = packageActivities.get(i).intents;
7973                if (intentFilters != null && intentFilters.size() > 0) {
7974                    PackageParser.ActivityIntentInfo[] array =
7975                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
7976                    intentFilters.toArray(array);
7977                    listCut.add(array);
7978                }
7979            }
7980            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7981        }
7982
7983        public final void addActivity(PackageParser.Activity a, String type) {
7984            final boolean systemApp = a.info.applicationInfo.isSystemApp();
7985            mActivities.put(a.getComponentName(), a);
7986            if (DEBUG_SHOW_INFO)
7987                Log.v(
7988                TAG, "  " + type + " " +
7989                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
7990            if (DEBUG_SHOW_INFO)
7991                Log.v(TAG, "    Class=" + a.info.name);
7992            final int NI = a.intents.size();
7993            for (int j=0; j<NI; j++) {
7994                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7995                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
7996                    intent.setPriority(0);
7997                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
7998                            + a.className + " with priority > 0, forcing to 0");
7999                }
8000                if (DEBUG_SHOW_INFO) {
8001                    Log.v(TAG, "    IntentFilter:");
8002                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8003                }
8004                if (!intent.debugCheck()) {
8005                    Log.w(TAG, "==> For Activity " + a.info.name);
8006                }
8007                addFilter(intent);
8008            }
8009        }
8010
8011        public final void removeActivity(PackageParser.Activity a, String type) {
8012            mActivities.remove(a.getComponentName());
8013            if (DEBUG_SHOW_INFO) {
8014                Log.v(TAG, "  " + type + " "
8015                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
8016                                : a.info.name) + ":");
8017                Log.v(TAG, "    Class=" + a.info.name);
8018            }
8019            final int NI = a.intents.size();
8020            for (int j=0; j<NI; j++) {
8021                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8022                if (DEBUG_SHOW_INFO) {
8023                    Log.v(TAG, "    IntentFilter:");
8024                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8025                }
8026                removeFilter(intent);
8027            }
8028        }
8029
8030        @Override
8031        protected boolean allowFilterResult(
8032                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
8033            ActivityInfo filterAi = filter.activity.info;
8034            for (int i=dest.size()-1; i>=0; i--) {
8035                ActivityInfo destAi = dest.get(i).activityInfo;
8036                if (destAi.name == filterAi.name
8037                        && destAi.packageName == filterAi.packageName) {
8038                    return false;
8039                }
8040            }
8041            return true;
8042        }
8043
8044        @Override
8045        protected ActivityIntentInfo[] newArray(int size) {
8046            return new ActivityIntentInfo[size];
8047        }
8048
8049        @Override
8050        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
8051            if (!sUserManager.exists(userId)) return true;
8052            PackageParser.Package p = filter.activity.owner;
8053            if (p != null) {
8054                PackageSetting ps = (PackageSetting)p.mExtras;
8055                if (ps != null) {
8056                    // System apps are never considered stopped for purposes of
8057                    // filtering, because there may be no way for the user to
8058                    // actually re-launch them.
8059                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
8060                            && ps.getStopped(userId);
8061                }
8062            }
8063            return false;
8064        }
8065
8066        @Override
8067        protected boolean isPackageForFilter(String packageName,
8068                PackageParser.ActivityIntentInfo info) {
8069            return packageName.equals(info.activity.owner.packageName);
8070        }
8071
8072        @Override
8073        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
8074                int match, int userId) {
8075            if (!sUserManager.exists(userId)) return null;
8076            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
8077                return null;
8078            }
8079            final PackageParser.Activity activity = info.activity;
8080            if (mSafeMode && (activity.info.applicationInfo.flags
8081                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8082                return null;
8083            }
8084            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
8085            if (ps == null) {
8086                return null;
8087            }
8088            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
8089                    ps.readUserState(userId), userId);
8090            if (ai == null) {
8091                return null;
8092            }
8093            final ResolveInfo res = new ResolveInfo();
8094            res.activityInfo = ai;
8095            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8096                res.filter = info;
8097            }
8098            if (info != null) {
8099                res.handleAllWebDataURI = info.handleAllWebDataURI();
8100            }
8101            res.priority = info.getPriority();
8102            res.preferredOrder = activity.owner.mPreferredOrder;
8103            //System.out.println("Result: " + res.activityInfo.className +
8104            //                   " = " + res.priority);
8105            res.match = match;
8106            res.isDefault = info.hasDefault;
8107            res.labelRes = info.labelRes;
8108            res.nonLocalizedLabel = info.nonLocalizedLabel;
8109            if (userNeedsBadging(userId)) {
8110                res.noResourceId = true;
8111            } else {
8112                res.icon = info.icon;
8113            }
8114            res.system = res.activityInfo.applicationInfo.isSystemApp();
8115            return res;
8116        }
8117
8118        @Override
8119        protected void sortResults(List<ResolveInfo> results) {
8120            Collections.sort(results, mResolvePrioritySorter);
8121        }
8122
8123        @Override
8124        protected void dumpFilter(PrintWriter out, String prefix,
8125                PackageParser.ActivityIntentInfo filter) {
8126            out.print(prefix); out.print(
8127                    Integer.toHexString(System.identityHashCode(filter.activity)));
8128                    out.print(' ');
8129                    filter.activity.printComponentShortName(out);
8130                    out.print(" filter ");
8131                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8132        }
8133
8134        @Override
8135        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
8136            return filter.activity;
8137        }
8138
8139        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8140            PackageParser.Activity activity = (PackageParser.Activity)label;
8141            out.print(prefix); out.print(
8142                    Integer.toHexString(System.identityHashCode(activity)));
8143                    out.print(' ');
8144                    activity.printComponentShortName(out);
8145            if (count > 1) {
8146                out.print(" ("); out.print(count); out.print(" filters)");
8147            }
8148            out.println();
8149        }
8150
8151//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8152//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8153//            final List<ResolveInfo> retList = Lists.newArrayList();
8154//            while (i.hasNext()) {
8155//                final ResolveInfo resolveInfo = i.next();
8156//                if (isEnabledLP(resolveInfo.activityInfo)) {
8157//                    retList.add(resolveInfo);
8158//                }
8159//            }
8160//            return retList;
8161//        }
8162
8163        // Keys are String (activity class name), values are Activity.
8164        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
8165                = new ArrayMap<ComponentName, PackageParser.Activity>();
8166        private int mFlags;
8167    }
8168
8169    private final class ServiceIntentResolver
8170            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
8171        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8172                boolean defaultOnly, int userId) {
8173            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8174            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8175        }
8176
8177        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8178                int userId) {
8179            if (!sUserManager.exists(userId)) return null;
8180            mFlags = flags;
8181            return super.queryIntent(intent, resolvedType,
8182                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8183        }
8184
8185        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8186                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
8187            if (!sUserManager.exists(userId)) return null;
8188            if (packageServices == null) {
8189                return null;
8190            }
8191            mFlags = flags;
8192            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8193            final int N = packageServices.size();
8194            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
8195                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
8196
8197            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
8198            for (int i = 0; i < N; ++i) {
8199                intentFilters = packageServices.get(i).intents;
8200                if (intentFilters != null && intentFilters.size() > 0) {
8201                    PackageParser.ServiceIntentInfo[] array =
8202                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
8203                    intentFilters.toArray(array);
8204                    listCut.add(array);
8205                }
8206            }
8207            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8208        }
8209
8210        public final void addService(PackageParser.Service s) {
8211            mServices.put(s.getComponentName(), s);
8212            if (DEBUG_SHOW_INFO) {
8213                Log.v(TAG, "  "
8214                        + (s.info.nonLocalizedLabel != null
8215                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8216                Log.v(TAG, "    Class=" + s.info.name);
8217            }
8218            final int NI = s.intents.size();
8219            int j;
8220            for (j=0; j<NI; j++) {
8221                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8222                if (DEBUG_SHOW_INFO) {
8223                    Log.v(TAG, "    IntentFilter:");
8224                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8225                }
8226                if (!intent.debugCheck()) {
8227                    Log.w(TAG, "==> For Service " + s.info.name);
8228                }
8229                addFilter(intent);
8230            }
8231        }
8232
8233        public final void removeService(PackageParser.Service s) {
8234            mServices.remove(s.getComponentName());
8235            if (DEBUG_SHOW_INFO) {
8236                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
8237                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8238                Log.v(TAG, "    Class=" + s.info.name);
8239            }
8240            final int NI = s.intents.size();
8241            int j;
8242            for (j=0; j<NI; j++) {
8243                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8244                if (DEBUG_SHOW_INFO) {
8245                    Log.v(TAG, "    IntentFilter:");
8246                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8247                }
8248                removeFilter(intent);
8249            }
8250        }
8251
8252        @Override
8253        protected boolean allowFilterResult(
8254                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
8255            ServiceInfo filterSi = filter.service.info;
8256            for (int i=dest.size()-1; i>=0; i--) {
8257                ServiceInfo destAi = dest.get(i).serviceInfo;
8258                if (destAi.name == filterSi.name
8259                        && destAi.packageName == filterSi.packageName) {
8260                    return false;
8261                }
8262            }
8263            return true;
8264        }
8265
8266        @Override
8267        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
8268            return new PackageParser.ServiceIntentInfo[size];
8269        }
8270
8271        @Override
8272        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
8273            if (!sUserManager.exists(userId)) return true;
8274            PackageParser.Package p = filter.service.owner;
8275            if (p != null) {
8276                PackageSetting ps = (PackageSetting)p.mExtras;
8277                if (ps != null) {
8278                    // System apps are never considered stopped for purposes of
8279                    // filtering, because there may be no way for the user to
8280                    // actually re-launch them.
8281                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8282                            && ps.getStopped(userId);
8283                }
8284            }
8285            return false;
8286        }
8287
8288        @Override
8289        protected boolean isPackageForFilter(String packageName,
8290                PackageParser.ServiceIntentInfo info) {
8291            return packageName.equals(info.service.owner.packageName);
8292        }
8293
8294        @Override
8295        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
8296                int match, int userId) {
8297            if (!sUserManager.exists(userId)) return null;
8298            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
8299            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
8300                return null;
8301            }
8302            final PackageParser.Service service = info.service;
8303            if (mSafeMode && (service.info.applicationInfo.flags
8304                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8305                return null;
8306            }
8307            PackageSetting ps = (PackageSetting) service.owner.mExtras;
8308            if (ps == null) {
8309                return null;
8310            }
8311            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
8312                    ps.readUserState(userId), userId);
8313            if (si == null) {
8314                return null;
8315            }
8316            final ResolveInfo res = new ResolveInfo();
8317            res.serviceInfo = si;
8318            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8319                res.filter = filter;
8320            }
8321            res.priority = info.getPriority();
8322            res.preferredOrder = service.owner.mPreferredOrder;
8323            res.match = match;
8324            res.isDefault = info.hasDefault;
8325            res.labelRes = info.labelRes;
8326            res.nonLocalizedLabel = info.nonLocalizedLabel;
8327            res.icon = info.icon;
8328            res.system = res.serviceInfo.applicationInfo.isSystemApp();
8329            return res;
8330        }
8331
8332        @Override
8333        protected void sortResults(List<ResolveInfo> results) {
8334            Collections.sort(results, mResolvePrioritySorter);
8335        }
8336
8337        @Override
8338        protected void dumpFilter(PrintWriter out, String prefix,
8339                PackageParser.ServiceIntentInfo filter) {
8340            out.print(prefix); out.print(
8341                    Integer.toHexString(System.identityHashCode(filter.service)));
8342                    out.print(' ');
8343                    filter.service.printComponentShortName(out);
8344                    out.print(" filter ");
8345                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8346        }
8347
8348        @Override
8349        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
8350            return filter.service;
8351        }
8352
8353        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8354            PackageParser.Service service = (PackageParser.Service)label;
8355            out.print(prefix); out.print(
8356                    Integer.toHexString(System.identityHashCode(service)));
8357                    out.print(' ');
8358                    service.printComponentShortName(out);
8359            if (count > 1) {
8360                out.print(" ("); out.print(count); out.print(" filters)");
8361            }
8362            out.println();
8363        }
8364
8365//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8366//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8367//            final List<ResolveInfo> retList = Lists.newArrayList();
8368//            while (i.hasNext()) {
8369//                final ResolveInfo resolveInfo = (ResolveInfo) i;
8370//                if (isEnabledLP(resolveInfo.serviceInfo)) {
8371//                    retList.add(resolveInfo);
8372//                }
8373//            }
8374//            return retList;
8375//        }
8376
8377        // Keys are String (activity class name), values are Activity.
8378        private final ArrayMap<ComponentName, PackageParser.Service> mServices
8379                = new ArrayMap<ComponentName, PackageParser.Service>();
8380        private int mFlags;
8381    };
8382
8383    private final class ProviderIntentResolver
8384            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
8385        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8386                boolean defaultOnly, int userId) {
8387            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8388            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8389        }
8390
8391        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8392                int userId) {
8393            if (!sUserManager.exists(userId))
8394                return null;
8395            mFlags = flags;
8396            return super.queryIntent(intent, resolvedType,
8397                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8398        }
8399
8400        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8401                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
8402            if (!sUserManager.exists(userId))
8403                return null;
8404            if (packageProviders == null) {
8405                return null;
8406            }
8407            mFlags = flags;
8408            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
8409            final int N = packageProviders.size();
8410            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
8411                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
8412
8413            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
8414            for (int i = 0; i < N; ++i) {
8415                intentFilters = packageProviders.get(i).intents;
8416                if (intentFilters != null && intentFilters.size() > 0) {
8417                    PackageParser.ProviderIntentInfo[] array =
8418                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
8419                    intentFilters.toArray(array);
8420                    listCut.add(array);
8421                }
8422            }
8423            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8424        }
8425
8426        public final void addProvider(PackageParser.Provider p) {
8427            if (mProviders.containsKey(p.getComponentName())) {
8428                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
8429                return;
8430            }
8431
8432            mProviders.put(p.getComponentName(), p);
8433            if (DEBUG_SHOW_INFO) {
8434                Log.v(TAG, "  "
8435                        + (p.info.nonLocalizedLabel != null
8436                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
8437                Log.v(TAG, "    Class=" + p.info.name);
8438            }
8439            final int NI = p.intents.size();
8440            int j;
8441            for (j = 0; j < NI; j++) {
8442                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
8443                if (DEBUG_SHOW_INFO) {
8444                    Log.v(TAG, "    IntentFilter:");
8445                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8446                }
8447                if (!intent.debugCheck()) {
8448                    Log.w(TAG, "==> For Provider " + p.info.name);
8449                }
8450                addFilter(intent);
8451            }
8452        }
8453
8454        public final void removeProvider(PackageParser.Provider p) {
8455            mProviders.remove(p.getComponentName());
8456            if (DEBUG_SHOW_INFO) {
8457                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
8458                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
8459                Log.v(TAG, "    Class=" + p.info.name);
8460            }
8461            final int NI = p.intents.size();
8462            int j;
8463            for (j = 0; j < NI; j++) {
8464                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
8465                if (DEBUG_SHOW_INFO) {
8466                    Log.v(TAG, "    IntentFilter:");
8467                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8468                }
8469                removeFilter(intent);
8470            }
8471        }
8472
8473        @Override
8474        protected boolean allowFilterResult(
8475                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
8476            ProviderInfo filterPi = filter.provider.info;
8477            for (int i = dest.size() - 1; i >= 0; i--) {
8478                ProviderInfo destPi = dest.get(i).providerInfo;
8479                if (destPi.name == filterPi.name
8480                        && destPi.packageName == filterPi.packageName) {
8481                    return false;
8482                }
8483            }
8484            return true;
8485        }
8486
8487        @Override
8488        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
8489            return new PackageParser.ProviderIntentInfo[size];
8490        }
8491
8492        @Override
8493        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
8494            if (!sUserManager.exists(userId))
8495                return true;
8496            PackageParser.Package p = filter.provider.owner;
8497            if (p != null) {
8498                PackageSetting ps = (PackageSetting) p.mExtras;
8499                if (ps != null) {
8500                    // System apps are never considered stopped for purposes of
8501                    // filtering, because there may be no way for the user to
8502                    // actually re-launch them.
8503                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8504                            && ps.getStopped(userId);
8505                }
8506            }
8507            return false;
8508        }
8509
8510        @Override
8511        protected boolean isPackageForFilter(String packageName,
8512                PackageParser.ProviderIntentInfo info) {
8513            return packageName.equals(info.provider.owner.packageName);
8514        }
8515
8516        @Override
8517        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
8518                int match, int userId) {
8519            if (!sUserManager.exists(userId))
8520                return null;
8521            final PackageParser.ProviderIntentInfo info = filter;
8522            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
8523                return null;
8524            }
8525            final PackageParser.Provider provider = info.provider;
8526            if (mSafeMode && (provider.info.applicationInfo.flags
8527                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
8528                return null;
8529            }
8530            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
8531            if (ps == null) {
8532                return null;
8533            }
8534            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
8535                    ps.readUserState(userId), userId);
8536            if (pi == null) {
8537                return null;
8538            }
8539            final ResolveInfo res = new ResolveInfo();
8540            res.providerInfo = pi;
8541            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
8542                res.filter = filter;
8543            }
8544            res.priority = info.getPriority();
8545            res.preferredOrder = provider.owner.mPreferredOrder;
8546            res.match = match;
8547            res.isDefault = info.hasDefault;
8548            res.labelRes = info.labelRes;
8549            res.nonLocalizedLabel = info.nonLocalizedLabel;
8550            res.icon = info.icon;
8551            res.system = res.providerInfo.applicationInfo.isSystemApp();
8552            return res;
8553        }
8554
8555        @Override
8556        protected void sortResults(List<ResolveInfo> results) {
8557            Collections.sort(results, mResolvePrioritySorter);
8558        }
8559
8560        @Override
8561        protected void dumpFilter(PrintWriter out, String prefix,
8562                PackageParser.ProviderIntentInfo filter) {
8563            out.print(prefix);
8564            out.print(
8565                    Integer.toHexString(System.identityHashCode(filter.provider)));
8566            out.print(' ');
8567            filter.provider.printComponentShortName(out);
8568            out.print(" filter ");
8569            out.println(Integer.toHexString(System.identityHashCode(filter)));
8570        }
8571
8572        @Override
8573        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
8574            return filter.provider;
8575        }
8576
8577        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8578            PackageParser.Provider provider = (PackageParser.Provider)label;
8579            out.print(prefix); out.print(
8580                    Integer.toHexString(System.identityHashCode(provider)));
8581                    out.print(' ');
8582                    provider.printComponentShortName(out);
8583            if (count > 1) {
8584                out.print(" ("); out.print(count); out.print(" filters)");
8585            }
8586            out.println();
8587        }
8588
8589        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
8590                = new ArrayMap<ComponentName, PackageParser.Provider>();
8591        private int mFlags;
8592    };
8593
8594    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
8595            new Comparator<ResolveInfo>() {
8596        public int compare(ResolveInfo r1, ResolveInfo r2) {
8597            int v1 = r1.priority;
8598            int v2 = r2.priority;
8599            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
8600            if (v1 != v2) {
8601                return (v1 > v2) ? -1 : 1;
8602            }
8603            v1 = r1.preferredOrder;
8604            v2 = r2.preferredOrder;
8605            if (v1 != v2) {
8606                return (v1 > v2) ? -1 : 1;
8607            }
8608            if (r1.isDefault != r2.isDefault) {
8609                return r1.isDefault ? -1 : 1;
8610            }
8611            v1 = r1.match;
8612            v2 = r2.match;
8613            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
8614            if (v1 != v2) {
8615                return (v1 > v2) ? -1 : 1;
8616            }
8617            if (r1.system != r2.system) {
8618                return r1.system ? -1 : 1;
8619            }
8620            return 0;
8621        }
8622    };
8623
8624    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
8625            new Comparator<ProviderInfo>() {
8626        public int compare(ProviderInfo p1, ProviderInfo p2) {
8627            final int v1 = p1.initOrder;
8628            final int v2 = p2.initOrder;
8629            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
8630        }
8631    };
8632
8633    final void sendPackageBroadcast(final String action, final String pkg,
8634            final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
8635            final int[] userIds) {
8636        mHandler.post(new Runnable() {
8637            @Override
8638            public void run() {
8639                try {
8640                    final IActivityManager am = ActivityManagerNative.getDefault();
8641                    if (am == null) return;
8642                    final int[] resolvedUserIds;
8643                    if (userIds == null) {
8644                        resolvedUserIds = am.getRunningUserIds();
8645                    } else {
8646                        resolvedUserIds = userIds;
8647                    }
8648                    for (int id : resolvedUserIds) {
8649                        final Intent intent = new Intent(action,
8650                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
8651                        if (extras != null) {
8652                            intent.putExtras(extras);
8653                        }
8654                        if (targetPkg != null) {
8655                            intent.setPackage(targetPkg);
8656                        }
8657                        // Modify the UID when posting to other users
8658                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
8659                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
8660                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
8661                            intent.putExtra(Intent.EXTRA_UID, uid);
8662                        }
8663                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
8664                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
8665                        if (DEBUG_BROADCASTS) {
8666                            RuntimeException here = new RuntimeException("here");
8667                            here.fillInStackTrace();
8668                            Slog.d(TAG, "Sending to user " + id + ": "
8669                                    + intent.toShortString(false, true, false, false)
8670                                    + " " + intent.getExtras(), here);
8671                        }
8672                        am.broadcastIntent(null, intent, null, finishedReceiver,
8673                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
8674                                finishedReceiver != null, false, id);
8675                    }
8676                } catch (RemoteException ex) {
8677                }
8678            }
8679        });
8680    }
8681
8682    /**
8683     * Check if the external storage media is available. This is true if there
8684     * is a mounted external storage medium or if the external storage is
8685     * emulated.
8686     */
8687    private boolean isExternalMediaAvailable() {
8688        return mMediaMounted || Environment.isExternalStorageEmulated();
8689    }
8690
8691    @Override
8692    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
8693        // writer
8694        synchronized (mPackages) {
8695            if (!isExternalMediaAvailable()) {
8696                // If the external storage is no longer mounted at this point,
8697                // the caller may not have been able to delete all of this
8698                // packages files and can not delete any more.  Bail.
8699                return null;
8700            }
8701            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
8702            if (lastPackage != null) {
8703                pkgs.remove(lastPackage);
8704            }
8705            if (pkgs.size() > 0) {
8706                return pkgs.get(0);
8707            }
8708        }
8709        return null;
8710    }
8711
8712    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
8713        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
8714                userId, andCode ? 1 : 0, packageName);
8715        if (mSystemReady) {
8716            msg.sendToTarget();
8717        } else {
8718            if (mPostSystemReadyMessages == null) {
8719                mPostSystemReadyMessages = new ArrayList<>();
8720            }
8721            mPostSystemReadyMessages.add(msg);
8722        }
8723    }
8724
8725    void startCleaningPackages() {
8726        // reader
8727        synchronized (mPackages) {
8728            if (!isExternalMediaAvailable()) {
8729                return;
8730            }
8731            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
8732                return;
8733            }
8734        }
8735        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
8736        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
8737        IActivityManager am = ActivityManagerNative.getDefault();
8738        if (am != null) {
8739            try {
8740                am.startService(null, intent, null, UserHandle.USER_OWNER);
8741            } catch (RemoteException e) {
8742            }
8743        }
8744    }
8745
8746    @Override
8747    public void installPackage(String originPath, IPackageInstallObserver2 observer,
8748            int installFlags, String installerPackageName, VerificationParams verificationParams,
8749            String packageAbiOverride) {
8750        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
8751                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
8752    }
8753
8754    @Override
8755    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
8756            int installFlags, String installerPackageName, VerificationParams verificationParams,
8757            String packageAbiOverride, int userId) {
8758        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
8759
8760        final int callingUid = Binder.getCallingUid();
8761        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
8762
8763        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
8764            try {
8765                if (observer != null) {
8766                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
8767                }
8768            } catch (RemoteException re) {
8769            }
8770            return;
8771        }
8772
8773        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
8774            installFlags |= PackageManager.INSTALL_FROM_ADB;
8775
8776        } else {
8777            // Caller holds INSTALL_PACKAGES permission, so we're less strict
8778            // about installerPackageName.
8779
8780            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
8781            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
8782        }
8783
8784        UserHandle user;
8785        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
8786            user = UserHandle.ALL;
8787        } else {
8788            user = new UserHandle(userId);
8789        }
8790
8791        // Only system components can circumvent runtime permissions when installing.
8792        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
8793                && mContext.checkCallingOrSelfPermission(Manifest.permission
8794                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
8795            throw new SecurityException("You need the "
8796                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
8797                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
8798        }
8799
8800        verificationParams.setInstallerUid(callingUid);
8801
8802        final File originFile = new File(originPath);
8803        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
8804
8805        final Message msg = mHandler.obtainMessage(INIT_COPY);
8806        msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName,
8807                null, verificationParams, user, packageAbiOverride);
8808        mHandler.sendMessage(msg);
8809    }
8810
8811    void installStage(String packageName, File stagedDir, String stagedCid,
8812            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
8813            String installerPackageName, int installerUid, UserHandle user) {
8814        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
8815                params.referrerUri, installerUid, null);
8816
8817        final OriginInfo origin;
8818        if (stagedDir != null) {
8819            origin = OriginInfo.fromStagedFile(stagedDir);
8820        } else {
8821            origin = OriginInfo.fromStagedContainer(stagedCid);
8822        }
8823
8824        final Message msg = mHandler.obtainMessage(INIT_COPY);
8825        msg.obj = new InstallParams(origin, null, observer, params.installFlags,
8826                installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride);
8827        mHandler.sendMessage(msg);
8828    }
8829
8830    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
8831        Bundle extras = new Bundle(1);
8832        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
8833
8834        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
8835                packageName, extras, null, null, new int[] {userId});
8836        try {
8837            IActivityManager am = ActivityManagerNative.getDefault();
8838            final boolean isSystem =
8839                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
8840            if (isSystem && am.isUserRunning(userId, false)) {
8841                // The just-installed/enabled app is bundled on the system, so presumed
8842                // to be able to run automatically without needing an explicit launch.
8843                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
8844                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
8845                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
8846                        .setPackage(packageName);
8847                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
8848                        android.app.AppOpsManager.OP_NONE, false, false, userId);
8849            }
8850        } catch (RemoteException e) {
8851            // shouldn't happen
8852            Slog.w(TAG, "Unable to bootstrap installed package", e);
8853        }
8854    }
8855
8856    @Override
8857    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
8858            int userId) {
8859        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
8860        PackageSetting pkgSetting;
8861        final int uid = Binder.getCallingUid();
8862        enforceCrossUserPermission(uid, userId, true, true,
8863                "setApplicationHiddenSetting for user " + userId);
8864
8865        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
8866            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
8867            return false;
8868        }
8869
8870        long callingId = Binder.clearCallingIdentity();
8871        try {
8872            boolean sendAdded = false;
8873            boolean sendRemoved = false;
8874            // writer
8875            synchronized (mPackages) {
8876                pkgSetting = mSettings.mPackages.get(packageName);
8877                if (pkgSetting == null) {
8878                    return false;
8879                }
8880                if (pkgSetting.getHidden(userId) != hidden) {
8881                    pkgSetting.setHidden(hidden, userId);
8882                    mSettings.writePackageRestrictionsLPr(userId);
8883                    if (hidden) {
8884                        sendRemoved = true;
8885                    } else {
8886                        sendAdded = true;
8887                    }
8888                }
8889            }
8890            if (sendAdded) {
8891                sendPackageAddedForUser(packageName, pkgSetting, userId);
8892                return true;
8893            }
8894            if (sendRemoved) {
8895                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
8896                        "hiding pkg");
8897                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
8898            }
8899        } finally {
8900            Binder.restoreCallingIdentity(callingId);
8901        }
8902        return false;
8903    }
8904
8905    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
8906            int userId) {
8907        final PackageRemovedInfo info = new PackageRemovedInfo();
8908        info.removedPackage = packageName;
8909        info.removedUsers = new int[] {userId};
8910        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
8911        info.sendBroadcast(false, false, false);
8912    }
8913
8914    /**
8915     * Returns true if application is not found or there was an error. Otherwise it returns
8916     * the hidden state of the package for the given user.
8917     */
8918    @Override
8919    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
8920        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
8921        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
8922                false, "getApplicationHidden for user " + userId);
8923        PackageSetting pkgSetting;
8924        long callingId = Binder.clearCallingIdentity();
8925        try {
8926            // writer
8927            synchronized (mPackages) {
8928                pkgSetting = mSettings.mPackages.get(packageName);
8929                if (pkgSetting == null) {
8930                    return true;
8931                }
8932                return pkgSetting.getHidden(userId);
8933            }
8934        } finally {
8935            Binder.restoreCallingIdentity(callingId);
8936        }
8937    }
8938
8939    /**
8940     * @hide
8941     */
8942    @Override
8943    public int installExistingPackageAsUser(String packageName, int userId) {
8944        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
8945                null);
8946        PackageSetting pkgSetting;
8947        final int uid = Binder.getCallingUid();
8948        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
8949                + userId);
8950        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
8951            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
8952        }
8953
8954        long callingId = Binder.clearCallingIdentity();
8955        try {
8956            boolean sendAdded = false;
8957
8958            // writer
8959            synchronized (mPackages) {
8960                pkgSetting = mSettings.mPackages.get(packageName);
8961                if (pkgSetting == null) {
8962                    return PackageManager.INSTALL_FAILED_INVALID_URI;
8963                }
8964                if (!pkgSetting.getInstalled(userId)) {
8965                    pkgSetting.setInstalled(true, userId);
8966                    pkgSetting.setHidden(false, userId);
8967                    mSettings.writePackageRestrictionsLPr(userId);
8968                    sendAdded = true;
8969                }
8970            }
8971
8972            if (sendAdded) {
8973                sendPackageAddedForUser(packageName, pkgSetting, userId);
8974            }
8975        } finally {
8976            Binder.restoreCallingIdentity(callingId);
8977        }
8978
8979        return PackageManager.INSTALL_SUCCEEDED;
8980    }
8981
8982    boolean isUserRestricted(int userId, String restrictionKey) {
8983        Bundle restrictions = sUserManager.getUserRestrictions(userId);
8984        if (restrictions.getBoolean(restrictionKey, false)) {
8985            Log.w(TAG, "User is restricted: " + restrictionKey);
8986            return true;
8987        }
8988        return false;
8989    }
8990
8991    @Override
8992    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
8993        mContext.enforceCallingOrSelfPermission(
8994                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8995                "Only package verification agents can verify applications");
8996
8997        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
8998        final PackageVerificationResponse response = new PackageVerificationResponse(
8999                verificationCode, Binder.getCallingUid());
9000        msg.arg1 = id;
9001        msg.obj = response;
9002        mHandler.sendMessage(msg);
9003    }
9004
9005    @Override
9006    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
9007            long millisecondsToDelay) {
9008        mContext.enforceCallingOrSelfPermission(
9009                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9010                "Only package verification agents can extend verification timeouts");
9011
9012        final PackageVerificationState state = mPendingVerification.get(id);
9013        final PackageVerificationResponse response = new PackageVerificationResponse(
9014                verificationCodeAtTimeout, Binder.getCallingUid());
9015
9016        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
9017            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
9018        }
9019        if (millisecondsToDelay < 0) {
9020            millisecondsToDelay = 0;
9021        }
9022        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9023                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9024            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9025        }
9026
9027        if ((state != null) && !state.timeoutExtended()) {
9028            state.extendTimeout();
9029
9030            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9031            msg.arg1 = id;
9032            msg.obj = response;
9033            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
9034        }
9035    }
9036
9037    private void broadcastPackageVerified(int verificationId, Uri packageUri,
9038            int verificationCode, UserHandle user) {
9039        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
9040        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
9041        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9042        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9043        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
9044
9045        mContext.sendBroadcastAsUser(intent, user,
9046                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
9047    }
9048
9049    private ComponentName matchComponentForVerifier(String packageName,
9050            List<ResolveInfo> receivers) {
9051        ActivityInfo targetReceiver = null;
9052
9053        final int NR = receivers.size();
9054        for (int i = 0; i < NR; i++) {
9055            final ResolveInfo info = receivers.get(i);
9056            if (info.activityInfo == null) {
9057                continue;
9058            }
9059
9060            if (packageName.equals(info.activityInfo.packageName)) {
9061                targetReceiver = info.activityInfo;
9062                break;
9063            }
9064        }
9065
9066        if (targetReceiver == null) {
9067            return null;
9068        }
9069
9070        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
9071    }
9072
9073    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
9074            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
9075        if (pkgInfo.verifiers.length == 0) {
9076            return null;
9077        }
9078
9079        final int N = pkgInfo.verifiers.length;
9080        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
9081        for (int i = 0; i < N; i++) {
9082            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
9083
9084            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
9085                    receivers);
9086            if (comp == null) {
9087                continue;
9088            }
9089
9090            final int verifierUid = getUidForVerifier(verifierInfo);
9091            if (verifierUid == -1) {
9092                continue;
9093            }
9094
9095            if (DEBUG_VERIFY) {
9096                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
9097                        + " with the correct signature");
9098            }
9099            sufficientVerifiers.add(comp);
9100            verificationState.addSufficientVerifier(verifierUid);
9101        }
9102
9103        return sufficientVerifiers;
9104    }
9105
9106    private int getUidForVerifier(VerifierInfo verifierInfo) {
9107        synchronized (mPackages) {
9108            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
9109            if (pkg == null) {
9110                return -1;
9111            } else if (pkg.mSignatures.length != 1) {
9112                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9113                        + " has more than one signature; ignoring");
9114                return -1;
9115            }
9116
9117            /*
9118             * If the public key of the package's signature does not match
9119             * our expected public key, then this is a different package and
9120             * we should skip.
9121             */
9122
9123            final byte[] expectedPublicKey;
9124            try {
9125                final Signature verifierSig = pkg.mSignatures[0];
9126                final PublicKey publicKey = verifierSig.getPublicKey();
9127                expectedPublicKey = publicKey.getEncoded();
9128            } catch (CertificateException e) {
9129                return -1;
9130            }
9131
9132            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
9133
9134            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
9135                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9136                        + " does not have the expected public key; ignoring");
9137                return -1;
9138            }
9139
9140            return pkg.applicationInfo.uid;
9141        }
9142    }
9143
9144    @Override
9145    public void finishPackageInstall(int token) {
9146        enforceSystemOrRoot("Only the system is allowed to finish installs");
9147
9148        if (DEBUG_INSTALL) {
9149            Slog.v(TAG, "BM finishing package install for " + token);
9150        }
9151
9152        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9153        mHandler.sendMessage(msg);
9154    }
9155
9156    /**
9157     * Get the verification agent timeout.
9158     *
9159     * @return verification timeout in milliseconds
9160     */
9161    private long getVerificationTimeout() {
9162        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
9163                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
9164                DEFAULT_VERIFICATION_TIMEOUT);
9165    }
9166
9167    /**
9168     * Get the default verification agent response code.
9169     *
9170     * @return default verification response code
9171     */
9172    private int getDefaultVerificationResponse() {
9173        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9174                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
9175                DEFAULT_VERIFICATION_RESPONSE);
9176    }
9177
9178    /**
9179     * Check whether or not package verification has been enabled.
9180     *
9181     * @return true if verification should be performed
9182     */
9183    private boolean isVerificationEnabled(int userId, int installFlags) {
9184        if (!DEFAULT_VERIFY_ENABLE) {
9185            return false;
9186        }
9187
9188        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
9189
9190        // Check if installing from ADB
9191        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
9192            // Do not run verification in a test harness environment
9193            if (ActivityManager.isRunningInTestHarness()) {
9194                return false;
9195            }
9196            if (ensureVerifyAppsEnabled) {
9197                return true;
9198            }
9199            // Check if the developer does not want package verification for ADB installs
9200            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9201                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
9202                return false;
9203            }
9204        }
9205
9206        if (ensureVerifyAppsEnabled) {
9207            return true;
9208        }
9209
9210        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9211                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9212    }
9213
9214    @Override
9215    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9216            throws RemoteException {
9217        mContext.enforceCallingOrSelfPermission(
9218                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9219                "Only intentfilter verification agents can verify applications");
9220
9221        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9222        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9223                Binder.getCallingUid(), verificationCode, failedDomains);
9224        msg.arg1 = id;
9225        msg.obj = response;
9226        mHandler.sendMessage(msg);
9227    }
9228
9229    @Override
9230    public int getIntentVerificationStatus(String packageName, int userId) {
9231        synchronized (mPackages) {
9232            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
9233        }
9234    }
9235
9236    @Override
9237    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
9238        boolean result = false;
9239        synchronized (mPackages) {
9240            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
9241        }
9242        if (result) {
9243            scheduleWritePackageRestrictionsLocked(userId);
9244        }
9245        return result;
9246    }
9247
9248    @Override
9249    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
9250        synchronized (mPackages) {
9251            return mSettings.getIntentFilterVerificationsLPr(packageName);
9252        }
9253    }
9254
9255    @Override
9256    public List<IntentFilter> getAllIntentFilters(String packageName) {
9257        if (TextUtils.isEmpty(packageName)) {
9258            return Collections.<IntentFilter>emptyList();
9259        }
9260        synchronized (mPackages) {
9261            PackageParser.Package pkg = mPackages.get(packageName);
9262            if (pkg == null || pkg.activities == null) {
9263                return Collections.<IntentFilter>emptyList();
9264            }
9265            final int count = pkg.activities.size();
9266            ArrayList<IntentFilter> result = new ArrayList<>();
9267            for (int n=0; n<count; n++) {
9268                PackageParser.Activity activity = pkg.activities.get(n);
9269                if (activity.intents != null || activity.intents.size() > 0) {
9270                    result.addAll(activity.intents);
9271                }
9272            }
9273            return result;
9274        }
9275    }
9276
9277    @Override
9278    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
9279        synchronized (mPackages) {
9280            boolean result = mSettings.setDefaultBrowserPackageNameLPr(packageName, userId);
9281            if (packageName != null) {
9282                result |= updateIntentVerificationStatus(packageName,
9283                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
9284                        UserHandle.myUserId());
9285            }
9286            return result;
9287        }
9288    }
9289
9290    @Override
9291    public String getDefaultBrowserPackageName(int userId) {
9292        synchronized (mPackages) {
9293            return mSettings.getDefaultBrowserPackageNameLPw(userId);
9294        }
9295    }
9296
9297    /**
9298     * Get the "allow unknown sources" setting.
9299     *
9300     * @return the current "allow unknown sources" setting
9301     */
9302    private int getUnknownSourcesSettings() {
9303        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9304                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
9305                -1);
9306    }
9307
9308    @Override
9309    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
9310        final int uid = Binder.getCallingUid();
9311        // writer
9312        synchronized (mPackages) {
9313            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
9314            if (targetPackageSetting == null) {
9315                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
9316            }
9317
9318            PackageSetting installerPackageSetting;
9319            if (installerPackageName != null) {
9320                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
9321                if (installerPackageSetting == null) {
9322                    throw new IllegalArgumentException("Unknown installer package: "
9323                            + installerPackageName);
9324                }
9325            } else {
9326                installerPackageSetting = null;
9327            }
9328
9329            Signature[] callerSignature;
9330            Object obj = mSettings.getUserIdLPr(uid);
9331            if (obj != null) {
9332                if (obj instanceof SharedUserSetting) {
9333                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
9334                } else if (obj instanceof PackageSetting) {
9335                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
9336                } else {
9337                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
9338                }
9339            } else {
9340                throw new SecurityException("Unknown calling uid " + uid);
9341            }
9342
9343            // Verify: can't set installerPackageName to a package that is
9344            // not signed with the same cert as the caller.
9345            if (installerPackageSetting != null) {
9346                if (compareSignatures(callerSignature,
9347                        installerPackageSetting.signatures.mSignatures)
9348                        != PackageManager.SIGNATURE_MATCH) {
9349                    throw new SecurityException(
9350                            "Caller does not have same cert as new installer package "
9351                            + installerPackageName);
9352                }
9353            }
9354
9355            // Verify: if target already has an installer package, it must
9356            // be signed with the same cert as the caller.
9357            if (targetPackageSetting.installerPackageName != null) {
9358                PackageSetting setting = mSettings.mPackages.get(
9359                        targetPackageSetting.installerPackageName);
9360                // If the currently set package isn't valid, then it's always
9361                // okay to change it.
9362                if (setting != null) {
9363                    if (compareSignatures(callerSignature,
9364                            setting.signatures.mSignatures)
9365                            != PackageManager.SIGNATURE_MATCH) {
9366                        throw new SecurityException(
9367                                "Caller does not have same cert as old installer package "
9368                                + targetPackageSetting.installerPackageName);
9369                    }
9370                }
9371            }
9372
9373            // Okay!
9374            targetPackageSetting.installerPackageName = installerPackageName;
9375            scheduleWriteSettingsLocked();
9376        }
9377    }
9378
9379    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
9380        // Queue up an async operation since the package installation may take a little while.
9381        mHandler.post(new Runnable() {
9382            public void run() {
9383                mHandler.removeCallbacks(this);
9384                 // Result object to be returned
9385                PackageInstalledInfo res = new PackageInstalledInfo();
9386                res.returnCode = currentStatus;
9387                res.uid = -1;
9388                res.pkg = null;
9389                res.removedInfo = new PackageRemovedInfo();
9390                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
9391                    args.doPreInstall(res.returnCode);
9392                    synchronized (mInstallLock) {
9393                        installPackageLI(args, res);
9394                    }
9395                    args.doPostInstall(res.returnCode, res.uid);
9396                }
9397
9398                // A restore should be performed at this point if (a) the install
9399                // succeeded, (b) the operation is not an update, and (c) the new
9400                // package has not opted out of backup participation.
9401                final boolean update = res.removedInfo.removedPackage != null;
9402                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
9403                boolean doRestore = !update
9404                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
9405
9406                // Set up the post-install work request bookkeeping.  This will be used
9407                // and cleaned up by the post-install event handling regardless of whether
9408                // there's a restore pass performed.  Token values are >= 1.
9409                int token;
9410                if (mNextInstallToken < 0) mNextInstallToken = 1;
9411                token = mNextInstallToken++;
9412
9413                PostInstallData data = new PostInstallData(args, res);
9414                mRunningInstalls.put(token, data);
9415                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
9416
9417                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
9418                    // Pass responsibility to the Backup Manager.  It will perform a
9419                    // restore if appropriate, then pass responsibility back to the
9420                    // Package Manager to run the post-install observer callbacks
9421                    // and broadcasts.
9422                    IBackupManager bm = IBackupManager.Stub.asInterface(
9423                            ServiceManager.getService(Context.BACKUP_SERVICE));
9424                    if (bm != null) {
9425                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
9426                                + " to BM for possible restore");
9427                        try {
9428                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
9429                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
9430                            } else {
9431                                doRestore = false;
9432                            }
9433                        } catch (RemoteException e) {
9434                            // can't happen; the backup manager is local
9435                        } catch (Exception e) {
9436                            Slog.e(TAG, "Exception trying to enqueue restore", e);
9437                            doRestore = false;
9438                        }
9439                    } else {
9440                        Slog.e(TAG, "Backup Manager not found!");
9441                        doRestore = false;
9442                    }
9443                }
9444
9445                if (!doRestore) {
9446                    // No restore possible, or the Backup Manager was mysteriously not
9447                    // available -- just fire the post-install work request directly.
9448                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
9449                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9450                    mHandler.sendMessage(msg);
9451                }
9452            }
9453        });
9454    }
9455
9456    private abstract class HandlerParams {
9457        private static final int MAX_RETRIES = 4;
9458
9459        /**
9460         * Number of times startCopy() has been attempted and had a non-fatal
9461         * error.
9462         */
9463        private int mRetries = 0;
9464
9465        /** User handle for the user requesting the information or installation. */
9466        private final UserHandle mUser;
9467
9468        HandlerParams(UserHandle user) {
9469            mUser = user;
9470        }
9471
9472        UserHandle getUser() {
9473            return mUser;
9474        }
9475
9476        final boolean startCopy() {
9477            boolean res;
9478            try {
9479                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
9480
9481                if (++mRetries > MAX_RETRIES) {
9482                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
9483                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
9484                    handleServiceError();
9485                    return false;
9486                } else {
9487                    handleStartCopy();
9488                    res = true;
9489                }
9490            } catch (RemoteException e) {
9491                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
9492                mHandler.sendEmptyMessage(MCS_RECONNECT);
9493                res = false;
9494            }
9495            handleReturnCode();
9496            return res;
9497        }
9498
9499        final void serviceError() {
9500            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
9501            handleServiceError();
9502            handleReturnCode();
9503        }
9504
9505        abstract void handleStartCopy() throws RemoteException;
9506        abstract void handleServiceError();
9507        abstract void handleReturnCode();
9508    }
9509
9510    class MeasureParams extends HandlerParams {
9511        private final PackageStats mStats;
9512        private boolean mSuccess;
9513
9514        private final IPackageStatsObserver mObserver;
9515
9516        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
9517            super(new UserHandle(stats.userHandle));
9518            mObserver = observer;
9519            mStats = stats;
9520        }
9521
9522        @Override
9523        public String toString() {
9524            return "MeasureParams{"
9525                + Integer.toHexString(System.identityHashCode(this))
9526                + " " + mStats.packageName + "}";
9527        }
9528
9529        @Override
9530        void handleStartCopy() throws RemoteException {
9531            synchronized (mInstallLock) {
9532                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
9533            }
9534
9535            if (mSuccess) {
9536                final boolean mounted;
9537                if (Environment.isExternalStorageEmulated()) {
9538                    mounted = true;
9539                } else {
9540                    final String status = Environment.getExternalStorageState();
9541                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
9542                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
9543                }
9544
9545                if (mounted) {
9546                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
9547
9548                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
9549                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
9550
9551                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
9552                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
9553
9554                    // Always subtract cache size, since it's a subdirectory
9555                    mStats.externalDataSize -= mStats.externalCacheSize;
9556
9557                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
9558                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
9559
9560                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
9561                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
9562                }
9563            }
9564        }
9565
9566        @Override
9567        void handleReturnCode() {
9568            if (mObserver != null) {
9569                try {
9570                    mObserver.onGetStatsCompleted(mStats, mSuccess);
9571                } catch (RemoteException e) {
9572                    Slog.i(TAG, "Observer no longer exists.");
9573                }
9574            }
9575        }
9576
9577        @Override
9578        void handleServiceError() {
9579            Slog.e(TAG, "Could not measure application " + mStats.packageName
9580                            + " external storage");
9581        }
9582    }
9583
9584    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
9585            throws RemoteException {
9586        long result = 0;
9587        for (File path : paths) {
9588            result += mcs.calculateDirectorySize(path.getAbsolutePath());
9589        }
9590        return result;
9591    }
9592
9593    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
9594        for (File path : paths) {
9595            try {
9596                mcs.clearDirectory(path.getAbsolutePath());
9597            } catch (RemoteException e) {
9598            }
9599        }
9600    }
9601
9602    static class OriginInfo {
9603        /**
9604         * Location where install is coming from, before it has been
9605         * copied/renamed into place. This could be a single monolithic APK
9606         * file, or a cluster directory. This location may be untrusted.
9607         */
9608        final File file;
9609        final String cid;
9610
9611        /**
9612         * Flag indicating that {@link #file} or {@link #cid} has already been
9613         * staged, meaning downstream users don't need to defensively copy the
9614         * contents.
9615         */
9616        final boolean staged;
9617
9618        /**
9619         * Flag indicating that {@link #file} or {@link #cid} is an already
9620         * installed app that is being moved.
9621         */
9622        final boolean existing;
9623
9624        final String resolvedPath;
9625        final File resolvedFile;
9626
9627        static OriginInfo fromNothing() {
9628            return new OriginInfo(null, null, false, false);
9629        }
9630
9631        static OriginInfo fromUntrustedFile(File file) {
9632            return new OriginInfo(file, null, false, false);
9633        }
9634
9635        static OriginInfo fromExistingFile(File file) {
9636            return new OriginInfo(file, null, false, true);
9637        }
9638
9639        static OriginInfo fromStagedFile(File file) {
9640            return new OriginInfo(file, null, true, false);
9641        }
9642
9643        static OriginInfo fromStagedContainer(String cid) {
9644            return new OriginInfo(null, cid, true, false);
9645        }
9646
9647        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
9648            this.file = file;
9649            this.cid = cid;
9650            this.staged = staged;
9651            this.existing = existing;
9652
9653            if (cid != null) {
9654                resolvedPath = PackageHelper.getSdDir(cid);
9655                resolvedFile = new File(resolvedPath);
9656            } else if (file != null) {
9657                resolvedPath = file.getAbsolutePath();
9658                resolvedFile = file;
9659            } else {
9660                resolvedPath = null;
9661                resolvedFile = null;
9662            }
9663        }
9664    }
9665
9666    class MoveInfo {
9667        final int moveId;
9668        final String fromUuid;
9669        final String toUuid;
9670        final String packageName;
9671        final String dataAppName;
9672        final int appId;
9673        final String seinfo;
9674
9675        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
9676                String dataAppName, int appId, String seinfo) {
9677            this.moveId = moveId;
9678            this.fromUuid = fromUuid;
9679            this.toUuid = toUuid;
9680            this.packageName = packageName;
9681            this.dataAppName = dataAppName;
9682            this.appId = appId;
9683            this.seinfo = seinfo;
9684        }
9685    }
9686
9687    class InstallParams extends HandlerParams {
9688        final OriginInfo origin;
9689        final MoveInfo move;
9690        final IPackageInstallObserver2 observer;
9691        int installFlags;
9692        final String installerPackageName;
9693        final String volumeUuid;
9694        final VerificationParams verificationParams;
9695        private InstallArgs mArgs;
9696        private int mRet;
9697        final String packageAbiOverride;
9698
9699        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
9700                int installFlags, String installerPackageName, String volumeUuid,
9701                VerificationParams verificationParams, UserHandle user, String packageAbiOverride) {
9702            super(user);
9703            this.origin = origin;
9704            this.move = move;
9705            this.observer = observer;
9706            this.installFlags = installFlags;
9707            this.installerPackageName = installerPackageName;
9708            this.volumeUuid = volumeUuid;
9709            this.verificationParams = verificationParams;
9710            this.packageAbiOverride = packageAbiOverride;
9711        }
9712
9713        @Override
9714        public String toString() {
9715            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
9716                    + " file=" + origin.file + " cid=" + origin.cid + "}";
9717        }
9718
9719        public ManifestDigest getManifestDigest() {
9720            if (verificationParams == null) {
9721                return null;
9722            }
9723            return verificationParams.getManifestDigest();
9724        }
9725
9726        private int installLocationPolicy(PackageInfoLite pkgLite) {
9727            String packageName = pkgLite.packageName;
9728            int installLocation = pkgLite.installLocation;
9729            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9730            // reader
9731            synchronized (mPackages) {
9732                PackageParser.Package pkg = mPackages.get(packageName);
9733                if (pkg != null) {
9734                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
9735                        // Check for downgrading.
9736                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
9737                            try {
9738                                checkDowngrade(pkg, pkgLite);
9739                            } catch (PackageManagerException e) {
9740                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
9741                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
9742                            }
9743                        }
9744                        // Check for updated system application.
9745                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
9746                            if (onSd) {
9747                                Slog.w(TAG, "Cannot install update to system app on sdcard");
9748                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
9749                            }
9750                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
9751                        } else {
9752                            if (onSd) {
9753                                // Install flag overrides everything.
9754                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
9755                            }
9756                            // If current upgrade specifies particular preference
9757                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
9758                                // Application explicitly specified internal.
9759                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
9760                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
9761                                // App explictly prefers external. Let policy decide
9762                            } else {
9763                                // Prefer previous location
9764                                if (isExternal(pkg)) {
9765                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
9766                                }
9767                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
9768                            }
9769                        }
9770                    } else {
9771                        // Invalid install. Return error code
9772                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
9773                    }
9774                }
9775            }
9776            // All the special cases have been taken care of.
9777            // Return result based on recommended install location.
9778            if (onSd) {
9779                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
9780            }
9781            return pkgLite.recommendedInstallLocation;
9782        }
9783
9784        /*
9785         * Invoke remote method to get package information and install
9786         * location values. Override install location based on default
9787         * policy if needed and then create install arguments based
9788         * on the install location.
9789         */
9790        public void handleStartCopy() throws RemoteException {
9791            int ret = PackageManager.INSTALL_SUCCEEDED;
9792
9793            // If we're already staged, we've firmly committed to an install location
9794            if (origin.staged) {
9795                if (origin.file != null) {
9796                    installFlags |= PackageManager.INSTALL_INTERNAL;
9797                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
9798                } else if (origin.cid != null) {
9799                    installFlags |= PackageManager.INSTALL_EXTERNAL;
9800                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
9801                } else {
9802                    throw new IllegalStateException("Invalid stage location");
9803                }
9804            }
9805
9806            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9807            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
9808
9809            PackageInfoLite pkgLite = null;
9810
9811            if (onInt && onSd) {
9812                // Check if both bits are set.
9813                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
9814                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
9815            } else {
9816                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
9817                        packageAbiOverride);
9818
9819                /*
9820                 * If we have too little free space, try to free cache
9821                 * before giving up.
9822                 */
9823                if (!origin.staged && pkgLite.recommendedInstallLocation
9824                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
9825                    // TODO: focus freeing disk space on the target device
9826                    final StorageManager storage = StorageManager.from(mContext);
9827                    final long lowThreshold = storage.getStorageLowBytes(
9828                            Environment.getDataDirectory());
9829
9830                    final long sizeBytes = mContainerService.calculateInstalledSize(
9831                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
9832
9833                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
9834                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
9835                                installFlags, packageAbiOverride);
9836                    }
9837
9838                    /*
9839                     * The cache free must have deleted the file we
9840                     * downloaded to install.
9841                     *
9842                     * TODO: fix the "freeCache" call to not delete
9843                     *       the file we care about.
9844                     */
9845                    if (pkgLite.recommendedInstallLocation
9846                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
9847                        pkgLite.recommendedInstallLocation
9848                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
9849                    }
9850                }
9851            }
9852
9853            if (ret == PackageManager.INSTALL_SUCCEEDED) {
9854                int loc = pkgLite.recommendedInstallLocation;
9855                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
9856                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
9857                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
9858                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
9859                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
9860                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9861                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
9862                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
9863                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
9864                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
9865                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
9866                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
9867                } else {
9868                    // Override with defaults if needed.
9869                    loc = installLocationPolicy(pkgLite);
9870                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
9871                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
9872                    } else if (!onSd && !onInt) {
9873                        // Override install location with flags
9874                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
9875                            // Set the flag to install on external media.
9876                            installFlags |= PackageManager.INSTALL_EXTERNAL;
9877                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
9878                        } else {
9879                            // Make sure the flag for installing on external
9880                            // media is unset
9881                            installFlags |= PackageManager.INSTALL_INTERNAL;
9882                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
9883                        }
9884                    }
9885                }
9886            }
9887
9888            final InstallArgs args = createInstallArgs(this);
9889            mArgs = args;
9890
9891            if (ret == PackageManager.INSTALL_SUCCEEDED) {
9892                 /*
9893                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
9894                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
9895                 */
9896                int userIdentifier = getUser().getIdentifier();
9897                if (userIdentifier == UserHandle.USER_ALL
9898                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
9899                    userIdentifier = UserHandle.USER_OWNER;
9900                }
9901
9902                /*
9903                 * Determine if we have any installed package verifiers. If we
9904                 * do, then we'll defer to them to verify the packages.
9905                 */
9906                final int requiredUid = mRequiredVerifierPackage == null ? -1
9907                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
9908                if (!origin.existing && requiredUid != -1
9909                        && isVerificationEnabled(userIdentifier, installFlags)) {
9910                    final Intent verification = new Intent(
9911                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
9912                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
9913                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
9914                            PACKAGE_MIME_TYPE);
9915                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9916
9917                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
9918                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
9919                            0 /* TODO: Which userId? */);
9920
9921                    if (DEBUG_VERIFY) {
9922                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
9923                                + verification.toString() + " with " + pkgLite.verifiers.length
9924                                + " optional verifiers");
9925                    }
9926
9927                    final int verificationId = mPendingVerificationToken++;
9928
9929                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9930
9931                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
9932                            installerPackageName);
9933
9934                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
9935                            installFlags);
9936
9937                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
9938                            pkgLite.packageName);
9939
9940                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
9941                            pkgLite.versionCode);
9942
9943                    if (verificationParams != null) {
9944                        if (verificationParams.getVerificationURI() != null) {
9945                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
9946                                 verificationParams.getVerificationURI());
9947                        }
9948                        if (verificationParams.getOriginatingURI() != null) {
9949                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
9950                                  verificationParams.getOriginatingURI());
9951                        }
9952                        if (verificationParams.getReferrer() != null) {
9953                            verification.putExtra(Intent.EXTRA_REFERRER,
9954                                  verificationParams.getReferrer());
9955                        }
9956                        if (verificationParams.getOriginatingUid() >= 0) {
9957                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
9958                                  verificationParams.getOriginatingUid());
9959                        }
9960                        if (verificationParams.getInstallerUid() >= 0) {
9961                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
9962                                  verificationParams.getInstallerUid());
9963                        }
9964                    }
9965
9966                    final PackageVerificationState verificationState = new PackageVerificationState(
9967                            requiredUid, args);
9968
9969                    mPendingVerification.append(verificationId, verificationState);
9970
9971                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
9972                            receivers, verificationState);
9973
9974                    /*
9975                     * If any sufficient verifiers were listed in the package
9976                     * manifest, attempt to ask them.
9977                     */
9978                    if (sufficientVerifiers != null) {
9979                        final int N = sufficientVerifiers.size();
9980                        if (N == 0) {
9981                            Slog.i(TAG, "Additional verifiers required, but none installed.");
9982                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
9983                        } else {
9984                            for (int i = 0; i < N; i++) {
9985                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
9986
9987                                final Intent sufficientIntent = new Intent(verification);
9988                                sufficientIntent.setComponent(verifierComponent);
9989
9990                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
9991                            }
9992                        }
9993                    }
9994
9995                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
9996                            mRequiredVerifierPackage, receivers);
9997                    if (ret == PackageManager.INSTALL_SUCCEEDED
9998                            && mRequiredVerifierPackage != null) {
9999                        /*
10000                         * Send the intent to the required verification agent,
10001                         * but only start the verification timeout after the
10002                         * target BroadcastReceivers have run.
10003                         */
10004                        verification.setComponent(requiredVerifierComponent);
10005                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
10006                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10007                                new BroadcastReceiver() {
10008                                    @Override
10009                                    public void onReceive(Context context, Intent intent) {
10010                                        final Message msg = mHandler
10011                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
10012                                        msg.arg1 = verificationId;
10013                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
10014                                    }
10015                                }, null, 0, null, null);
10016
10017                        /*
10018                         * We don't want the copy to proceed until verification
10019                         * succeeds, so null out this field.
10020                         */
10021                        mArgs = null;
10022                    }
10023                } else {
10024                    /*
10025                     * No package verification is enabled, so immediately start
10026                     * the remote call to initiate copy using temporary file.
10027                     */
10028                    ret = args.copyApk(mContainerService, true);
10029                }
10030            }
10031
10032            mRet = ret;
10033        }
10034
10035        @Override
10036        void handleReturnCode() {
10037            // If mArgs is null, then MCS couldn't be reached. When it
10038            // reconnects, it will try again to install. At that point, this
10039            // will succeed.
10040            if (mArgs != null) {
10041                processPendingInstall(mArgs, mRet);
10042            }
10043        }
10044
10045        @Override
10046        void handleServiceError() {
10047            mArgs = createInstallArgs(this);
10048            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10049        }
10050
10051        public boolean isForwardLocked() {
10052            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10053        }
10054    }
10055
10056    /**
10057     * Used during creation of InstallArgs
10058     *
10059     * @param installFlags package installation flags
10060     * @return true if should be installed on external storage
10061     */
10062    private static boolean installOnExternalAsec(int installFlags) {
10063        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
10064            return false;
10065        }
10066        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
10067            return true;
10068        }
10069        return false;
10070    }
10071
10072    /**
10073     * Used during creation of InstallArgs
10074     *
10075     * @param installFlags package installation flags
10076     * @return true if should be installed as forward locked
10077     */
10078    private static boolean installForwardLocked(int installFlags) {
10079        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10080    }
10081
10082    private InstallArgs createInstallArgs(InstallParams params) {
10083        if (params.move != null) {
10084            return new MoveInstallArgs(params);
10085        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
10086            return new AsecInstallArgs(params);
10087        } else {
10088            return new FileInstallArgs(params);
10089        }
10090    }
10091
10092    /**
10093     * Create args that describe an existing installed package. Typically used
10094     * when cleaning up old installs, or used as a move source.
10095     */
10096    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
10097            String resourcePath, String[] instructionSets) {
10098        final boolean isInAsec;
10099        if (installOnExternalAsec(installFlags)) {
10100            /* Apps on SD card are always in ASEC containers. */
10101            isInAsec = true;
10102        } else if (installForwardLocked(installFlags)
10103                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
10104            /*
10105             * Forward-locked apps are only in ASEC containers if they're the
10106             * new style
10107             */
10108            isInAsec = true;
10109        } else {
10110            isInAsec = false;
10111        }
10112
10113        if (isInAsec) {
10114            return new AsecInstallArgs(codePath, instructionSets,
10115                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
10116        } else {
10117            return new FileInstallArgs(codePath, resourcePath, instructionSets);
10118        }
10119    }
10120
10121    static abstract class InstallArgs {
10122        /** @see InstallParams#origin */
10123        final OriginInfo origin;
10124        /** @see InstallParams#move */
10125        final MoveInfo move;
10126
10127        final IPackageInstallObserver2 observer;
10128        // Always refers to PackageManager flags only
10129        final int installFlags;
10130        final String installerPackageName;
10131        final String volumeUuid;
10132        final ManifestDigest manifestDigest;
10133        final UserHandle user;
10134        final String abiOverride;
10135
10136        // The list of instruction sets supported by this app. This is currently
10137        // only used during the rmdex() phase to clean up resources. We can get rid of this
10138        // if we move dex files under the common app path.
10139        /* nullable */ String[] instructionSets;
10140
10141        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10142                int installFlags, String installerPackageName, String volumeUuid,
10143                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
10144                String abiOverride) {
10145            this.origin = origin;
10146            this.move = move;
10147            this.installFlags = installFlags;
10148            this.observer = observer;
10149            this.installerPackageName = installerPackageName;
10150            this.volumeUuid = volumeUuid;
10151            this.manifestDigest = manifestDigest;
10152            this.user = user;
10153            this.instructionSets = instructionSets;
10154            this.abiOverride = abiOverride;
10155        }
10156
10157        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
10158        abstract int doPreInstall(int status);
10159
10160        /**
10161         * Rename package into final resting place. All paths on the given
10162         * scanned package should be updated to reflect the rename.
10163         */
10164        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
10165        abstract int doPostInstall(int status, int uid);
10166
10167        /** @see PackageSettingBase#codePathString */
10168        abstract String getCodePath();
10169        /** @see PackageSettingBase#resourcePathString */
10170        abstract String getResourcePath();
10171
10172        // Need installer lock especially for dex file removal.
10173        abstract void cleanUpResourcesLI();
10174        abstract boolean doPostDeleteLI(boolean delete);
10175
10176        /**
10177         * Called before the source arguments are copied. This is used mostly
10178         * for MoveParams when it needs to read the source file to put it in the
10179         * destination.
10180         */
10181        int doPreCopy() {
10182            return PackageManager.INSTALL_SUCCEEDED;
10183        }
10184
10185        /**
10186         * Called after the source arguments are copied. This is used mostly for
10187         * MoveParams when it needs to read the source file to put it in the
10188         * destination.
10189         *
10190         * @return
10191         */
10192        int doPostCopy(int uid) {
10193            return PackageManager.INSTALL_SUCCEEDED;
10194        }
10195
10196        protected boolean isFwdLocked() {
10197            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10198        }
10199
10200        protected boolean isExternalAsec() {
10201            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10202        }
10203
10204        UserHandle getUser() {
10205            return user;
10206        }
10207    }
10208
10209    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
10210        if (!allCodePaths.isEmpty()) {
10211            if (instructionSets == null) {
10212                throw new IllegalStateException("instructionSet == null");
10213            }
10214            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
10215            for (String codePath : allCodePaths) {
10216                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
10217                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
10218                    if (retCode < 0) {
10219                        Slog.w(TAG, "Couldn't remove dex file for package: "
10220                                + " at location " + codePath + ", retcode=" + retCode);
10221                        // we don't consider this to be a failure of the core package deletion
10222                    }
10223                }
10224            }
10225        }
10226    }
10227
10228    /**
10229     * Logic to handle installation of non-ASEC applications, including copying
10230     * and renaming logic.
10231     */
10232    class FileInstallArgs extends InstallArgs {
10233        private File codeFile;
10234        private File resourceFile;
10235
10236        // Example topology:
10237        // /data/app/com.example/base.apk
10238        // /data/app/com.example/split_foo.apk
10239        // /data/app/com.example/lib/arm/libfoo.so
10240        // /data/app/com.example/lib/arm64/libfoo.so
10241        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
10242
10243        /** New install */
10244        FileInstallArgs(InstallParams params) {
10245            super(params.origin, params.move, params.observer, params.installFlags,
10246                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10247                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10248            if (isFwdLocked()) {
10249                throw new IllegalArgumentException("Forward locking only supported in ASEC");
10250            }
10251        }
10252
10253        /** Existing install */
10254        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
10255            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
10256                    null);
10257            this.codeFile = (codePath != null) ? new File(codePath) : null;
10258            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
10259        }
10260
10261        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10262            if (origin.staged) {
10263                Slog.d(TAG, origin.file + " already staged; skipping copy");
10264                codeFile = origin.file;
10265                resourceFile = origin.file;
10266                return PackageManager.INSTALL_SUCCEEDED;
10267            }
10268
10269            try {
10270                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
10271                codeFile = tempDir;
10272                resourceFile = tempDir;
10273            } catch (IOException e) {
10274                Slog.w(TAG, "Failed to create copy file: " + e);
10275                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10276            }
10277
10278            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
10279                @Override
10280                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
10281                    if (!FileUtils.isValidExtFilename(name)) {
10282                        throw new IllegalArgumentException("Invalid filename: " + name);
10283                    }
10284                    try {
10285                        final File file = new File(codeFile, name);
10286                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
10287                                O_RDWR | O_CREAT, 0644);
10288                        Os.chmod(file.getAbsolutePath(), 0644);
10289                        return new ParcelFileDescriptor(fd);
10290                    } catch (ErrnoException e) {
10291                        throw new RemoteException("Failed to open: " + e.getMessage());
10292                    }
10293                }
10294            };
10295
10296            int ret = PackageManager.INSTALL_SUCCEEDED;
10297            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
10298            if (ret != PackageManager.INSTALL_SUCCEEDED) {
10299                Slog.e(TAG, "Failed to copy package");
10300                return ret;
10301            }
10302
10303            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
10304            NativeLibraryHelper.Handle handle = null;
10305            try {
10306                handle = NativeLibraryHelper.Handle.create(codeFile);
10307                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
10308                        abiOverride);
10309            } catch (IOException e) {
10310                Slog.e(TAG, "Copying native libraries failed", e);
10311                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10312            } finally {
10313                IoUtils.closeQuietly(handle);
10314            }
10315
10316            return ret;
10317        }
10318
10319        int doPreInstall(int status) {
10320            if (status != PackageManager.INSTALL_SUCCEEDED) {
10321                cleanUp();
10322            }
10323            return status;
10324        }
10325
10326        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10327            if (status != PackageManager.INSTALL_SUCCEEDED) {
10328                cleanUp();
10329                return false;
10330            }
10331
10332            final File targetDir = codeFile.getParentFile();
10333            final File beforeCodeFile = codeFile;
10334            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
10335
10336            Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
10337            try {
10338                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
10339            } catch (ErrnoException e) {
10340                Slog.d(TAG, "Failed to rename", e);
10341                return false;
10342            }
10343
10344            if (!SELinux.restoreconRecursive(afterCodeFile)) {
10345                Slog.d(TAG, "Failed to restorecon");
10346                return false;
10347            }
10348
10349            // Reflect the rename internally
10350            codeFile = afterCodeFile;
10351            resourceFile = afterCodeFile;
10352
10353            // Reflect the rename in scanned details
10354            pkg.codePath = afterCodeFile.getAbsolutePath();
10355            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10356                    pkg.baseCodePath);
10357            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10358                    pkg.splitCodePaths);
10359
10360            // Reflect the rename in app info
10361            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10362            pkg.applicationInfo.setCodePath(pkg.codePath);
10363            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10364            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10365            pkg.applicationInfo.setResourcePath(pkg.codePath);
10366            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10367            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10368
10369            return true;
10370        }
10371
10372        int doPostInstall(int status, int uid) {
10373            if (status != PackageManager.INSTALL_SUCCEEDED) {
10374                cleanUp();
10375            }
10376            return status;
10377        }
10378
10379        @Override
10380        String getCodePath() {
10381            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
10382        }
10383
10384        @Override
10385        String getResourcePath() {
10386            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
10387        }
10388
10389        private boolean cleanUp() {
10390            if (codeFile == null || !codeFile.exists()) {
10391                return false;
10392            }
10393
10394            if (codeFile.isDirectory()) {
10395                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
10396            } else {
10397                codeFile.delete();
10398            }
10399
10400            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
10401                resourceFile.delete();
10402            }
10403
10404            return true;
10405        }
10406
10407        void cleanUpResourcesLI() {
10408            // Try enumerating all code paths before deleting
10409            List<String> allCodePaths = Collections.EMPTY_LIST;
10410            if (codeFile != null && codeFile.exists()) {
10411                try {
10412                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
10413                    allCodePaths = pkg.getAllCodePaths();
10414                } catch (PackageParserException e) {
10415                    // Ignored; we tried our best
10416                }
10417            }
10418
10419            cleanUp();
10420            removeDexFiles(allCodePaths, instructionSets);
10421        }
10422
10423        boolean doPostDeleteLI(boolean delete) {
10424            // XXX err, shouldn't we respect the delete flag?
10425            cleanUpResourcesLI();
10426            return true;
10427        }
10428    }
10429
10430    private boolean isAsecExternal(String cid) {
10431        final String asecPath = PackageHelper.getSdFilesystem(cid);
10432        return !asecPath.startsWith(mAsecInternalPath);
10433    }
10434
10435    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
10436            PackageManagerException {
10437        if (copyRet < 0) {
10438            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
10439                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
10440                throw new PackageManagerException(copyRet, message);
10441            }
10442        }
10443    }
10444
10445    /**
10446     * Extract the MountService "container ID" from the full code path of an
10447     * .apk.
10448     */
10449    static String cidFromCodePath(String fullCodePath) {
10450        int eidx = fullCodePath.lastIndexOf("/");
10451        String subStr1 = fullCodePath.substring(0, eidx);
10452        int sidx = subStr1.lastIndexOf("/");
10453        return subStr1.substring(sidx+1, eidx);
10454    }
10455
10456    /**
10457     * Logic to handle installation of ASEC applications, including copying and
10458     * renaming logic.
10459     */
10460    class AsecInstallArgs extends InstallArgs {
10461        static final String RES_FILE_NAME = "pkg.apk";
10462        static final String PUBLIC_RES_FILE_NAME = "res.zip";
10463
10464        String cid;
10465        String packagePath;
10466        String resourcePath;
10467
10468        /** New install */
10469        AsecInstallArgs(InstallParams params) {
10470            super(params.origin, params.move, params.observer, params.installFlags,
10471                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10472                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10473        }
10474
10475        /** Existing install */
10476        AsecInstallArgs(String fullCodePath, String[] instructionSets,
10477                        boolean isExternal, boolean isForwardLocked) {
10478            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
10479                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
10480                    instructionSets, null);
10481            // Hackily pretend we're still looking at a full code path
10482            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
10483                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
10484            }
10485
10486            // Extract cid from fullCodePath
10487            int eidx = fullCodePath.lastIndexOf("/");
10488            String subStr1 = fullCodePath.substring(0, eidx);
10489            int sidx = subStr1.lastIndexOf("/");
10490            cid = subStr1.substring(sidx+1, eidx);
10491            setMountPath(subStr1);
10492        }
10493
10494        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
10495            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
10496                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
10497                    instructionSets, null);
10498            this.cid = cid;
10499            setMountPath(PackageHelper.getSdDir(cid));
10500        }
10501
10502        void createCopyFile() {
10503            cid = mInstallerService.allocateExternalStageCidLegacy();
10504        }
10505
10506        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10507            if (origin.staged) {
10508                Slog.d(TAG, origin.cid + " already staged; skipping copy");
10509                cid = origin.cid;
10510                setMountPath(PackageHelper.getSdDir(cid));
10511                return PackageManager.INSTALL_SUCCEEDED;
10512            }
10513
10514            if (temp) {
10515                createCopyFile();
10516            } else {
10517                /*
10518                 * Pre-emptively destroy the container since it's destroyed if
10519                 * copying fails due to it existing anyway.
10520                 */
10521                PackageHelper.destroySdDir(cid);
10522            }
10523
10524            final String newMountPath = imcs.copyPackageToContainer(
10525                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
10526                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
10527
10528            if (newMountPath != null) {
10529                setMountPath(newMountPath);
10530                return PackageManager.INSTALL_SUCCEEDED;
10531            } else {
10532                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10533            }
10534        }
10535
10536        @Override
10537        String getCodePath() {
10538            return packagePath;
10539        }
10540
10541        @Override
10542        String getResourcePath() {
10543            return resourcePath;
10544        }
10545
10546        int doPreInstall(int status) {
10547            if (status != PackageManager.INSTALL_SUCCEEDED) {
10548                // Destroy container
10549                PackageHelper.destroySdDir(cid);
10550            } else {
10551                boolean mounted = PackageHelper.isContainerMounted(cid);
10552                if (!mounted) {
10553                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
10554                            Process.SYSTEM_UID);
10555                    if (newMountPath != null) {
10556                        setMountPath(newMountPath);
10557                    } else {
10558                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10559                    }
10560                }
10561            }
10562            return status;
10563        }
10564
10565        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10566            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
10567            String newMountPath = null;
10568            if (PackageHelper.isContainerMounted(cid)) {
10569                // Unmount the container
10570                if (!PackageHelper.unMountSdDir(cid)) {
10571                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
10572                    return false;
10573                }
10574            }
10575            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
10576                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
10577                        " which might be stale. Will try to clean up.");
10578                // Clean up the stale container and proceed to recreate.
10579                if (!PackageHelper.destroySdDir(newCacheId)) {
10580                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
10581                    return false;
10582                }
10583                // Successfully cleaned up stale container. Try to rename again.
10584                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
10585                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
10586                            + " inspite of cleaning it up.");
10587                    return false;
10588                }
10589            }
10590            if (!PackageHelper.isContainerMounted(newCacheId)) {
10591                Slog.w(TAG, "Mounting container " + newCacheId);
10592                newMountPath = PackageHelper.mountSdDir(newCacheId,
10593                        getEncryptKey(), Process.SYSTEM_UID);
10594            } else {
10595                newMountPath = PackageHelper.getSdDir(newCacheId);
10596            }
10597            if (newMountPath == null) {
10598                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
10599                return false;
10600            }
10601            Log.i(TAG, "Succesfully renamed " + cid +
10602                    " to " + newCacheId +
10603                    " at new path: " + newMountPath);
10604            cid = newCacheId;
10605
10606            final File beforeCodeFile = new File(packagePath);
10607            setMountPath(newMountPath);
10608            final File afterCodeFile = new File(packagePath);
10609
10610            // Reflect the rename in scanned details
10611            pkg.codePath = afterCodeFile.getAbsolutePath();
10612            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10613                    pkg.baseCodePath);
10614            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10615                    pkg.splitCodePaths);
10616
10617            // Reflect the rename in app info
10618            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10619            pkg.applicationInfo.setCodePath(pkg.codePath);
10620            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10621            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10622            pkg.applicationInfo.setResourcePath(pkg.codePath);
10623            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10624            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10625
10626            return true;
10627        }
10628
10629        private void setMountPath(String mountPath) {
10630            final File mountFile = new File(mountPath);
10631
10632            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
10633            if (monolithicFile.exists()) {
10634                packagePath = monolithicFile.getAbsolutePath();
10635                if (isFwdLocked()) {
10636                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
10637                } else {
10638                    resourcePath = packagePath;
10639                }
10640            } else {
10641                packagePath = mountFile.getAbsolutePath();
10642                resourcePath = packagePath;
10643            }
10644        }
10645
10646        int doPostInstall(int status, int uid) {
10647            if (status != PackageManager.INSTALL_SUCCEEDED) {
10648                cleanUp();
10649            } else {
10650                final int groupOwner;
10651                final String protectedFile;
10652                if (isFwdLocked()) {
10653                    groupOwner = UserHandle.getSharedAppGid(uid);
10654                    protectedFile = RES_FILE_NAME;
10655                } else {
10656                    groupOwner = -1;
10657                    protectedFile = null;
10658                }
10659
10660                if (uid < Process.FIRST_APPLICATION_UID
10661                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
10662                    Slog.e(TAG, "Failed to finalize " + cid);
10663                    PackageHelper.destroySdDir(cid);
10664                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10665                }
10666
10667                boolean mounted = PackageHelper.isContainerMounted(cid);
10668                if (!mounted) {
10669                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
10670                }
10671            }
10672            return status;
10673        }
10674
10675        private void cleanUp() {
10676            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
10677
10678            // Destroy secure container
10679            PackageHelper.destroySdDir(cid);
10680        }
10681
10682        private List<String> getAllCodePaths() {
10683            final File codeFile = new File(getCodePath());
10684            if (codeFile != null && codeFile.exists()) {
10685                try {
10686                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
10687                    return pkg.getAllCodePaths();
10688                } catch (PackageParserException e) {
10689                    // Ignored; we tried our best
10690                }
10691            }
10692            return Collections.EMPTY_LIST;
10693        }
10694
10695        void cleanUpResourcesLI() {
10696            // Enumerate all code paths before deleting
10697            cleanUpResourcesLI(getAllCodePaths());
10698        }
10699
10700        private void cleanUpResourcesLI(List<String> allCodePaths) {
10701            cleanUp();
10702            removeDexFiles(allCodePaths, instructionSets);
10703        }
10704
10705        String getPackageName() {
10706            return getAsecPackageName(cid);
10707        }
10708
10709        boolean doPostDeleteLI(boolean delete) {
10710            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
10711            final List<String> allCodePaths = getAllCodePaths();
10712            boolean mounted = PackageHelper.isContainerMounted(cid);
10713            if (mounted) {
10714                // Unmount first
10715                if (PackageHelper.unMountSdDir(cid)) {
10716                    mounted = false;
10717                }
10718            }
10719            if (!mounted && delete) {
10720                cleanUpResourcesLI(allCodePaths);
10721            }
10722            return !mounted;
10723        }
10724
10725        @Override
10726        int doPreCopy() {
10727            if (isFwdLocked()) {
10728                if (!PackageHelper.fixSdPermissions(cid,
10729                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
10730                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10731                }
10732            }
10733
10734            return PackageManager.INSTALL_SUCCEEDED;
10735        }
10736
10737        @Override
10738        int doPostCopy(int uid) {
10739            if (isFwdLocked()) {
10740                if (uid < Process.FIRST_APPLICATION_UID
10741                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
10742                                RES_FILE_NAME)) {
10743                    Slog.e(TAG, "Failed to finalize " + cid);
10744                    PackageHelper.destroySdDir(cid);
10745                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10746                }
10747            }
10748
10749            return PackageManager.INSTALL_SUCCEEDED;
10750        }
10751    }
10752
10753    /**
10754     * Logic to handle movement of existing installed applications.
10755     */
10756    class MoveInstallArgs extends InstallArgs {
10757        private File codeFile;
10758        private File resourceFile;
10759
10760        /** New install */
10761        MoveInstallArgs(InstallParams params) {
10762            super(params.origin, params.move, params.observer, params.installFlags,
10763                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10764                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10765        }
10766
10767        int copyApk(IMediaContainerService imcs, boolean temp) {
10768            Slog.d(TAG, "Moving " + move.packageName + " from " + move.fromUuid + " to "
10769                    + move.toUuid);
10770            synchronized (mInstaller) {
10771                if (mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
10772                        move.dataAppName, move.appId, move.seinfo) != 0) {
10773                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10774                }
10775            }
10776
10777            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
10778            resourceFile = codeFile;
10779            Slog.d(TAG, "codeFile after move is " + codeFile);
10780
10781            return PackageManager.INSTALL_SUCCEEDED;
10782        }
10783
10784        int doPreInstall(int status) {
10785            if (status != PackageManager.INSTALL_SUCCEEDED) {
10786                cleanUp();
10787            }
10788            return status;
10789        }
10790
10791        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10792            if (status != PackageManager.INSTALL_SUCCEEDED) {
10793                cleanUp();
10794                return false;
10795            }
10796
10797            // Reflect the move in app info
10798            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10799            pkg.applicationInfo.setCodePath(pkg.codePath);
10800            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10801            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10802            pkg.applicationInfo.setResourcePath(pkg.codePath);
10803            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10804            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10805
10806            return true;
10807        }
10808
10809        int doPostInstall(int status, int uid) {
10810            if (status != PackageManager.INSTALL_SUCCEEDED) {
10811                cleanUp();
10812            }
10813            return status;
10814        }
10815
10816        @Override
10817        String getCodePath() {
10818            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
10819        }
10820
10821        @Override
10822        String getResourcePath() {
10823            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
10824        }
10825
10826        private boolean cleanUp() {
10827            if (codeFile == null || !codeFile.exists()) {
10828                return false;
10829            }
10830
10831            if (codeFile.isDirectory()) {
10832                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
10833            } else {
10834                codeFile.delete();
10835            }
10836
10837            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
10838                resourceFile.delete();
10839            }
10840
10841            return true;
10842        }
10843
10844        void cleanUpResourcesLI() {
10845            cleanUp();
10846        }
10847
10848        boolean doPostDeleteLI(boolean delete) {
10849            // XXX err, shouldn't we respect the delete flag?
10850            cleanUpResourcesLI();
10851            return true;
10852        }
10853    }
10854
10855    static String getAsecPackageName(String packageCid) {
10856        int idx = packageCid.lastIndexOf("-");
10857        if (idx == -1) {
10858            return packageCid;
10859        }
10860        return packageCid.substring(0, idx);
10861    }
10862
10863    // Utility method used to create code paths based on package name and available index.
10864    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
10865        String idxStr = "";
10866        int idx = 1;
10867        // Fall back to default value of idx=1 if prefix is not
10868        // part of oldCodePath
10869        if (oldCodePath != null) {
10870            String subStr = oldCodePath;
10871            // Drop the suffix right away
10872            if (suffix != null && subStr.endsWith(suffix)) {
10873                subStr = subStr.substring(0, subStr.length() - suffix.length());
10874            }
10875            // If oldCodePath already contains prefix find out the
10876            // ending index to either increment or decrement.
10877            int sidx = subStr.lastIndexOf(prefix);
10878            if (sidx != -1) {
10879                subStr = subStr.substring(sidx + prefix.length());
10880                if (subStr != null) {
10881                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
10882                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
10883                    }
10884                    try {
10885                        idx = Integer.parseInt(subStr);
10886                        if (idx <= 1) {
10887                            idx++;
10888                        } else {
10889                            idx--;
10890                        }
10891                    } catch(NumberFormatException e) {
10892                    }
10893                }
10894            }
10895        }
10896        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
10897        return prefix + idxStr;
10898    }
10899
10900    private File getNextCodePath(File targetDir, String packageName) {
10901        int suffix = 1;
10902        File result;
10903        do {
10904            result = new File(targetDir, packageName + "-" + suffix);
10905            suffix++;
10906        } while (result.exists());
10907        return result;
10908    }
10909
10910    // Utility method that returns the relative package path with respect
10911    // to the installation directory. Like say for /data/data/com.test-1.apk
10912    // string com.test-1 is returned.
10913    static String deriveCodePathName(String codePath) {
10914        if (codePath == null) {
10915            return null;
10916        }
10917        final File codeFile = new File(codePath);
10918        final String name = codeFile.getName();
10919        if (codeFile.isDirectory()) {
10920            return name;
10921        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
10922            final int lastDot = name.lastIndexOf('.');
10923            return name.substring(0, lastDot);
10924        } else {
10925            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
10926            return null;
10927        }
10928    }
10929
10930    class PackageInstalledInfo {
10931        String name;
10932        int uid;
10933        // The set of users that originally had this package installed.
10934        int[] origUsers;
10935        // The set of users that now have this package installed.
10936        int[] newUsers;
10937        PackageParser.Package pkg;
10938        int returnCode;
10939        String returnMsg;
10940        PackageRemovedInfo removedInfo;
10941
10942        public void setError(int code, String msg) {
10943            returnCode = code;
10944            returnMsg = msg;
10945            Slog.w(TAG, msg);
10946        }
10947
10948        public void setError(String msg, PackageParserException e) {
10949            returnCode = e.error;
10950            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
10951            Slog.w(TAG, msg, e);
10952        }
10953
10954        public void setError(String msg, PackageManagerException e) {
10955            returnCode = e.error;
10956            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
10957            Slog.w(TAG, msg, e);
10958        }
10959
10960        // In some error cases we want to convey more info back to the observer
10961        String origPackage;
10962        String origPermission;
10963    }
10964
10965    /*
10966     * Install a non-existing package.
10967     */
10968    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
10969            UserHandle user, String installerPackageName, String volumeUuid,
10970            PackageInstalledInfo res) {
10971        // Remember this for later, in case we need to rollback this install
10972        String pkgName = pkg.packageName;
10973
10974        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
10975        final boolean dataDirExists = PackageManager.getDataDirForUser(volumeUuid, pkgName,
10976                UserHandle.USER_OWNER).exists();
10977        synchronized(mPackages) {
10978            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
10979                // A package with the same name is already installed, though
10980                // it has been renamed to an older name.  The package we
10981                // are trying to install should be installed as an update to
10982                // the existing one, but that has not been requested, so bail.
10983                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
10984                        + " without first uninstalling package running as "
10985                        + mSettings.mRenamedPackages.get(pkgName));
10986                return;
10987            }
10988            if (mPackages.containsKey(pkgName)) {
10989                // Don't allow installation over an existing package with the same name.
10990                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
10991                        + " without first uninstalling.");
10992                return;
10993            }
10994        }
10995
10996        try {
10997            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
10998                    System.currentTimeMillis(), user);
10999
11000            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
11001            // delete the partially installed application. the data directory will have to be
11002            // restored if it was already existing
11003            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11004                // remove package from internal structures.  Note that we want deletePackageX to
11005                // delete the package data and cache directories that it created in
11006                // scanPackageLocked, unless those directories existed before we even tried to
11007                // install.
11008                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
11009                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
11010                                res.removedInfo, true);
11011            }
11012
11013        } catch (PackageManagerException e) {
11014            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11015        }
11016    }
11017
11018    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
11019        // Upgrade keysets are being used.  Determine if new package has a superset of the
11020        // required keys.
11021        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
11022        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11023        for (int i = 0; i < upgradeKeySets.length; i++) {
11024            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
11025            if (newPkg.mSigningKeys.containsAll(upgradeSet)) {
11026                return true;
11027            }
11028        }
11029        return false;
11030    }
11031
11032    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11033            UserHandle user, String installerPackageName, String volumeUuid,
11034            PackageInstalledInfo res) {
11035        final PackageParser.Package oldPackage;
11036        final String pkgName = pkg.packageName;
11037        final int[] allUsers;
11038        final boolean[] perUserInstalled;
11039        final boolean weFroze;
11040
11041        // First find the old package info and check signatures
11042        synchronized(mPackages) {
11043            oldPackage = mPackages.get(pkgName);
11044            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
11045            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11046            if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
11047                // default to original signature matching
11048                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
11049                    != PackageManager.SIGNATURE_MATCH) {
11050                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11051                            "New package has a different signature: " + pkgName);
11052                    return;
11053                }
11054            } else {
11055                if(!checkUpgradeKeySetLP(ps, pkg)) {
11056                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11057                            "New package not signed by keys specified by upgrade-keysets: "
11058                            + pkgName);
11059                    return;
11060                }
11061            }
11062
11063            // In case of rollback, remember per-user/profile install state
11064            allUsers = sUserManager.getUserIds();
11065            perUserInstalled = new boolean[allUsers.length];
11066            for (int i = 0; i < allUsers.length; i++) {
11067                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11068            }
11069
11070            // Mark the app as frozen to prevent launching during the upgrade
11071            // process, and then kill all running instances
11072            if (!ps.frozen) {
11073                ps.frozen = true;
11074                weFroze = true;
11075            } else {
11076                weFroze = false;
11077            }
11078        }
11079
11080        // Now that we're guarded by frozen state, kill app during upgrade
11081        killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg");
11082
11083        try {
11084            boolean sysPkg = (isSystemApp(oldPackage));
11085            if (sysPkg) {
11086                replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11087                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11088            } else {
11089                replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11090                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11091            }
11092        } finally {
11093            // Regardless of success or failure of upgrade steps above, always
11094            // unfreeze the package if we froze it
11095            if (weFroze) {
11096                unfreezePackage(pkgName);
11097            }
11098        }
11099    }
11100
11101    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
11102            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11103            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11104            String volumeUuid, PackageInstalledInfo res) {
11105        String pkgName = deletedPackage.packageName;
11106        boolean deletedPkg = true;
11107        boolean updatedSettings = false;
11108
11109        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
11110                + deletedPackage);
11111        long origUpdateTime;
11112        if (pkg.mExtras != null) {
11113            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
11114        } else {
11115            origUpdateTime = 0;
11116        }
11117
11118        // First delete the existing package while retaining the data directory
11119        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
11120                res.removedInfo, true)) {
11121            // If the existing package wasn't successfully deleted
11122            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
11123            deletedPkg = false;
11124        } else {
11125            // Successfully deleted the old package; proceed with replace.
11126
11127            // If deleted package lived in a container, give users a chance to
11128            // relinquish resources before killing.
11129            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
11130                if (DEBUG_INSTALL) {
11131                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
11132                }
11133                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
11134                final ArrayList<String> pkgList = new ArrayList<String>(1);
11135                pkgList.add(deletedPackage.applicationInfo.packageName);
11136                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
11137            }
11138
11139            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
11140            try {
11141                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
11142                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
11143                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11144                        perUserInstalled, res, user);
11145                updatedSettings = true;
11146            } catch (PackageManagerException e) {
11147                res.setError("Package couldn't be installed in " + pkg.codePath, e);
11148            }
11149        }
11150
11151        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11152            // remove package from internal structures.  Note that we want deletePackageX to
11153            // delete the package data and cache directories that it created in
11154            // scanPackageLocked, unless those directories existed before we even tried to
11155            // install.
11156            if(updatedSettings) {
11157                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
11158                deletePackageLI(
11159                        pkgName, null, true, allUsers, perUserInstalled,
11160                        PackageManager.DELETE_KEEP_DATA,
11161                                res.removedInfo, true);
11162            }
11163            // Since we failed to install the new package we need to restore the old
11164            // package that we deleted.
11165            if (deletedPkg) {
11166                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
11167                File restoreFile = new File(deletedPackage.codePath);
11168                // Parse old package
11169                boolean oldExternal = isExternal(deletedPackage);
11170                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
11171                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
11172                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11173                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
11174                try {
11175                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
11176                } catch (PackageManagerException e) {
11177                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
11178                            + e.getMessage());
11179                    return;
11180                }
11181                // Restore of old package succeeded. Update permissions.
11182                // writer
11183                synchronized (mPackages) {
11184                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
11185                            UPDATE_PERMISSIONS_ALL);
11186                    // can downgrade to reader
11187                    mSettings.writeLPr();
11188                }
11189                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
11190            }
11191        }
11192    }
11193
11194    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
11195            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11196            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11197            String volumeUuid, PackageInstalledInfo res) {
11198        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
11199                + ", old=" + deletedPackage);
11200        boolean disabledSystem = false;
11201        boolean updatedSettings = false;
11202        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
11203        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
11204                != 0) {
11205            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11206        }
11207        String packageName = deletedPackage.packageName;
11208        if (packageName == null) {
11209            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11210                    "Attempt to delete null packageName.");
11211            return;
11212        }
11213        PackageParser.Package oldPkg;
11214        PackageSetting oldPkgSetting;
11215        // reader
11216        synchronized (mPackages) {
11217            oldPkg = mPackages.get(packageName);
11218            oldPkgSetting = mSettings.mPackages.get(packageName);
11219            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
11220                    (oldPkgSetting == null)) {
11221                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11222                        "Couldn't find package:" + packageName + " information");
11223                return;
11224            }
11225        }
11226
11227        res.removedInfo.uid = oldPkg.applicationInfo.uid;
11228        res.removedInfo.removedPackage = packageName;
11229        // Remove existing system package
11230        removePackageLI(oldPkgSetting, true);
11231        // writer
11232        synchronized (mPackages) {
11233            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
11234            if (!disabledSystem && deletedPackage != null) {
11235                // We didn't need to disable the .apk as a current system package,
11236                // which means we are replacing another update that is already
11237                // installed.  We need to make sure to delete the older one's .apk.
11238                res.removedInfo.args = createInstallArgsForExisting(0,
11239                        deletedPackage.applicationInfo.getCodePath(),
11240                        deletedPackage.applicationInfo.getResourcePath(),
11241                        getAppDexInstructionSets(deletedPackage.applicationInfo));
11242            } else {
11243                res.removedInfo.args = null;
11244            }
11245        }
11246
11247        // Successfully disabled the old package. Now proceed with re-installation
11248        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
11249
11250        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11251        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
11252
11253        PackageParser.Package newPackage = null;
11254        try {
11255            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
11256            if (newPackage.mExtras != null) {
11257                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
11258                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
11259                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
11260
11261                // is the update attempting to change shared user? that isn't going to work...
11262                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
11263                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
11264                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
11265                            + " to " + newPkgSetting.sharedUser);
11266                    updatedSettings = true;
11267                }
11268            }
11269
11270            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11271                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11272                        perUserInstalled, res, user);
11273                updatedSettings = true;
11274            }
11275
11276        } catch (PackageManagerException e) {
11277            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11278        }
11279
11280        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11281            // Re installation failed. Restore old information
11282            // Remove new pkg information
11283            if (newPackage != null) {
11284                removeInstalledPackageLI(newPackage, true);
11285            }
11286            // Add back the old system package
11287            try {
11288                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
11289            } catch (PackageManagerException e) {
11290                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
11291            }
11292            // Restore the old system information in Settings
11293            synchronized (mPackages) {
11294                if (disabledSystem) {
11295                    mSettings.enableSystemPackageLPw(packageName);
11296                }
11297                if (updatedSettings) {
11298                    mSettings.setInstallerPackageName(packageName,
11299                            oldPkgSetting.installerPackageName);
11300                }
11301                mSettings.writeLPr();
11302            }
11303        }
11304    }
11305
11306    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
11307            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
11308            UserHandle user) {
11309        String pkgName = newPackage.packageName;
11310        synchronized (mPackages) {
11311            //write settings. the installStatus will be incomplete at this stage.
11312            //note that the new package setting would have already been
11313            //added to mPackages. It hasn't been persisted yet.
11314            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
11315            mSettings.writeLPr();
11316        }
11317
11318        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
11319
11320        synchronized (mPackages) {
11321            updatePermissionsLPw(newPackage.packageName, newPackage,
11322                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
11323                            ? UPDATE_PERMISSIONS_ALL : 0));
11324            // For system-bundled packages, we assume that installing an upgraded version
11325            // of the package implies that the user actually wants to run that new code,
11326            // so we enable the package.
11327            PackageSetting ps = mSettings.mPackages.get(pkgName);
11328            if (ps != null) {
11329                if (isSystemApp(newPackage)) {
11330                    // NB: implicit assumption that system package upgrades apply to all users
11331                    if (DEBUG_INSTALL) {
11332                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
11333                    }
11334                    if (res.origUsers != null) {
11335                        for (int userHandle : res.origUsers) {
11336                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
11337                                    userHandle, installerPackageName);
11338                        }
11339                    }
11340                    // Also convey the prior install/uninstall state
11341                    if (allUsers != null && perUserInstalled != null) {
11342                        for (int i = 0; i < allUsers.length; i++) {
11343                            if (DEBUG_INSTALL) {
11344                                Slog.d(TAG, "    user " + allUsers[i]
11345                                        + " => " + perUserInstalled[i]);
11346                            }
11347                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
11348                        }
11349                        // these install state changes will be persisted in the
11350                        // upcoming call to mSettings.writeLPr().
11351                    }
11352                }
11353                // It's implied that when a user requests installation, they want the app to be
11354                // installed and enabled.
11355                int userId = user.getIdentifier();
11356                if (userId != UserHandle.USER_ALL) {
11357                    ps.setInstalled(true, userId);
11358                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
11359                }
11360            }
11361            res.name = pkgName;
11362            res.uid = newPackage.applicationInfo.uid;
11363            res.pkg = newPackage;
11364            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
11365            mSettings.setInstallerPackageName(pkgName, installerPackageName);
11366            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11367            //to update install status
11368            mSettings.writeLPr();
11369        }
11370    }
11371
11372    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
11373        final int installFlags = args.installFlags;
11374        final String installerPackageName = args.installerPackageName;
11375        final String volumeUuid = args.volumeUuid;
11376        final File tmpPackageFile = new File(args.getCodePath());
11377        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
11378        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
11379                || (args.volumeUuid != null));
11380        boolean replace = false;
11381        int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE;
11382        // Result object to be returned
11383        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11384
11385        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
11386        // Retrieve PackageSettings and parse package
11387        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
11388                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
11389                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11390        PackageParser pp = new PackageParser();
11391        pp.setSeparateProcesses(mSeparateProcesses);
11392        pp.setDisplayMetrics(mMetrics);
11393
11394        final PackageParser.Package pkg;
11395        try {
11396            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
11397        } catch (PackageParserException e) {
11398            res.setError("Failed parse during installPackageLI", e);
11399            return;
11400        }
11401
11402        // Mark that we have an install time CPU ABI override.
11403        pkg.cpuAbiOverride = args.abiOverride;
11404
11405        String pkgName = res.name = pkg.packageName;
11406        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
11407            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
11408                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
11409                return;
11410            }
11411        }
11412
11413        try {
11414            pp.collectCertificates(pkg, parseFlags);
11415            pp.collectManifestDigest(pkg);
11416        } catch (PackageParserException e) {
11417            res.setError("Failed collect during installPackageLI", e);
11418            return;
11419        }
11420
11421        /* If the installer passed in a manifest digest, compare it now. */
11422        if (args.manifestDigest != null) {
11423            if (DEBUG_INSTALL) {
11424                final String parsedManifest = pkg.manifestDigest == null ? "null"
11425                        : pkg.manifestDigest.toString();
11426                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
11427                        + parsedManifest);
11428            }
11429
11430            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
11431                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
11432                return;
11433            }
11434        } else if (DEBUG_INSTALL) {
11435            final String parsedManifest = pkg.manifestDigest == null
11436                    ? "null" : pkg.manifestDigest.toString();
11437            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
11438        }
11439
11440        // Get rid of all references to package scan path via parser.
11441        pp = null;
11442        String oldCodePath = null;
11443        boolean systemApp = false;
11444        synchronized (mPackages) {
11445            // Check if installing already existing package
11446            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
11447                String oldName = mSettings.mRenamedPackages.get(pkgName);
11448                if (pkg.mOriginalPackages != null
11449                        && pkg.mOriginalPackages.contains(oldName)
11450                        && mPackages.containsKey(oldName)) {
11451                    // This package is derived from an original package,
11452                    // and this device has been updating from that original
11453                    // name.  We must continue using the original name, so
11454                    // rename the new package here.
11455                    pkg.setPackageName(oldName);
11456                    pkgName = pkg.packageName;
11457                    replace = true;
11458                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
11459                            + oldName + " pkgName=" + pkgName);
11460                } else if (mPackages.containsKey(pkgName)) {
11461                    // This package, under its official name, already exists
11462                    // on the device; we should replace it.
11463                    replace = true;
11464                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
11465                }
11466
11467                // Prevent apps opting out from runtime permissions
11468                if (replace) {
11469                    PackageParser.Package oldPackage = mPackages.get(pkgName);
11470                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
11471                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
11472                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
11473                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
11474                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
11475                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
11476                                        + " doesn't support runtime permissions but the old"
11477                                        + " target SDK " + oldTargetSdk + " does.");
11478                        return;
11479                    }
11480                }
11481            }
11482
11483            PackageSetting ps = mSettings.mPackages.get(pkgName);
11484            if (ps != null) {
11485                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
11486
11487                // Quick sanity check that we're signed correctly if updating;
11488                // we'll check this again later when scanning, but we want to
11489                // bail early here before tripping over redefined permissions.
11490                if (!ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
11491                    try {
11492                        verifySignaturesLP(ps, pkg);
11493                    } catch (PackageManagerException e) {
11494                        res.setError(e.error, e.getMessage());
11495                        return;
11496                    }
11497                } else {
11498                    if (!checkUpgradeKeySetLP(ps, pkg)) {
11499                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
11500                                + pkg.packageName + " upgrade keys do not match the "
11501                                + "previously installed version");
11502                        return;
11503                    }
11504                }
11505
11506                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
11507                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
11508                    systemApp = (ps.pkg.applicationInfo.flags &
11509                            ApplicationInfo.FLAG_SYSTEM) != 0;
11510                }
11511                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
11512            }
11513
11514            // Check whether the newly-scanned package wants to define an already-defined perm
11515            int N = pkg.permissions.size();
11516            for (int i = N-1; i >= 0; i--) {
11517                PackageParser.Permission perm = pkg.permissions.get(i);
11518                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
11519                if (bp != null) {
11520                    // If the defining package is signed with our cert, it's okay.  This
11521                    // also includes the "updating the same package" case, of course.
11522                    // "updating same package" could also involve key-rotation.
11523                    final boolean sigsOk;
11524                    if (!bp.sourcePackage.equals(pkg.packageName)
11525                            || !(bp.packageSetting instanceof PackageSetting)
11526                            || !bp.packageSetting.keySetData.isUsingUpgradeKeySets()
11527                            || ((PackageSetting) bp.packageSetting).sharedUser != null) {
11528                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
11529                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
11530                    } else {
11531                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
11532                    }
11533                    if (!sigsOk) {
11534                        // If the owning package is the system itself, we log but allow
11535                        // install to proceed; we fail the install on all other permission
11536                        // redefinitions.
11537                        if (!bp.sourcePackage.equals("android")) {
11538                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
11539                                    + pkg.packageName + " attempting to redeclare permission "
11540                                    + perm.info.name + " already owned by " + bp.sourcePackage);
11541                            res.origPermission = perm.info.name;
11542                            res.origPackage = bp.sourcePackage;
11543                            return;
11544                        } else {
11545                            Slog.w(TAG, "Package " + pkg.packageName
11546                                    + " attempting to redeclare system permission "
11547                                    + perm.info.name + "; ignoring new declaration");
11548                            pkg.permissions.remove(i);
11549                        }
11550                    }
11551                }
11552            }
11553
11554        }
11555
11556        if (systemApp && onExternal) {
11557            // Disable updates to system apps on sdcard
11558            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
11559                    "Cannot install updates to system apps on sdcard");
11560            return;
11561        }
11562
11563        if (args.move != null) {
11564            // We did an in-place move, so dex is ready to roll
11565            scanFlags |= SCAN_NO_DEX;
11566        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
11567            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
11568            scanFlags |= SCAN_NO_DEX;
11569            // Run dexopt before old package gets removed, to minimize time when app is unavailable
11570            int result = mPackageDexOptimizer
11571                    .performDexOpt(pkg, null /* instruction sets */, true /* forceDex */,
11572                            false /* defer */, false /* inclDependencies */);
11573            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
11574                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
11575                return;
11576            }
11577        }
11578
11579        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
11580            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
11581            return;
11582        }
11583
11584        startIntentFilterVerifications(args.user.getIdentifier(), pkg);
11585
11586        if (replace) {
11587            replacePackageLI(pkg, parseFlags, scanFlags, args.user,
11588                    installerPackageName, volumeUuid, res);
11589        } else {
11590            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
11591                    args.user, installerPackageName, volumeUuid, res);
11592        }
11593        synchronized (mPackages) {
11594            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11595            if (ps != null) {
11596                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
11597            }
11598        }
11599    }
11600
11601    private void startIntentFilterVerifications(int userId, PackageParser.Package pkg) {
11602        if (mIntentFilterVerifierComponent == null) {
11603            Slog.d(TAG, "No IntentFilter verification will not be done as "
11604                    + "there is no IntentFilterVerifier available!");
11605            return;
11606        }
11607
11608        final int verifierUid = getPackageUid(
11609                mIntentFilterVerifierComponent.getPackageName(),
11610                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
11611
11612        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
11613        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
11614        msg.obj = pkg;
11615        msg.arg1 = userId;
11616        msg.arg2 = verifierUid;
11617
11618        mHandler.sendMessage(msg);
11619    }
11620
11621    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid,
11622            PackageParser.Package pkg) {
11623        int size = pkg.activities.size();
11624        if (size == 0) {
11625            Slog.d(TAG, "No activity, so no need to verify any IntentFilter!");
11626            return;
11627        }
11628
11629        final boolean hasDomainURLs = hasDomainURLs(pkg);
11630        if (!hasDomainURLs) {
11631            Slog.d(TAG, "No domain URLs, so no need to verify any IntentFilter!");
11632            return;
11633        }
11634
11635        Slog.d(TAG, "Checking for userId:" + userId + " if any IntentFilter from the " + size
11636                + " Activities needs verification ...");
11637
11638        final int verificationId = mIntentFilterVerificationToken++;
11639        int count = 0;
11640        final String packageName = pkg.packageName;
11641        ArrayList<String> allHosts = new ArrayList<>();
11642
11643        synchronized (mPackages) {
11644            for (PackageParser.Activity a : pkg.activities) {
11645                for (ActivityIntentInfo filter : a.intents) {
11646                    boolean needsFilterVerification = filter.needsVerification();
11647                    if (needsFilterVerification && needsNetworkVerificationLPr(filter)) {
11648                        Slog.d(TAG, "Verification needed for IntentFilter:" + filter.toString());
11649                        mIntentFilterVerifier.addOneIntentFilterVerification(
11650                                verifierUid, userId, verificationId, filter, packageName);
11651                        count++;
11652                    } else if (!needsFilterVerification) {
11653                        Slog.d(TAG, "No verification needed for IntentFilter:" + filter.toString());
11654                        if (hasValidDomains(filter)) {
11655                            ArrayList<String> hosts = filter.getHostsList();
11656                            if (hosts.size() > 0) {
11657                                allHosts.addAll(hosts);
11658                            } else {
11659                                if (allHosts.isEmpty()) {
11660                                    allHosts.add("*");
11661                                }
11662                            }
11663                        }
11664                    } else {
11665                        Slog.d(TAG, "Verification already done for IntentFilter:"
11666                                + filter.toString());
11667                    }
11668                }
11669            }
11670        }
11671
11672        if (count > 0) {
11673            mIntentFilterVerifier.startVerifications(userId);
11674            Slog.d(TAG, "Started " + count + " IntentFilter verification"
11675                    + (count > 1 ? "s" : "") +  " for userId:" + userId + "!");
11676        } else {
11677            Slog.d(TAG, "No need to start any IntentFilter verification!");
11678            if (allHosts.size() > 0 && mSettings.createIntentFilterVerificationIfNeededLPw(
11679                    packageName, allHosts) != null) {
11680                scheduleWriteSettingsLocked();
11681            }
11682        }
11683    }
11684
11685    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
11686        final ComponentName cn  = filter.activity.getComponentName();
11687        final String packageName = cn.getPackageName();
11688
11689        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
11690                packageName);
11691        if (ivi == null) {
11692            return true;
11693        }
11694        int status = ivi.getStatus();
11695        switch (status) {
11696            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
11697            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
11698                return true;
11699
11700            default:
11701                // Nothing to do
11702                return false;
11703        }
11704    }
11705
11706    private boolean isSystemComponentOrPersistentPrivApp(PackageParser.Package pkg) {
11707        return UserHandle.getAppId(pkg.applicationInfo.uid) < FIRST_APPLICATION_UID
11708                || ((pkg.applicationInfo.privateFlags
11709                        & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0
11710                && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0);
11711    }
11712
11713    private static boolean isMultiArch(PackageSetting ps) {
11714        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
11715    }
11716
11717    private static boolean isMultiArch(ApplicationInfo info) {
11718        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
11719    }
11720
11721    private static boolean isExternal(PackageParser.Package pkg) {
11722        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
11723    }
11724
11725    private static boolean isExternal(PackageSetting ps) {
11726        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
11727    }
11728
11729    private static boolean isExternal(ApplicationInfo info) {
11730        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
11731    }
11732
11733    private static boolean isSystemApp(PackageParser.Package pkg) {
11734        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
11735    }
11736
11737    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
11738        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
11739    }
11740
11741    private static boolean hasDomainURLs(PackageParser.Package pkg) {
11742        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
11743    }
11744
11745    private static boolean isSystemApp(PackageSetting ps) {
11746        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
11747    }
11748
11749    private static boolean isUpdatedSystemApp(PackageSetting ps) {
11750        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
11751    }
11752
11753    private int packageFlagsToInstallFlags(PackageSetting ps) {
11754        int installFlags = 0;
11755        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
11756            // This existing package was an external ASEC install when we have
11757            // the external flag without a UUID
11758            installFlags |= PackageManager.INSTALL_EXTERNAL;
11759        }
11760        if (ps.isForwardLocked()) {
11761            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
11762        }
11763        return installFlags;
11764    }
11765
11766    private void deleteTempPackageFiles() {
11767        final FilenameFilter filter = new FilenameFilter() {
11768            public boolean accept(File dir, String name) {
11769                return name.startsWith("vmdl") && name.endsWith(".tmp");
11770            }
11771        };
11772        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
11773            file.delete();
11774        }
11775    }
11776
11777    @Override
11778    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
11779            int flags) {
11780        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
11781                flags);
11782    }
11783
11784    @Override
11785    public void deletePackage(final String packageName,
11786            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
11787        mContext.enforceCallingOrSelfPermission(
11788                android.Manifest.permission.DELETE_PACKAGES, null);
11789        final int uid = Binder.getCallingUid();
11790        if (UserHandle.getUserId(uid) != userId) {
11791            mContext.enforceCallingPermission(
11792                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
11793                    "deletePackage for user " + userId);
11794        }
11795        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
11796            try {
11797                observer.onPackageDeleted(packageName,
11798                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
11799            } catch (RemoteException re) {
11800            }
11801            return;
11802        }
11803
11804        boolean uninstallBlocked = false;
11805        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
11806            int[] users = sUserManager.getUserIds();
11807            for (int i = 0; i < users.length; ++i) {
11808                if (getBlockUninstallForUser(packageName, users[i])) {
11809                    uninstallBlocked = true;
11810                    break;
11811                }
11812            }
11813        } else {
11814            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
11815        }
11816        if (uninstallBlocked) {
11817            try {
11818                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
11819                        null);
11820            } catch (RemoteException re) {
11821            }
11822            return;
11823        }
11824
11825        if (DEBUG_REMOVE) {
11826            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
11827        }
11828        // Queue up an async operation since the package deletion may take a little while.
11829        mHandler.post(new Runnable() {
11830            public void run() {
11831                mHandler.removeCallbacks(this);
11832                final int returnCode = deletePackageX(packageName, userId, flags);
11833                if (observer != null) {
11834                    try {
11835                        observer.onPackageDeleted(packageName, returnCode, null);
11836                    } catch (RemoteException e) {
11837                        Log.i(TAG, "Observer no longer exists.");
11838                    } //end catch
11839                } //end if
11840            } //end run
11841        });
11842    }
11843
11844    private boolean isPackageDeviceAdmin(String packageName, int userId) {
11845        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
11846                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
11847        try {
11848            if (dpm != null) {
11849                if (dpm.isDeviceOwner(packageName)) {
11850                    return true;
11851                }
11852                int[] users;
11853                if (userId == UserHandle.USER_ALL) {
11854                    users = sUserManager.getUserIds();
11855                } else {
11856                    users = new int[]{userId};
11857                }
11858                for (int i = 0; i < users.length; ++i) {
11859                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
11860                        return true;
11861                    }
11862                }
11863            }
11864        } catch (RemoteException e) {
11865        }
11866        return false;
11867    }
11868
11869    /**
11870     *  This method is an internal method that could be get invoked either
11871     *  to delete an installed package or to clean up a failed installation.
11872     *  After deleting an installed package, a broadcast is sent to notify any
11873     *  listeners that the package has been installed. For cleaning up a failed
11874     *  installation, the broadcast is not necessary since the package's
11875     *  installation wouldn't have sent the initial broadcast either
11876     *  The key steps in deleting a package are
11877     *  deleting the package information in internal structures like mPackages,
11878     *  deleting the packages base directories through installd
11879     *  updating mSettings to reflect current status
11880     *  persisting settings for later use
11881     *  sending a broadcast if necessary
11882     */
11883    private int deletePackageX(String packageName, int userId, int flags) {
11884        final PackageRemovedInfo info = new PackageRemovedInfo();
11885        final boolean res;
11886
11887        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
11888                ? UserHandle.ALL : new UserHandle(userId);
11889
11890        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
11891            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
11892            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
11893        }
11894
11895        boolean removedForAllUsers = false;
11896        boolean systemUpdate = false;
11897
11898        // for the uninstall-updates case and restricted profiles, remember the per-
11899        // userhandle installed state
11900        int[] allUsers;
11901        boolean[] perUserInstalled;
11902        synchronized (mPackages) {
11903            PackageSetting ps = mSettings.mPackages.get(packageName);
11904            allUsers = sUserManager.getUserIds();
11905            perUserInstalled = new boolean[allUsers.length];
11906            for (int i = 0; i < allUsers.length; i++) {
11907                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11908            }
11909        }
11910
11911        synchronized (mInstallLock) {
11912            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
11913            res = deletePackageLI(packageName, removeForUser,
11914                    true, allUsers, perUserInstalled,
11915                    flags | REMOVE_CHATTY, info, true);
11916            systemUpdate = info.isRemovedPackageSystemUpdate;
11917            if (res && !systemUpdate && mPackages.get(packageName) == null) {
11918                removedForAllUsers = true;
11919            }
11920            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
11921                    + " removedForAllUsers=" + removedForAllUsers);
11922        }
11923
11924        if (res) {
11925            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
11926
11927            // If the removed package was a system update, the old system package
11928            // was re-enabled; we need to broadcast this information
11929            if (systemUpdate) {
11930                Bundle extras = new Bundle(1);
11931                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
11932                        ? info.removedAppId : info.uid);
11933                extras.putBoolean(Intent.EXTRA_REPLACING, true);
11934
11935                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
11936                        extras, null, null, null);
11937                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
11938                        extras, null, null, null);
11939                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
11940                        null, packageName, null, null);
11941            }
11942        }
11943        // Force a gc here.
11944        Runtime.getRuntime().gc();
11945        // Delete the resources here after sending the broadcast to let
11946        // other processes clean up before deleting resources.
11947        if (info.args != null) {
11948            synchronized (mInstallLock) {
11949                info.args.doPostDeleteLI(true);
11950            }
11951        }
11952
11953        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
11954    }
11955
11956    class PackageRemovedInfo {
11957        String removedPackage;
11958        int uid = -1;
11959        int removedAppId = -1;
11960        int[] removedUsers = null;
11961        boolean isRemovedPackageSystemUpdate = false;
11962        // Clean up resources deleted packages.
11963        InstallArgs args = null;
11964
11965        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
11966            Bundle extras = new Bundle(1);
11967            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
11968            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
11969            if (replacing) {
11970                extras.putBoolean(Intent.EXTRA_REPLACING, true);
11971            }
11972            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
11973            if (removedPackage != null) {
11974                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
11975                        extras, null, null, removedUsers);
11976                if (fullRemove && !replacing) {
11977                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
11978                            extras, null, null, removedUsers);
11979                }
11980            }
11981            if (removedAppId >= 0) {
11982                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
11983                        removedUsers);
11984            }
11985        }
11986    }
11987
11988    /*
11989     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
11990     * flag is not set, the data directory is removed as well.
11991     * make sure this flag is set for partially installed apps. If not its meaningless to
11992     * delete a partially installed application.
11993     */
11994    private void removePackageDataLI(PackageSetting ps,
11995            int[] allUserHandles, boolean[] perUserInstalled,
11996            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
11997        String packageName = ps.name;
11998        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
11999        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
12000        // Retrieve object to delete permissions for shared user later on
12001        final PackageSetting deletedPs;
12002        // reader
12003        synchronized (mPackages) {
12004            deletedPs = mSettings.mPackages.get(packageName);
12005            if (outInfo != null) {
12006                outInfo.removedPackage = packageName;
12007                outInfo.removedUsers = deletedPs != null
12008                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
12009                        : null;
12010            }
12011        }
12012        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12013            removeDataDirsLI(ps.volumeUuid, packageName);
12014            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
12015        }
12016        // writer
12017        synchronized (mPackages) {
12018            if (deletedPs != null) {
12019                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12020                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
12021                    clearDefaultBrowserIfNeeded(packageName);
12022                    if (outInfo != null) {
12023                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
12024                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
12025                    }
12026                    updatePermissionsLPw(deletedPs.name, null, 0);
12027                    if (deletedPs.sharedUser != null) {
12028                        // Remove permissions associated with package. Since runtime
12029                        // permissions are per user we have to kill the removed package
12030                        // or packages running under the shared user of the removed
12031                        // package if revoking the permissions requested only by the removed
12032                        // package is successful and this causes a change in gids.
12033                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12034                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
12035                                    userId);
12036                            if (userIdToKill == UserHandle.USER_ALL
12037                                    || userIdToKill >= UserHandle.USER_OWNER) {
12038                                // If gids changed for this user, kill all affected packages.
12039                                mHandler.post(new Runnable() {
12040                                    @Override
12041                                    public void run() {
12042                                        // This has to happen with no lock held.
12043                                        killSettingPackagesForUser(deletedPs, userIdToKill,
12044                                                KILL_APP_REASON_GIDS_CHANGED);
12045                                    }
12046                                });
12047                            break;
12048                            }
12049                        }
12050                    }
12051                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
12052                }
12053                // make sure to preserve per-user disabled state if this removal was just
12054                // a downgrade of a system app to the factory package
12055                if (allUserHandles != null && perUserInstalled != null) {
12056                    if (DEBUG_REMOVE) {
12057                        Slog.d(TAG, "Propagating install state across downgrade");
12058                    }
12059                    for (int i = 0; i < allUserHandles.length; i++) {
12060                        if (DEBUG_REMOVE) {
12061                            Slog.d(TAG, "    user " + allUserHandles[i]
12062                                    + " => " + perUserInstalled[i]);
12063                        }
12064                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12065                    }
12066                }
12067            }
12068            // can downgrade to reader
12069            if (writeSettings) {
12070                // Save settings now
12071                mSettings.writeLPr();
12072            }
12073        }
12074        if (outInfo != null) {
12075            // A user ID was deleted here. Go through all users and remove it
12076            // from KeyStore.
12077            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
12078        }
12079    }
12080
12081    static boolean locationIsPrivileged(File path) {
12082        try {
12083            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
12084                    .getCanonicalPath();
12085            return path.getCanonicalPath().startsWith(privilegedAppDir);
12086        } catch (IOException e) {
12087            Slog.e(TAG, "Unable to access code path " + path);
12088        }
12089        return false;
12090    }
12091
12092    /*
12093     * Tries to delete system package.
12094     */
12095    private boolean deleteSystemPackageLI(PackageSetting newPs,
12096            int[] allUserHandles, boolean[] perUserInstalled,
12097            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
12098        final boolean applyUserRestrictions
12099                = (allUserHandles != null) && (perUserInstalled != null);
12100        PackageSetting disabledPs = null;
12101        // Confirm if the system package has been updated
12102        // An updated system app can be deleted. This will also have to restore
12103        // the system pkg from system partition
12104        // reader
12105        synchronized (mPackages) {
12106            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
12107        }
12108        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
12109                + " disabledPs=" + disabledPs);
12110        if (disabledPs == null) {
12111            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
12112            return false;
12113        } else if (DEBUG_REMOVE) {
12114            Slog.d(TAG, "Deleting system pkg from data partition");
12115        }
12116        if (DEBUG_REMOVE) {
12117            if (applyUserRestrictions) {
12118                Slog.d(TAG, "Remembering install states:");
12119                for (int i = 0; i < allUserHandles.length; i++) {
12120                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
12121                }
12122            }
12123        }
12124        // Delete the updated package
12125        outInfo.isRemovedPackageSystemUpdate = true;
12126        if (disabledPs.versionCode < newPs.versionCode) {
12127            // Delete data for downgrades
12128            flags &= ~PackageManager.DELETE_KEEP_DATA;
12129        } else {
12130            // Preserve data by setting flag
12131            flags |= PackageManager.DELETE_KEEP_DATA;
12132        }
12133        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
12134                allUserHandles, perUserInstalled, outInfo, writeSettings);
12135        if (!ret) {
12136            return false;
12137        }
12138        // writer
12139        synchronized (mPackages) {
12140            // Reinstate the old system package
12141            mSettings.enableSystemPackageLPw(newPs.name);
12142            // Remove any native libraries from the upgraded package.
12143            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
12144        }
12145        // Install the system package
12146        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
12147        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
12148        if (locationIsPrivileged(disabledPs.codePath)) {
12149            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12150        }
12151
12152        final PackageParser.Package newPkg;
12153        try {
12154            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
12155        } catch (PackageManagerException e) {
12156            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
12157            return false;
12158        }
12159
12160        // writer
12161        synchronized (mPackages) {
12162            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
12163            updatePermissionsLPw(newPkg.packageName, newPkg,
12164                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
12165            if (applyUserRestrictions) {
12166                if (DEBUG_REMOVE) {
12167                    Slog.d(TAG, "Propagating install state across reinstall");
12168                }
12169                for (int i = 0; i < allUserHandles.length; i++) {
12170                    if (DEBUG_REMOVE) {
12171                        Slog.d(TAG, "    user " + allUserHandles[i]
12172                                + " => " + perUserInstalled[i]);
12173                    }
12174                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12175                }
12176                // Regardless of writeSettings we need to ensure that this restriction
12177                // state propagation is persisted
12178                mSettings.writeAllUsersPackageRestrictionsLPr();
12179            }
12180            // can downgrade to reader here
12181            if (writeSettings) {
12182                mSettings.writeLPr();
12183            }
12184        }
12185        return true;
12186    }
12187
12188    private boolean deleteInstalledPackageLI(PackageSetting ps,
12189            boolean deleteCodeAndResources, int flags,
12190            int[] allUserHandles, boolean[] perUserInstalled,
12191            PackageRemovedInfo outInfo, boolean writeSettings) {
12192        if (outInfo != null) {
12193            outInfo.uid = ps.appId;
12194        }
12195
12196        // Delete package data from internal structures and also remove data if flag is set
12197        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
12198
12199        // Delete application code and resources
12200        if (deleteCodeAndResources && (outInfo != null)) {
12201            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
12202                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
12203            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
12204        }
12205        return true;
12206    }
12207
12208    @Override
12209    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
12210            int userId) {
12211        mContext.enforceCallingOrSelfPermission(
12212                android.Manifest.permission.DELETE_PACKAGES, null);
12213        synchronized (mPackages) {
12214            PackageSetting ps = mSettings.mPackages.get(packageName);
12215            if (ps == null) {
12216                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
12217                return false;
12218            }
12219            if (!ps.getInstalled(userId)) {
12220                // Can't block uninstall for an app that is not installed or enabled.
12221                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
12222                return false;
12223            }
12224            ps.setBlockUninstall(blockUninstall, userId);
12225            mSettings.writePackageRestrictionsLPr(userId);
12226        }
12227        return true;
12228    }
12229
12230    @Override
12231    public boolean getBlockUninstallForUser(String packageName, int userId) {
12232        synchronized (mPackages) {
12233            PackageSetting ps = mSettings.mPackages.get(packageName);
12234            if (ps == null) {
12235                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
12236                return false;
12237            }
12238            return ps.getBlockUninstall(userId);
12239        }
12240    }
12241
12242    /*
12243     * This method handles package deletion in general
12244     */
12245    private boolean deletePackageLI(String packageName, UserHandle user,
12246            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
12247            int flags, PackageRemovedInfo outInfo,
12248            boolean writeSettings) {
12249        if (packageName == null) {
12250            Slog.w(TAG, "Attempt to delete null packageName.");
12251            return false;
12252        }
12253        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
12254        PackageSetting ps;
12255        boolean dataOnly = false;
12256        int removeUser = -1;
12257        int appId = -1;
12258        synchronized (mPackages) {
12259            ps = mSettings.mPackages.get(packageName);
12260            if (ps == null) {
12261                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12262                return false;
12263            }
12264            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
12265                    && user.getIdentifier() != UserHandle.USER_ALL) {
12266                // The caller is asking that the package only be deleted for a single
12267                // user.  To do this, we just mark its uninstalled state and delete
12268                // its data.  If this is a system app, we only allow this to happen if
12269                // they have set the special DELETE_SYSTEM_APP which requests different
12270                // semantics than normal for uninstalling system apps.
12271                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
12272                ps.setUserState(user.getIdentifier(),
12273                        COMPONENT_ENABLED_STATE_DEFAULT,
12274                        false, //installed
12275                        true,  //stopped
12276                        true,  //notLaunched
12277                        false, //hidden
12278                        null, null, null,
12279                        false, // blockUninstall
12280                        INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
12281                if (!isSystemApp(ps)) {
12282                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
12283                        // Other user still have this package installed, so all
12284                        // we need to do is clear this user's data and save that
12285                        // it is uninstalled.
12286                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
12287                        removeUser = user.getIdentifier();
12288                        appId = ps.appId;
12289                        scheduleWritePackageRestrictionsLocked(removeUser);
12290                    } else {
12291                        // We need to set it back to 'installed' so the uninstall
12292                        // broadcasts will be sent correctly.
12293                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
12294                        ps.setInstalled(true, user.getIdentifier());
12295                    }
12296                } else {
12297                    // This is a system app, so we assume that the
12298                    // other users still have this package installed, so all
12299                    // we need to do is clear this user's data and save that
12300                    // it is uninstalled.
12301                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
12302                    removeUser = user.getIdentifier();
12303                    appId = ps.appId;
12304                    scheduleWritePackageRestrictionsLocked(removeUser);
12305                }
12306            }
12307        }
12308
12309        if (removeUser >= 0) {
12310            // From above, we determined that we are deleting this only
12311            // for a single user.  Continue the work here.
12312            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
12313            if (outInfo != null) {
12314                outInfo.removedPackage = packageName;
12315                outInfo.removedAppId = appId;
12316                outInfo.removedUsers = new int[] {removeUser};
12317            }
12318            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
12319            removeKeystoreDataIfNeeded(removeUser, appId);
12320            schedulePackageCleaning(packageName, removeUser, false);
12321            synchronized (mPackages) {
12322                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
12323                    scheduleWritePackageRestrictionsLocked(removeUser);
12324                }
12325            }
12326            return true;
12327        }
12328
12329        if (dataOnly) {
12330            // Delete application data first
12331            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
12332            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
12333            return true;
12334        }
12335
12336        boolean ret = false;
12337        if (isSystemApp(ps)) {
12338            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
12339            // When an updated system application is deleted we delete the existing resources as well and
12340            // fall back to existing code in system partition
12341            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
12342                    flags, outInfo, writeSettings);
12343        } else {
12344            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
12345            // Kill application pre-emptively especially for apps on sd.
12346            killApplication(packageName, ps.appId, "uninstall pkg");
12347            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
12348                    allUserHandles, perUserInstalled,
12349                    outInfo, writeSettings);
12350        }
12351
12352        return ret;
12353    }
12354
12355    private final class ClearStorageConnection implements ServiceConnection {
12356        IMediaContainerService mContainerService;
12357
12358        @Override
12359        public void onServiceConnected(ComponentName name, IBinder service) {
12360            synchronized (this) {
12361                mContainerService = IMediaContainerService.Stub.asInterface(service);
12362                notifyAll();
12363            }
12364        }
12365
12366        @Override
12367        public void onServiceDisconnected(ComponentName name) {
12368        }
12369    }
12370
12371    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
12372        final boolean mounted;
12373        if (Environment.isExternalStorageEmulated()) {
12374            mounted = true;
12375        } else {
12376            final String status = Environment.getExternalStorageState();
12377
12378            mounted = status.equals(Environment.MEDIA_MOUNTED)
12379                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
12380        }
12381
12382        if (!mounted) {
12383            return;
12384        }
12385
12386        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
12387        int[] users;
12388        if (userId == UserHandle.USER_ALL) {
12389            users = sUserManager.getUserIds();
12390        } else {
12391            users = new int[] { userId };
12392        }
12393        final ClearStorageConnection conn = new ClearStorageConnection();
12394        if (mContext.bindServiceAsUser(
12395                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
12396            try {
12397                for (int curUser : users) {
12398                    long timeout = SystemClock.uptimeMillis() + 5000;
12399                    synchronized (conn) {
12400                        long now = SystemClock.uptimeMillis();
12401                        while (conn.mContainerService == null && now < timeout) {
12402                            try {
12403                                conn.wait(timeout - now);
12404                            } catch (InterruptedException e) {
12405                            }
12406                        }
12407                    }
12408                    if (conn.mContainerService == null) {
12409                        return;
12410                    }
12411
12412                    final UserEnvironment userEnv = new UserEnvironment(curUser);
12413                    clearDirectory(conn.mContainerService,
12414                            userEnv.buildExternalStorageAppCacheDirs(packageName));
12415                    if (allData) {
12416                        clearDirectory(conn.mContainerService,
12417                                userEnv.buildExternalStorageAppDataDirs(packageName));
12418                        clearDirectory(conn.mContainerService,
12419                                userEnv.buildExternalStorageAppMediaDirs(packageName));
12420                    }
12421                }
12422            } finally {
12423                mContext.unbindService(conn);
12424            }
12425        }
12426    }
12427
12428    @Override
12429    public void clearApplicationUserData(final String packageName,
12430            final IPackageDataObserver observer, final int userId) {
12431        mContext.enforceCallingOrSelfPermission(
12432                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
12433        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
12434        // Queue up an async operation since the package deletion may take a little while.
12435        mHandler.post(new Runnable() {
12436            public void run() {
12437                mHandler.removeCallbacks(this);
12438                final boolean succeeded;
12439                synchronized (mInstallLock) {
12440                    succeeded = clearApplicationUserDataLI(packageName, userId);
12441                }
12442                clearExternalStorageDataSync(packageName, userId, true);
12443                if (succeeded) {
12444                    // invoke DeviceStorageMonitor's update method to clear any notifications
12445                    DeviceStorageMonitorInternal
12446                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
12447                    if (dsm != null) {
12448                        dsm.checkMemory();
12449                    }
12450                }
12451                if(observer != null) {
12452                    try {
12453                        observer.onRemoveCompleted(packageName, succeeded);
12454                    } catch (RemoteException e) {
12455                        Log.i(TAG, "Observer no longer exists.");
12456                    }
12457                } //end if observer
12458            } //end run
12459        });
12460    }
12461
12462    private boolean clearApplicationUserDataLI(String packageName, int userId) {
12463        if (packageName == null) {
12464            Slog.w(TAG, "Attempt to delete null packageName.");
12465            return false;
12466        }
12467
12468        // Try finding details about the requested package
12469        PackageParser.Package pkg;
12470        synchronized (mPackages) {
12471            pkg = mPackages.get(packageName);
12472            if (pkg == null) {
12473                final PackageSetting ps = mSettings.mPackages.get(packageName);
12474                if (ps != null) {
12475                    pkg = ps.pkg;
12476                }
12477            }
12478        }
12479
12480        if (pkg == null) {
12481            Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12482        }
12483
12484        // Always delete data directories for package, even if we found no other
12485        // record of app. This helps users recover from UID mismatches without
12486        // resorting to a full data wipe.
12487        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
12488        if (retCode < 0) {
12489            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
12490            return false;
12491        }
12492
12493        if (pkg == null) {
12494            return false;
12495        }
12496
12497        if (pkg != null && pkg.applicationInfo != null) {
12498            final int appId = pkg.applicationInfo.uid;
12499            removeKeystoreDataIfNeeded(userId, appId);
12500        }
12501
12502        // Create a native library symlink only if we have native libraries
12503        // and if the native libraries are 32 bit libraries. We do not provide
12504        // this symlink for 64 bit libraries.
12505        if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null &&
12506                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
12507            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
12508            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
12509                    nativeLibPath, userId) < 0) {
12510                Slog.w(TAG, "Failed linking native library dir");
12511                return false;
12512            }
12513        }
12514
12515        return true;
12516    }
12517
12518    /**
12519     * Remove entries from the keystore daemon. Will only remove it if the
12520     * {@code appId} is valid.
12521     */
12522    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
12523        if (appId < 0) {
12524            return;
12525        }
12526
12527        final KeyStore keyStore = KeyStore.getInstance();
12528        if (keyStore != null) {
12529            if (userId == UserHandle.USER_ALL) {
12530                for (final int individual : sUserManager.getUserIds()) {
12531                    keyStore.clearUid(UserHandle.getUid(individual, appId));
12532                }
12533            } else {
12534                keyStore.clearUid(UserHandle.getUid(userId, appId));
12535            }
12536        } else {
12537            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
12538        }
12539    }
12540
12541    @Override
12542    public void deleteApplicationCacheFiles(final String packageName,
12543            final IPackageDataObserver observer) {
12544        mContext.enforceCallingOrSelfPermission(
12545                android.Manifest.permission.DELETE_CACHE_FILES, null);
12546        // Queue up an async operation since the package deletion may take a little while.
12547        final int userId = UserHandle.getCallingUserId();
12548        mHandler.post(new Runnable() {
12549            public void run() {
12550                mHandler.removeCallbacks(this);
12551                final boolean succeded;
12552                synchronized (mInstallLock) {
12553                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
12554                }
12555                clearExternalStorageDataSync(packageName, userId, false);
12556                if (observer != null) {
12557                    try {
12558                        observer.onRemoveCompleted(packageName, succeded);
12559                    } catch (RemoteException e) {
12560                        Log.i(TAG, "Observer no longer exists.");
12561                    }
12562                } //end if observer
12563            } //end run
12564        });
12565    }
12566
12567    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
12568        if (packageName == null) {
12569            Slog.w(TAG, "Attempt to delete null packageName.");
12570            return false;
12571        }
12572        PackageParser.Package p;
12573        synchronized (mPackages) {
12574            p = mPackages.get(packageName);
12575        }
12576        if (p == null) {
12577            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
12578            return false;
12579        }
12580        final ApplicationInfo applicationInfo = p.applicationInfo;
12581        if (applicationInfo == null) {
12582            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
12583            return false;
12584        }
12585        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
12586        if (retCode < 0) {
12587            Slog.w(TAG, "Couldn't remove cache files for package: "
12588                       + packageName + " u" + userId);
12589            return false;
12590        }
12591        return true;
12592    }
12593
12594    @Override
12595    public void getPackageSizeInfo(final String packageName, int userHandle,
12596            final IPackageStatsObserver observer) {
12597        mContext.enforceCallingOrSelfPermission(
12598                android.Manifest.permission.GET_PACKAGE_SIZE, null);
12599        if (packageName == null) {
12600            throw new IllegalArgumentException("Attempt to get size of null packageName");
12601        }
12602
12603        PackageStats stats = new PackageStats(packageName, userHandle);
12604
12605        /*
12606         * Queue up an async operation since the package measurement may take a
12607         * little while.
12608         */
12609        Message msg = mHandler.obtainMessage(INIT_COPY);
12610        msg.obj = new MeasureParams(stats, observer);
12611        mHandler.sendMessage(msg);
12612    }
12613
12614    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
12615            PackageStats pStats) {
12616        if (packageName == null) {
12617            Slog.w(TAG, "Attempt to get size of null packageName.");
12618            return false;
12619        }
12620        PackageParser.Package p;
12621        boolean dataOnly = false;
12622        String libDirRoot = null;
12623        String asecPath = null;
12624        PackageSetting ps = null;
12625        synchronized (mPackages) {
12626            p = mPackages.get(packageName);
12627            ps = mSettings.mPackages.get(packageName);
12628            if(p == null) {
12629                dataOnly = true;
12630                if((ps == null) || (ps.pkg == null)) {
12631                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
12632                    return false;
12633                }
12634                p = ps.pkg;
12635            }
12636            if (ps != null) {
12637                libDirRoot = ps.legacyNativeLibraryPathString;
12638            }
12639            if (p != null && (isExternal(p) || p.isForwardLocked())) {
12640                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
12641                if (secureContainerId != null) {
12642                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
12643                }
12644            }
12645        }
12646        String publicSrcDir = null;
12647        if(!dataOnly) {
12648            final ApplicationInfo applicationInfo = p.applicationInfo;
12649            if (applicationInfo == null) {
12650                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
12651                return false;
12652            }
12653            if (p.isForwardLocked()) {
12654                publicSrcDir = applicationInfo.getBaseResourcePath();
12655            }
12656        }
12657        // TODO: extend to measure size of split APKs
12658        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
12659        // not just the first level.
12660        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
12661        // just the primary.
12662        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
12663        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath,
12664                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
12665        if (res < 0) {
12666            return false;
12667        }
12668
12669        // Fix-up for forward-locked applications in ASEC containers.
12670        if (!isExternal(p)) {
12671            pStats.codeSize += pStats.externalCodeSize;
12672            pStats.externalCodeSize = 0L;
12673        }
12674
12675        return true;
12676    }
12677
12678
12679    @Override
12680    public void addPackageToPreferred(String packageName) {
12681        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
12682    }
12683
12684    @Override
12685    public void removePackageFromPreferred(String packageName) {
12686        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
12687    }
12688
12689    @Override
12690    public List<PackageInfo> getPreferredPackages(int flags) {
12691        return new ArrayList<PackageInfo>();
12692    }
12693
12694    private int getUidTargetSdkVersionLockedLPr(int uid) {
12695        Object obj = mSettings.getUserIdLPr(uid);
12696        if (obj instanceof SharedUserSetting) {
12697            final SharedUserSetting sus = (SharedUserSetting) obj;
12698            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
12699            final Iterator<PackageSetting> it = sus.packages.iterator();
12700            while (it.hasNext()) {
12701                final PackageSetting ps = it.next();
12702                if (ps.pkg != null) {
12703                    int v = ps.pkg.applicationInfo.targetSdkVersion;
12704                    if (v < vers) vers = v;
12705                }
12706            }
12707            return vers;
12708        } else if (obj instanceof PackageSetting) {
12709            final PackageSetting ps = (PackageSetting) obj;
12710            if (ps.pkg != null) {
12711                return ps.pkg.applicationInfo.targetSdkVersion;
12712            }
12713        }
12714        return Build.VERSION_CODES.CUR_DEVELOPMENT;
12715    }
12716
12717    @Override
12718    public void addPreferredActivity(IntentFilter filter, int match,
12719            ComponentName[] set, ComponentName activity, int userId) {
12720        addPreferredActivityInternal(filter, match, set, activity, true, userId,
12721                "Adding preferred");
12722    }
12723
12724    private void addPreferredActivityInternal(IntentFilter filter, int match,
12725            ComponentName[] set, ComponentName activity, boolean always, int userId,
12726            String opname) {
12727        // writer
12728        int callingUid = Binder.getCallingUid();
12729        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
12730        if (filter.countActions() == 0) {
12731            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
12732            return;
12733        }
12734        synchronized (mPackages) {
12735            if (mContext.checkCallingOrSelfPermission(
12736                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
12737                    != PackageManager.PERMISSION_GRANTED) {
12738                if (getUidTargetSdkVersionLockedLPr(callingUid)
12739                        < Build.VERSION_CODES.FROYO) {
12740                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
12741                            + callingUid);
12742                    return;
12743                }
12744                mContext.enforceCallingOrSelfPermission(
12745                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12746            }
12747
12748            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
12749            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
12750                    + userId + ":");
12751            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12752            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
12753            scheduleWritePackageRestrictionsLocked(userId);
12754        }
12755    }
12756
12757    @Override
12758    public void replacePreferredActivity(IntentFilter filter, int match,
12759            ComponentName[] set, ComponentName activity, int userId) {
12760        if (filter.countActions() != 1) {
12761            throw new IllegalArgumentException(
12762                    "replacePreferredActivity expects filter to have only 1 action.");
12763        }
12764        if (filter.countDataAuthorities() != 0
12765                || filter.countDataPaths() != 0
12766                || filter.countDataSchemes() > 1
12767                || filter.countDataTypes() != 0) {
12768            throw new IllegalArgumentException(
12769                    "replacePreferredActivity expects filter to have no data authorities, " +
12770                    "paths, or types; and at most one scheme.");
12771        }
12772
12773        final int callingUid = Binder.getCallingUid();
12774        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
12775        synchronized (mPackages) {
12776            if (mContext.checkCallingOrSelfPermission(
12777                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
12778                    != PackageManager.PERMISSION_GRANTED) {
12779                if (getUidTargetSdkVersionLockedLPr(callingUid)
12780                        < Build.VERSION_CODES.FROYO) {
12781                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
12782                            + Binder.getCallingUid());
12783                    return;
12784                }
12785                mContext.enforceCallingOrSelfPermission(
12786                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12787            }
12788
12789            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
12790            if (pir != null) {
12791                // Get all of the existing entries that exactly match this filter.
12792                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
12793                if (existing != null && existing.size() == 1) {
12794                    PreferredActivity cur = existing.get(0);
12795                    if (DEBUG_PREFERRED) {
12796                        Slog.i(TAG, "Checking replace of preferred:");
12797                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12798                        if (!cur.mPref.mAlways) {
12799                            Slog.i(TAG, "  -- CUR; not mAlways!");
12800                        } else {
12801                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
12802                            Slog.i(TAG, "  -- CUR: mSet="
12803                                    + Arrays.toString(cur.mPref.mSetComponents));
12804                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
12805                            Slog.i(TAG, "  -- NEW: mMatch="
12806                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
12807                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
12808                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
12809                        }
12810                    }
12811                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
12812                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
12813                            && cur.mPref.sameSet(set)) {
12814                        // Setting the preferred activity to what it happens to be already
12815                        if (DEBUG_PREFERRED) {
12816                            Slog.i(TAG, "Replacing with same preferred activity "
12817                                    + cur.mPref.mShortComponent + " for user "
12818                                    + userId + ":");
12819                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12820                        }
12821                        return;
12822                    }
12823                }
12824
12825                if (existing != null) {
12826                    if (DEBUG_PREFERRED) {
12827                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
12828                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12829                    }
12830                    for (int i = 0; i < existing.size(); i++) {
12831                        PreferredActivity pa = existing.get(i);
12832                        if (DEBUG_PREFERRED) {
12833                            Slog.i(TAG, "Removing existing preferred activity "
12834                                    + pa.mPref.mComponent + ":");
12835                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
12836                        }
12837                        pir.removeFilter(pa);
12838                    }
12839                }
12840            }
12841            addPreferredActivityInternal(filter, match, set, activity, true, userId,
12842                    "Replacing preferred");
12843        }
12844    }
12845
12846    @Override
12847    public void clearPackagePreferredActivities(String packageName) {
12848        final int uid = Binder.getCallingUid();
12849        // writer
12850        synchronized (mPackages) {
12851            PackageParser.Package pkg = mPackages.get(packageName);
12852            if (pkg == null || pkg.applicationInfo.uid != uid) {
12853                if (mContext.checkCallingOrSelfPermission(
12854                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
12855                        != PackageManager.PERMISSION_GRANTED) {
12856                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
12857                            < Build.VERSION_CODES.FROYO) {
12858                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
12859                                + Binder.getCallingUid());
12860                        return;
12861                    }
12862                    mContext.enforceCallingOrSelfPermission(
12863                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12864                }
12865            }
12866
12867            int user = UserHandle.getCallingUserId();
12868            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
12869                scheduleWritePackageRestrictionsLocked(user);
12870            }
12871        }
12872    }
12873
12874    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
12875    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
12876        ArrayList<PreferredActivity> removed = null;
12877        boolean changed = false;
12878        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12879            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
12880            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12881            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
12882                continue;
12883            }
12884            Iterator<PreferredActivity> it = pir.filterIterator();
12885            while (it.hasNext()) {
12886                PreferredActivity pa = it.next();
12887                // Mark entry for removal only if it matches the package name
12888                // and the entry is of type "always".
12889                if (packageName == null ||
12890                        (pa.mPref.mComponent.getPackageName().equals(packageName)
12891                                && pa.mPref.mAlways)) {
12892                    if (removed == null) {
12893                        removed = new ArrayList<PreferredActivity>();
12894                    }
12895                    removed.add(pa);
12896                }
12897            }
12898            if (removed != null) {
12899                for (int j=0; j<removed.size(); j++) {
12900                    PreferredActivity pa = removed.get(j);
12901                    pir.removeFilter(pa);
12902                }
12903                changed = true;
12904            }
12905        }
12906        return changed;
12907    }
12908
12909    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
12910    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
12911        if (userId == UserHandle.USER_ALL) {
12912            if (mSettings.removeIntentFilterVerificationLPw(packageName,
12913                    sUserManager.getUserIds())) {
12914                for (int oneUserId : sUserManager.getUserIds()) {
12915                    scheduleWritePackageRestrictionsLocked(oneUserId);
12916                }
12917            }
12918        } else {
12919            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
12920                scheduleWritePackageRestrictionsLocked(userId);
12921            }
12922        }
12923    }
12924
12925
12926    void clearDefaultBrowserIfNeeded(String packageName) {
12927        for (int oneUserId : sUserManager.getUserIds()) {
12928            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
12929            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
12930            if (packageName.equals(defaultBrowserPackageName)) {
12931                setDefaultBrowserPackageName(null, oneUserId);
12932            }
12933        }
12934    }
12935
12936    @Override
12937    public void resetPreferredActivities(int userId) {
12938        /* TODO: Actually use userId. Why is it being passed in? */
12939        mContext.enforceCallingOrSelfPermission(
12940                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12941        // writer
12942        synchronized (mPackages) {
12943            int user = UserHandle.getCallingUserId();
12944            clearPackagePreferredActivitiesLPw(null, user);
12945            mSettings.readDefaultPreferredAppsLPw(this, user);
12946            scheduleWritePackageRestrictionsLocked(user);
12947        }
12948    }
12949
12950    @Override
12951    public int getPreferredActivities(List<IntentFilter> outFilters,
12952            List<ComponentName> outActivities, String packageName) {
12953
12954        int num = 0;
12955        final int userId = UserHandle.getCallingUserId();
12956        // reader
12957        synchronized (mPackages) {
12958            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
12959            if (pir != null) {
12960                final Iterator<PreferredActivity> it = pir.filterIterator();
12961                while (it.hasNext()) {
12962                    final PreferredActivity pa = it.next();
12963                    if (packageName == null
12964                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
12965                                    && pa.mPref.mAlways)) {
12966                        if (outFilters != null) {
12967                            outFilters.add(new IntentFilter(pa));
12968                        }
12969                        if (outActivities != null) {
12970                            outActivities.add(pa.mPref.mComponent);
12971                        }
12972                    }
12973                }
12974            }
12975        }
12976
12977        return num;
12978    }
12979
12980    @Override
12981    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
12982            int userId) {
12983        int callingUid = Binder.getCallingUid();
12984        if (callingUid != Process.SYSTEM_UID) {
12985            throw new SecurityException(
12986                    "addPersistentPreferredActivity can only be run by the system");
12987        }
12988        if (filter.countActions() == 0) {
12989            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
12990            return;
12991        }
12992        synchronized (mPackages) {
12993            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
12994                    " :");
12995            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12996            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
12997                    new PersistentPreferredActivity(filter, activity));
12998            scheduleWritePackageRestrictionsLocked(userId);
12999        }
13000    }
13001
13002    @Override
13003    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
13004        int callingUid = Binder.getCallingUid();
13005        if (callingUid != Process.SYSTEM_UID) {
13006            throw new SecurityException(
13007                    "clearPackagePersistentPreferredActivities can only be run by the system");
13008        }
13009        ArrayList<PersistentPreferredActivity> removed = null;
13010        boolean changed = false;
13011        synchronized (mPackages) {
13012            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
13013                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
13014                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
13015                        .valueAt(i);
13016                if (userId != thisUserId) {
13017                    continue;
13018                }
13019                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
13020                while (it.hasNext()) {
13021                    PersistentPreferredActivity ppa = it.next();
13022                    // Mark entry for removal only if it matches the package name.
13023                    if (ppa.mComponent.getPackageName().equals(packageName)) {
13024                        if (removed == null) {
13025                            removed = new ArrayList<PersistentPreferredActivity>();
13026                        }
13027                        removed.add(ppa);
13028                    }
13029                }
13030                if (removed != null) {
13031                    for (int j=0; j<removed.size(); j++) {
13032                        PersistentPreferredActivity ppa = removed.get(j);
13033                        ppir.removeFilter(ppa);
13034                    }
13035                    changed = true;
13036                }
13037            }
13038
13039            if (changed) {
13040                scheduleWritePackageRestrictionsLocked(userId);
13041            }
13042        }
13043    }
13044
13045    /**
13046     * Non-Binder method, support for the backup/restore mechanism: write the
13047     * full set of preferred activities in its canonical XML format.  Returns true
13048     * on success; false otherwise.
13049     */
13050    @Override
13051    public byte[] getPreferredActivityBackup(int userId) {
13052        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13053            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
13054        }
13055
13056        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13057        try {
13058            final XmlSerializer serializer = new FastXmlSerializer();
13059            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13060            serializer.startDocument(null, true);
13061            serializer.startTag(null, TAG_PREFERRED_BACKUP);
13062
13063            synchronized (mPackages) {
13064                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
13065            }
13066
13067            serializer.endTag(null, TAG_PREFERRED_BACKUP);
13068            serializer.endDocument();
13069            serializer.flush();
13070        } catch (Exception e) {
13071            if (DEBUG_BACKUP) {
13072                Slog.e(TAG, "Unable to write preferred activities for backup", e);
13073            }
13074            return null;
13075        }
13076
13077        return dataStream.toByteArray();
13078    }
13079
13080    @Override
13081    public void restorePreferredActivities(byte[] backup, int userId) {
13082        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13083            throw new SecurityException("Only the system may call restorePreferredActivities()");
13084        }
13085
13086        try {
13087            final XmlPullParser parser = Xml.newPullParser();
13088            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13089
13090            int type;
13091            while ((type = parser.next()) != XmlPullParser.START_TAG
13092                    && type != XmlPullParser.END_DOCUMENT) {
13093            }
13094            if (type != XmlPullParser.START_TAG) {
13095                // oops didn't find a start tag?!
13096                if (DEBUG_BACKUP) {
13097                    Slog.e(TAG, "Didn't find start tag during restore");
13098                }
13099                return;
13100            }
13101
13102            // this is supposed to be TAG_PREFERRED_BACKUP
13103            if (!TAG_PREFERRED_BACKUP.equals(parser.getName())) {
13104                if (DEBUG_BACKUP) {
13105                    Slog.e(TAG, "Found unexpected tag " + parser.getName());
13106                }
13107                return;
13108            }
13109
13110            // skip interfering stuff, then we're aligned with the backing implementation
13111            while ((type = parser.next()) == XmlPullParser.TEXT) { }
13112            synchronized (mPackages) {
13113                mSettings.readPreferredActivitiesLPw(parser, userId);
13114            }
13115        } catch (Exception e) {
13116            if (DEBUG_BACKUP) {
13117                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
13118            }
13119        }
13120    }
13121
13122    @Override
13123    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
13124            int sourceUserId, int targetUserId, int flags) {
13125        mContext.enforceCallingOrSelfPermission(
13126                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
13127        int callingUid = Binder.getCallingUid();
13128        enforceOwnerRights(ownerPackage, callingUid);
13129        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
13130        if (intentFilter.countActions() == 0) {
13131            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
13132            return;
13133        }
13134        synchronized (mPackages) {
13135            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
13136                    ownerPackage, targetUserId, flags);
13137            CrossProfileIntentResolver resolver =
13138                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
13139            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
13140            // We have all those whose filter is equal. Now checking if the rest is equal as well.
13141            if (existing != null) {
13142                int size = existing.size();
13143                for (int i = 0; i < size; i++) {
13144                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
13145                        return;
13146                    }
13147                }
13148            }
13149            resolver.addFilter(newFilter);
13150            scheduleWritePackageRestrictionsLocked(sourceUserId);
13151        }
13152    }
13153
13154    @Override
13155    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
13156        mContext.enforceCallingOrSelfPermission(
13157                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
13158        int callingUid = Binder.getCallingUid();
13159        enforceOwnerRights(ownerPackage, callingUid);
13160        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
13161        synchronized (mPackages) {
13162            CrossProfileIntentResolver resolver =
13163                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
13164            ArraySet<CrossProfileIntentFilter> set =
13165                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
13166            for (CrossProfileIntentFilter filter : set) {
13167                if (filter.getOwnerPackage().equals(ownerPackage)) {
13168                    resolver.removeFilter(filter);
13169                }
13170            }
13171            scheduleWritePackageRestrictionsLocked(sourceUserId);
13172        }
13173    }
13174
13175    // Enforcing that callingUid is owning pkg on userId
13176    private void enforceOwnerRights(String pkg, int callingUid) {
13177        // The system owns everything.
13178        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
13179            return;
13180        }
13181        int callingUserId = UserHandle.getUserId(callingUid);
13182        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
13183        if (pi == null) {
13184            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
13185                    + callingUserId);
13186        }
13187        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
13188            throw new SecurityException("Calling uid " + callingUid
13189                    + " does not own package " + pkg);
13190        }
13191    }
13192
13193    @Override
13194    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
13195        Intent intent = new Intent(Intent.ACTION_MAIN);
13196        intent.addCategory(Intent.CATEGORY_HOME);
13197
13198        final int callingUserId = UserHandle.getCallingUserId();
13199        List<ResolveInfo> list = queryIntentActivities(intent, null,
13200                PackageManager.GET_META_DATA, callingUserId);
13201        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
13202                true, false, false, callingUserId);
13203
13204        allHomeCandidates.clear();
13205        if (list != null) {
13206            for (ResolveInfo ri : list) {
13207                allHomeCandidates.add(ri);
13208            }
13209        }
13210        return (preferred == null || preferred.activityInfo == null)
13211                ? null
13212                : new ComponentName(preferred.activityInfo.packageName,
13213                        preferred.activityInfo.name);
13214    }
13215
13216    @Override
13217    public void setApplicationEnabledSetting(String appPackageName,
13218            int newState, int flags, int userId, String callingPackage) {
13219        if (!sUserManager.exists(userId)) return;
13220        if (callingPackage == null) {
13221            callingPackage = Integer.toString(Binder.getCallingUid());
13222        }
13223        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
13224    }
13225
13226    @Override
13227    public void setComponentEnabledSetting(ComponentName componentName,
13228            int newState, int flags, int userId) {
13229        if (!sUserManager.exists(userId)) return;
13230        setEnabledSetting(componentName.getPackageName(),
13231                componentName.getClassName(), newState, flags, userId, null);
13232    }
13233
13234    private void setEnabledSetting(final String packageName, String className, int newState,
13235            final int flags, int userId, String callingPackage) {
13236        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
13237              || newState == COMPONENT_ENABLED_STATE_ENABLED
13238              || newState == COMPONENT_ENABLED_STATE_DISABLED
13239              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
13240              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
13241            throw new IllegalArgumentException("Invalid new component state: "
13242                    + newState);
13243        }
13244        PackageSetting pkgSetting;
13245        final int uid = Binder.getCallingUid();
13246        final int permission = mContext.checkCallingOrSelfPermission(
13247                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
13248        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
13249        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
13250        boolean sendNow = false;
13251        boolean isApp = (className == null);
13252        String componentName = isApp ? packageName : className;
13253        int packageUid = -1;
13254        ArrayList<String> components;
13255
13256        // writer
13257        synchronized (mPackages) {
13258            pkgSetting = mSettings.mPackages.get(packageName);
13259            if (pkgSetting == null) {
13260                if (className == null) {
13261                    throw new IllegalArgumentException(
13262                            "Unknown package: " + packageName);
13263                }
13264                throw new IllegalArgumentException(
13265                        "Unknown component: " + packageName
13266                        + "/" + className);
13267            }
13268            // Allow root and verify that userId is not being specified by a different user
13269            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
13270                throw new SecurityException(
13271                        "Permission Denial: attempt to change component state from pid="
13272                        + Binder.getCallingPid()
13273                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
13274            }
13275            if (className == null) {
13276                // We're dealing with an application/package level state change
13277                if (pkgSetting.getEnabled(userId) == newState) {
13278                    // Nothing to do
13279                    return;
13280                }
13281                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
13282                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
13283                    // Don't care about who enables an app.
13284                    callingPackage = null;
13285                }
13286                pkgSetting.setEnabled(newState, userId, callingPackage);
13287                // pkgSetting.pkg.mSetEnabled = newState;
13288            } else {
13289                // We're dealing with a component level state change
13290                // First, verify that this is a valid class name.
13291                PackageParser.Package pkg = pkgSetting.pkg;
13292                if (pkg == null || !pkg.hasComponentClassName(className)) {
13293                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
13294                        throw new IllegalArgumentException("Component class " + className
13295                                + " does not exist in " + packageName);
13296                    } else {
13297                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
13298                                + className + " does not exist in " + packageName);
13299                    }
13300                }
13301                switch (newState) {
13302                case COMPONENT_ENABLED_STATE_ENABLED:
13303                    if (!pkgSetting.enableComponentLPw(className, userId)) {
13304                        return;
13305                    }
13306                    break;
13307                case COMPONENT_ENABLED_STATE_DISABLED:
13308                    if (!pkgSetting.disableComponentLPw(className, userId)) {
13309                        return;
13310                    }
13311                    break;
13312                case COMPONENT_ENABLED_STATE_DEFAULT:
13313                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
13314                        return;
13315                    }
13316                    break;
13317                default:
13318                    Slog.e(TAG, "Invalid new component state: " + newState);
13319                    return;
13320                }
13321            }
13322            scheduleWritePackageRestrictionsLocked(userId);
13323            components = mPendingBroadcasts.get(userId, packageName);
13324            final boolean newPackage = components == null;
13325            if (newPackage) {
13326                components = new ArrayList<String>();
13327            }
13328            if (!components.contains(componentName)) {
13329                components.add(componentName);
13330            }
13331            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
13332                sendNow = true;
13333                // Purge entry from pending broadcast list if another one exists already
13334                // since we are sending one right away.
13335                mPendingBroadcasts.remove(userId, packageName);
13336            } else {
13337                if (newPackage) {
13338                    mPendingBroadcasts.put(userId, packageName, components);
13339                }
13340                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
13341                    // Schedule a message
13342                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
13343                }
13344            }
13345        }
13346
13347        long callingId = Binder.clearCallingIdentity();
13348        try {
13349            if (sendNow) {
13350                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
13351                sendPackageChangedBroadcast(packageName,
13352                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
13353            }
13354        } finally {
13355            Binder.restoreCallingIdentity(callingId);
13356        }
13357    }
13358
13359    private void sendPackageChangedBroadcast(String packageName,
13360            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
13361        if (DEBUG_INSTALL)
13362            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
13363                    + componentNames);
13364        Bundle extras = new Bundle(4);
13365        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
13366        String nameList[] = new String[componentNames.size()];
13367        componentNames.toArray(nameList);
13368        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
13369        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
13370        extras.putInt(Intent.EXTRA_UID, packageUid);
13371        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
13372                new int[] {UserHandle.getUserId(packageUid)});
13373    }
13374
13375    @Override
13376    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
13377        if (!sUserManager.exists(userId)) return;
13378        final int uid = Binder.getCallingUid();
13379        final int permission = mContext.checkCallingOrSelfPermission(
13380                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
13381        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
13382        enforceCrossUserPermission(uid, userId, true, true, "stop package");
13383        // writer
13384        synchronized (mPackages) {
13385            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
13386                    allowedByPermission, uid, userId)) {
13387                scheduleWritePackageRestrictionsLocked(userId);
13388            }
13389        }
13390    }
13391
13392    @Override
13393    public String getInstallerPackageName(String packageName) {
13394        // reader
13395        synchronized (mPackages) {
13396            return mSettings.getInstallerPackageNameLPr(packageName);
13397        }
13398    }
13399
13400    @Override
13401    public int getApplicationEnabledSetting(String packageName, int userId) {
13402        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
13403        int uid = Binder.getCallingUid();
13404        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
13405        // reader
13406        synchronized (mPackages) {
13407            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
13408        }
13409    }
13410
13411    @Override
13412    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
13413        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
13414        int uid = Binder.getCallingUid();
13415        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
13416        // reader
13417        synchronized (mPackages) {
13418            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
13419        }
13420    }
13421
13422    @Override
13423    public void enterSafeMode() {
13424        enforceSystemOrRoot("Only the system can request entering safe mode");
13425
13426        if (!mSystemReady) {
13427            mSafeMode = true;
13428        }
13429    }
13430
13431    @Override
13432    public void systemReady() {
13433        mSystemReady = true;
13434
13435        // Read the compatibilty setting when the system is ready.
13436        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
13437                mContext.getContentResolver(),
13438                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
13439        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
13440        if (DEBUG_SETTINGS) {
13441            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
13442        }
13443
13444        synchronized (mPackages) {
13445            // Verify that all of the preferred activity components actually
13446            // exist.  It is possible for applications to be updated and at
13447            // that point remove a previously declared activity component that
13448            // had been set as a preferred activity.  We try to clean this up
13449            // the next time we encounter that preferred activity, but it is
13450            // possible for the user flow to never be able to return to that
13451            // situation so here we do a sanity check to make sure we haven't
13452            // left any junk around.
13453            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
13454            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13455                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13456                removed.clear();
13457                for (PreferredActivity pa : pir.filterSet()) {
13458                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
13459                        removed.add(pa);
13460                    }
13461                }
13462                if (removed.size() > 0) {
13463                    for (int r=0; r<removed.size(); r++) {
13464                        PreferredActivity pa = removed.get(r);
13465                        Slog.w(TAG, "Removing dangling preferred activity: "
13466                                + pa.mPref.mComponent);
13467                        pir.removeFilter(pa);
13468                    }
13469                    mSettings.writePackageRestrictionsLPr(
13470                            mSettings.mPreferredActivities.keyAt(i));
13471                }
13472            }
13473        }
13474        sUserManager.systemReady();
13475
13476        // Kick off any messages waiting for system ready
13477        if (mPostSystemReadyMessages != null) {
13478            for (Message msg : mPostSystemReadyMessages) {
13479                msg.sendToTarget();
13480            }
13481            mPostSystemReadyMessages = null;
13482        }
13483
13484        // Watch for external volumes that come and go over time
13485        final StorageManager storage = mContext.getSystemService(StorageManager.class);
13486        storage.registerListener(mStorageListener);
13487
13488        mInstallerService.systemReady();
13489        mPackageDexOptimizer.systemReady();
13490    }
13491
13492    @Override
13493    public boolean isSafeMode() {
13494        return mSafeMode;
13495    }
13496
13497    @Override
13498    public boolean hasSystemUidErrors() {
13499        return mHasSystemUidErrors;
13500    }
13501
13502    static String arrayToString(int[] array) {
13503        StringBuffer buf = new StringBuffer(128);
13504        buf.append('[');
13505        if (array != null) {
13506            for (int i=0; i<array.length; i++) {
13507                if (i > 0) buf.append(", ");
13508                buf.append(array[i]);
13509            }
13510        }
13511        buf.append(']');
13512        return buf.toString();
13513    }
13514
13515    static class DumpState {
13516        public static final int DUMP_LIBS = 1 << 0;
13517        public static final int DUMP_FEATURES = 1 << 1;
13518        public static final int DUMP_RESOLVERS = 1 << 2;
13519        public static final int DUMP_PERMISSIONS = 1 << 3;
13520        public static final int DUMP_PACKAGES = 1 << 4;
13521        public static final int DUMP_SHARED_USERS = 1 << 5;
13522        public static final int DUMP_MESSAGES = 1 << 6;
13523        public static final int DUMP_PROVIDERS = 1 << 7;
13524        public static final int DUMP_VERIFIERS = 1 << 8;
13525        public static final int DUMP_PREFERRED = 1 << 9;
13526        public static final int DUMP_PREFERRED_XML = 1 << 10;
13527        public static final int DUMP_KEYSETS = 1 << 11;
13528        public static final int DUMP_VERSION = 1 << 12;
13529        public static final int DUMP_INSTALLS = 1 << 13;
13530        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
13531        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
13532
13533        public static final int OPTION_SHOW_FILTERS = 1 << 0;
13534
13535        private int mTypes;
13536
13537        private int mOptions;
13538
13539        private boolean mTitlePrinted;
13540
13541        private SharedUserSetting mSharedUser;
13542
13543        public boolean isDumping(int type) {
13544            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
13545                return true;
13546            }
13547
13548            return (mTypes & type) != 0;
13549        }
13550
13551        public void setDump(int type) {
13552            mTypes |= type;
13553        }
13554
13555        public boolean isOptionEnabled(int option) {
13556            return (mOptions & option) != 0;
13557        }
13558
13559        public void setOptionEnabled(int option) {
13560            mOptions |= option;
13561        }
13562
13563        public boolean onTitlePrinted() {
13564            final boolean printed = mTitlePrinted;
13565            mTitlePrinted = true;
13566            return printed;
13567        }
13568
13569        public boolean getTitlePrinted() {
13570            return mTitlePrinted;
13571        }
13572
13573        public void setTitlePrinted(boolean enabled) {
13574            mTitlePrinted = enabled;
13575        }
13576
13577        public SharedUserSetting getSharedUser() {
13578            return mSharedUser;
13579        }
13580
13581        public void setSharedUser(SharedUserSetting user) {
13582            mSharedUser = user;
13583        }
13584    }
13585
13586    @Override
13587    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
13588        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
13589                != PackageManager.PERMISSION_GRANTED) {
13590            pw.println("Permission Denial: can't dump ActivityManager from from pid="
13591                    + Binder.getCallingPid()
13592                    + ", uid=" + Binder.getCallingUid()
13593                    + " without permission "
13594                    + android.Manifest.permission.DUMP);
13595            return;
13596        }
13597
13598        DumpState dumpState = new DumpState();
13599        boolean fullPreferred = false;
13600        boolean checkin = false;
13601
13602        String packageName = null;
13603
13604        int opti = 0;
13605        while (opti < args.length) {
13606            String opt = args[opti];
13607            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
13608                break;
13609            }
13610            opti++;
13611
13612            if ("-a".equals(opt)) {
13613                // Right now we only know how to print all.
13614            } else if ("-h".equals(opt)) {
13615                pw.println("Package manager dump options:");
13616                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
13617                pw.println("    --checkin: dump for a checkin");
13618                pw.println("    -f: print details of intent filters");
13619                pw.println("    -h: print this help");
13620                pw.println("  cmd may be one of:");
13621                pw.println("    l[ibraries]: list known shared libraries");
13622                pw.println("    f[ibraries]: list device features");
13623                pw.println("    k[eysets]: print known keysets");
13624                pw.println("    r[esolvers]: dump intent resolvers");
13625                pw.println("    perm[issions]: dump permissions");
13626                pw.println("    pref[erred]: print preferred package settings");
13627                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
13628                pw.println("    prov[iders]: dump content providers");
13629                pw.println("    p[ackages]: dump installed packages");
13630                pw.println("    s[hared-users]: dump shared user IDs");
13631                pw.println("    m[essages]: print collected runtime messages");
13632                pw.println("    v[erifiers]: print package verifier info");
13633                pw.println("    version: print database version info");
13634                pw.println("    write: write current settings now");
13635                pw.println("    <package.name>: info about given package");
13636                pw.println("    installs: details about install sessions");
13637                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
13638                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
13639                return;
13640            } else if ("--checkin".equals(opt)) {
13641                checkin = true;
13642            } else if ("-f".equals(opt)) {
13643                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
13644            } else {
13645                pw.println("Unknown argument: " + opt + "; use -h for help");
13646            }
13647        }
13648
13649        // Is the caller requesting to dump a particular piece of data?
13650        if (opti < args.length) {
13651            String cmd = args[opti];
13652            opti++;
13653            // Is this a package name?
13654            if ("android".equals(cmd) || cmd.contains(".")) {
13655                packageName = cmd;
13656                // When dumping a single package, we always dump all of its
13657                // filter information since the amount of data will be reasonable.
13658                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
13659            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
13660                dumpState.setDump(DumpState.DUMP_LIBS);
13661            } else if ("f".equals(cmd) || "features".equals(cmd)) {
13662                dumpState.setDump(DumpState.DUMP_FEATURES);
13663            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
13664                dumpState.setDump(DumpState.DUMP_RESOLVERS);
13665            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
13666                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
13667            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
13668                dumpState.setDump(DumpState.DUMP_PREFERRED);
13669            } else if ("preferred-xml".equals(cmd)) {
13670                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
13671                if (opti < args.length && "--full".equals(args[opti])) {
13672                    fullPreferred = true;
13673                    opti++;
13674                }
13675            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
13676                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
13677            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
13678                dumpState.setDump(DumpState.DUMP_PACKAGES);
13679            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
13680                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
13681            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
13682                dumpState.setDump(DumpState.DUMP_PROVIDERS);
13683            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
13684                dumpState.setDump(DumpState.DUMP_MESSAGES);
13685            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
13686                dumpState.setDump(DumpState.DUMP_VERIFIERS);
13687            } else if ("i".equals(cmd) || "ifv".equals(cmd)
13688                    || "intent-filter-verifiers".equals(cmd)) {
13689                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
13690            } else if ("version".equals(cmd)) {
13691                dumpState.setDump(DumpState.DUMP_VERSION);
13692            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
13693                dumpState.setDump(DumpState.DUMP_KEYSETS);
13694            } else if ("installs".equals(cmd)) {
13695                dumpState.setDump(DumpState.DUMP_INSTALLS);
13696            } else if ("write".equals(cmd)) {
13697                synchronized (mPackages) {
13698                    mSettings.writeLPr();
13699                    pw.println("Settings written.");
13700                    return;
13701                }
13702            }
13703        }
13704
13705        if (checkin) {
13706            pw.println("vers,1");
13707        }
13708
13709        // reader
13710        synchronized (mPackages) {
13711            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
13712                if (!checkin) {
13713                    if (dumpState.onTitlePrinted())
13714                        pw.println();
13715                    pw.println("Database versions:");
13716                    pw.print("  SDK Version:");
13717                    pw.print(" internal=");
13718                    pw.print(mSettings.mInternalSdkPlatform);
13719                    pw.print(" external=");
13720                    pw.println(mSettings.mExternalSdkPlatform);
13721                    pw.print("  DB Version:");
13722                    pw.print(" internal=");
13723                    pw.print(mSettings.mInternalDatabaseVersion);
13724                    pw.print(" external=");
13725                    pw.println(mSettings.mExternalDatabaseVersion);
13726                }
13727            }
13728
13729            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
13730                if (!checkin) {
13731                    if (dumpState.onTitlePrinted())
13732                        pw.println();
13733                    pw.println("Verifiers:");
13734                    pw.print("  Required: ");
13735                    pw.print(mRequiredVerifierPackage);
13736                    pw.print(" (uid=");
13737                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
13738                    pw.println(")");
13739                } else if (mRequiredVerifierPackage != null) {
13740                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
13741                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
13742                }
13743            }
13744
13745            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
13746                    packageName == null) {
13747                if (mIntentFilterVerifierComponent != null) {
13748                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
13749                    if (!checkin) {
13750                        if (dumpState.onTitlePrinted())
13751                            pw.println();
13752                        pw.println("Intent Filter Verifier:");
13753                        pw.print("  Using: ");
13754                        pw.print(verifierPackageName);
13755                        pw.print(" (uid=");
13756                        pw.print(getPackageUid(verifierPackageName, 0));
13757                        pw.println(")");
13758                    } else if (verifierPackageName != null) {
13759                        pw.print("ifv,"); pw.print(verifierPackageName);
13760                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
13761                    }
13762                } else {
13763                    pw.println();
13764                    pw.println("No Intent Filter Verifier available!");
13765                }
13766            }
13767
13768            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
13769                boolean printedHeader = false;
13770                final Iterator<String> it = mSharedLibraries.keySet().iterator();
13771                while (it.hasNext()) {
13772                    String name = it.next();
13773                    SharedLibraryEntry ent = mSharedLibraries.get(name);
13774                    if (!checkin) {
13775                        if (!printedHeader) {
13776                            if (dumpState.onTitlePrinted())
13777                                pw.println();
13778                            pw.println("Libraries:");
13779                            printedHeader = true;
13780                        }
13781                        pw.print("  ");
13782                    } else {
13783                        pw.print("lib,");
13784                    }
13785                    pw.print(name);
13786                    if (!checkin) {
13787                        pw.print(" -> ");
13788                    }
13789                    if (ent.path != null) {
13790                        if (!checkin) {
13791                            pw.print("(jar) ");
13792                            pw.print(ent.path);
13793                        } else {
13794                            pw.print(",jar,");
13795                            pw.print(ent.path);
13796                        }
13797                    } else {
13798                        if (!checkin) {
13799                            pw.print("(apk) ");
13800                            pw.print(ent.apk);
13801                        } else {
13802                            pw.print(",apk,");
13803                            pw.print(ent.apk);
13804                        }
13805                    }
13806                    pw.println();
13807                }
13808            }
13809
13810            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
13811                if (dumpState.onTitlePrinted())
13812                    pw.println();
13813                if (!checkin) {
13814                    pw.println("Features:");
13815                }
13816                Iterator<String> it = mAvailableFeatures.keySet().iterator();
13817                while (it.hasNext()) {
13818                    String name = it.next();
13819                    if (!checkin) {
13820                        pw.print("  ");
13821                    } else {
13822                        pw.print("feat,");
13823                    }
13824                    pw.println(name);
13825                }
13826            }
13827
13828            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
13829                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
13830                        : "Activity Resolver Table:", "  ", packageName,
13831                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
13832                    dumpState.setTitlePrinted(true);
13833                }
13834                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
13835                        : "Receiver Resolver Table:", "  ", packageName,
13836                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
13837                    dumpState.setTitlePrinted(true);
13838                }
13839                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
13840                        : "Service Resolver Table:", "  ", packageName,
13841                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
13842                    dumpState.setTitlePrinted(true);
13843                }
13844                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
13845                        : "Provider Resolver Table:", "  ", packageName,
13846                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
13847                    dumpState.setTitlePrinted(true);
13848                }
13849            }
13850
13851            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
13852                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13853                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13854                    int user = mSettings.mPreferredActivities.keyAt(i);
13855                    if (pir.dump(pw,
13856                            dumpState.getTitlePrinted()
13857                                ? "\nPreferred Activities User " + user + ":"
13858                                : "Preferred Activities User " + user + ":", "  ",
13859                            packageName, true, false)) {
13860                        dumpState.setTitlePrinted(true);
13861                    }
13862                }
13863            }
13864
13865            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
13866                pw.flush();
13867                FileOutputStream fout = new FileOutputStream(fd);
13868                BufferedOutputStream str = new BufferedOutputStream(fout);
13869                XmlSerializer serializer = new FastXmlSerializer();
13870                try {
13871                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
13872                    serializer.startDocument(null, true);
13873                    serializer.setFeature(
13874                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
13875                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
13876                    serializer.endDocument();
13877                    serializer.flush();
13878                } catch (IllegalArgumentException e) {
13879                    pw.println("Failed writing: " + e);
13880                } catch (IllegalStateException e) {
13881                    pw.println("Failed writing: " + e);
13882                } catch (IOException e) {
13883                    pw.println("Failed writing: " + e);
13884                }
13885            }
13886
13887            if (!checkin && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)) {
13888                pw.println();
13889                int count = mSettings.mPackages.size();
13890                if (count == 0) {
13891                    pw.println("No domain preferred apps!");
13892                    pw.println();
13893                } else {
13894                    final String prefix = "  ";
13895                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
13896                    if (allPackageSettings.size() == 0) {
13897                        pw.println("No domain preferred apps!");
13898                        pw.println();
13899                    } else {
13900                        pw.println("Domain preferred apps status:");
13901                        pw.println();
13902                        count = 0;
13903                        for (PackageSetting ps : allPackageSettings) {
13904                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
13905                            if (ivi == null || ivi.getPackageName() == null) continue;
13906                            pw.println(prefix + "Package Name: " + ivi.getPackageName());
13907                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
13908                            pw.println(prefix + "Status: " + ivi.getStatusString());
13909                            pw.println();
13910                            count++;
13911                        }
13912                        if (count == 0) {
13913                            pw.println(prefix + "No domain preferred app status!");
13914                            pw.println();
13915                        }
13916                        for (int userId : sUserManager.getUserIds()) {
13917                            pw.println("Domain preferred apps for User " + userId + ":");
13918                            pw.println();
13919                            count = 0;
13920                            for (PackageSetting ps : allPackageSettings) {
13921                                IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
13922                                if (ivi == null || ivi.getPackageName() == null) {
13923                                    continue;
13924                                }
13925                                final int status = ps.getDomainVerificationStatusForUser(userId);
13926                                if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
13927                                    continue;
13928                                }
13929                                pw.println(prefix + "Package Name: " + ivi.getPackageName());
13930                                pw.println(prefix + "Domains: " + ivi.getDomainsString());
13931                                String statusStr = IntentFilterVerificationInfo.
13932                                        getStatusStringFromValue(status);
13933                                pw.println(prefix + "Status: " + statusStr);
13934                                pw.println();
13935                                count++;
13936                            }
13937                            if (count == 0) {
13938                                pw.println(prefix + "No domain preferred apps!");
13939                                pw.println();
13940                            }
13941                        }
13942                    }
13943                }
13944            }
13945
13946            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
13947                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
13948                if (packageName == null) {
13949                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
13950                        if (iperm == 0) {
13951                            if (dumpState.onTitlePrinted())
13952                                pw.println();
13953                            pw.println("AppOp Permissions:");
13954                        }
13955                        pw.print("  AppOp Permission ");
13956                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
13957                        pw.println(":");
13958                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
13959                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
13960                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
13961                        }
13962                    }
13963                }
13964            }
13965
13966            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
13967                boolean printedSomething = false;
13968                for (PackageParser.Provider p : mProviders.mProviders.values()) {
13969                    if (packageName != null && !packageName.equals(p.info.packageName)) {
13970                        continue;
13971                    }
13972                    if (!printedSomething) {
13973                        if (dumpState.onTitlePrinted())
13974                            pw.println();
13975                        pw.println("Registered ContentProviders:");
13976                        printedSomething = true;
13977                    }
13978                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
13979                    pw.print("    "); pw.println(p.toString());
13980                }
13981                printedSomething = false;
13982                for (Map.Entry<String, PackageParser.Provider> entry :
13983                        mProvidersByAuthority.entrySet()) {
13984                    PackageParser.Provider p = entry.getValue();
13985                    if (packageName != null && !packageName.equals(p.info.packageName)) {
13986                        continue;
13987                    }
13988                    if (!printedSomething) {
13989                        if (dumpState.onTitlePrinted())
13990                            pw.println();
13991                        pw.println("ContentProvider Authorities:");
13992                        printedSomething = true;
13993                    }
13994                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
13995                    pw.print("    "); pw.println(p.toString());
13996                    if (p.info != null && p.info.applicationInfo != null) {
13997                        final String appInfo = p.info.applicationInfo.toString();
13998                        pw.print("      applicationInfo="); pw.println(appInfo);
13999                    }
14000                }
14001            }
14002
14003            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
14004                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
14005            }
14006
14007            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
14008                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
14009            }
14010
14011            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
14012                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin);
14013            }
14014
14015            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
14016                // XXX should handle packageName != null by dumping only install data that
14017                // the given package is involved with.
14018                if (dumpState.onTitlePrinted()) pw.println();
14019                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
14020            }
14021
14022            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
14023                if (dumpState.onTitlePrinted()) pw.println();
14024                mSettings.dumpReadMessagesLPr(pw, dumpState);
14025
14026                pw.println();
14027                pw.println("Package warning messages:");
14028                BufferedReader in = null;
14029                String line = null;
14030                try {
14031                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
14032                    while ((line = in.readLine()) != null) {
14033                        if (line.contains("ignored: updated version")) continue;
14034                        pw.println(line);
14035                    }
14036                } catch (IOException ignored) {
14037                } finally {
14038                    IoUtils.closeQuietly(in);
14039                }
14040            }
14041
14042            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
14043                BufferedReader in = null;
14044                String line = null;
14045                try {
14046                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
14047                    while ((line = in.readLine()) != null) {
14048                        if (line.contains("ignored: updated version")) continue;
14049                        pw.print("msg,");
14050                        pw.println(line);
14051                    }
14052                } catch (IOException ignored) {
14053                } finally {
14054                    IoUtils.closeQuietly(in);
14055                }
14056            }
14057        }
14058    }
14059
14060    // ------- apps on sdcard specific code -------
14061    static final boolean DEBUG_SD_INSTALL = false;
14062
14063    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
14064
14065    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
14066
14067    private boolean mMediaMounted = false;
14068
14069    static String getEncryptKey() {
14070        try {
14071            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
14072                    SD_ENCRYPTION_KEYSTORE_NAME);
14073            if (sdEncKey == null) {
14074                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
14075                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
14076                if (sdEncKey == null) {
14077                    Slog.e(TAG, "Failed to create encryption keys");
14078                    return null;
14079                }
14080            }
14081            return sdEncKey;
14082        } catch (NoSuchAlgorithmException nsae) {
14083            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
14084            return null;
14085        } catch (IOException ioe) {
14086            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
14087            return null;
14088        }
14089    }
14090
14091    /*
14092     * Update media status on PackageManager.
14093     */
14094    @Override
14095    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
14096        int callingUid = Binder.getCallingUid();
14097        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
14098            throw new SecurityException("Media status can only be updated by the system");
14099        }
14100        // reader; this apparently protects mMediaMounted, but should probably
14101        // be a different lock in that case.
14102        synchronized (mPackages) {
14103            Log.i(TAG, "Updating external media status from "
14104                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
14105                    + (mediaStatus ? "mounted" : "unmounted"));
14106            if (DEBUG_SD_INSTALL)
14107                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
14108                        + ", mMediaMounted=" + mMediaMounted);
14109            if (mediaStatus == mMediaMounted) {
14110                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
14111                        : 0, -1);
14112                mHandler.sendMessage(msg);
14113                return;
14114            }
14115            mMediaMounted = mediaStatus;
14116        }
14117        // Queue up an async operation since the package installation may take a
14118        // little while.
14119        mHandler.post(new Runnable() {
14120            public void run() {
14121                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
14122            }
14123        });
14124    }
14125
14126    /**
14127     * Called by MountService when the initial ASECs to scan are available.
14128     * Should block until all the ASEC containers are finished being scanned.
14129     */
14130    public void scanAvailableAsecs() {
14131        updateExternalMediaStatusInner(true, false, false);
14132        if (mShouldRestoreconData) {
14133            SELinuxMMAC.setRestoreconDone();
14134            mShouldRestoreconData = false;
14135        }
14136    }
14137
14138    /*
14139     * Collect information of applications on external media, map them against
14140     * existing containers and update information based on current mount status.
14141     * Please note that we always have to report status if reportStatus has been
14142     * set to true especially when unloading packages.
14143     */
14144    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
14145            boolean externalStorage) {
14146        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
14147        int[] uidArr = EmptyArray.INT;
14148
14149        final String[] list = PackageHelper.getSecureContainerList();
14150        if (ArrayUtils.isEmpty(list)) {
14151            Log.i(TAG, "No secure containers found");
14152        } else {
14153            // Process list of secure containers and categorize them
14154            // as active or stale based on their package internal state.
14155
14156            // reader
14157            synchronized (mPackages) {
14158                for (String cid : list) {
14159                    // Leave stages untouched for now; installer service owns them
14160                    if (PackageInstallerService.isStageName(cid)) continue;
14161
14162                    if (DEBUG_SD_INSTALL)
14163                        Log.i(TAG, "Processing container " + cid);
14164                    String pkgName = getAsecPackageName(cid);
14165                    if (pkgName == null) {
14166                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
14167                        continue;
14168                    }
14169                    if (DEBUG_SD_INSTALL)
14170                        Log.i(TAG, "Looking for pkg : " + pkgName);
14171
14172                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
14173                    if (ps == null) {
14174                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
14175                        continue;
14176                    }
14177
14178                    /*
14179                     * Skip packages that are not external if we're unmounting
14180                     * external storage.
14181                     */
14182                    if (externalStorage && !isMounted && !isExternal(ps)) {
14183                        continue;
14184                    }
14185
14186                    final AsecInstallArgs args = new AsecInstallArgs(cid,
14187                            getAppDexInstructionSets(ps), ps.isForwardLocked());
14188                    // The package status is changed only if the code path
14189                    // matches between settings and the container id.
14190                    if (ps.codePathString != null
14191                            && ps.codePathString.startsWith(args.getCodePath())) {
14192                        if (DEBUG_SD_INSTALL) {
14193                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
14194                                    + " at code path: " + ps.codePathString);
14195                        }
14196
14197                        // We do have a valid package installed on sdcard
14198                        processCids.put(args, ps.codePathString);
14199                        final int uid = ps.appId;
14200                        if (uid != -1) {
14201                            uidArr = ArrayUtils.appendInt(uidArr, uid);
14202                        }
14203                    } else {
14204                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
14205                                + ps.codePathString);
14206                    }
14207                }
14208            }
14209
14210            Arrays.sort(uidArr);
14211        }
14212
14213        // Process packages with valid entries.
14214        if (isMounted) {
14215            if (DEBUG_SD_INSTALL)
14216                Log.i(TAG, "Loading packages");
14217            loadMediaPackages(processCids, uidArr);
14218            startCleaningPackages();
14219            mInstallerService.onSecureContainersAvailable();
14220        } else {
14221            if (DEBUG_SD_INSTALL)
14222                Log.i(TAG, "Unloading packages");
14223            unloadMediaPackages(processCids, uidArr, reportStatus);
14224        }
14225    }
14226
14227    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14228            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
14229        final int size = infos.size();
14230        final String[] packageNames = new String[size];
14231        final int[] packageUids = new int[size];
14232        for (int i = 0; i < size; i++) {
14233            final ApplicationInfo info = infos.get(i);
14234            packageNames[i] = info.packageName;
14235            packageUids[i] = info.uid;
14236        }
14237        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
14238                finishedReceiver);
14239    }
14240
14241    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14242            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
14243        sendResourcesChangedBroadcast(mediaStatus, replacing,
14244                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
14245    }
14246
14247    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14248            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
14249        int size = pkgList.length;
14250        if (size > 0) {
14251            // Send broadcasts here
14252            Bundle extras = new Bundle();
14253            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14254            if (uidArr != null) {
14255                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
14256            }
14257            if (replacing) {
14258                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
14259            }
14260            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
14261                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
14262            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
14263        }
14264    }
14265
14266   /*
14267     * Look at potentially valid container ids from processCids If package
14268     * information doesn't match the one on record or package scanning fails,
14269     * the cid is added to list of removeCids. We currently don't delete stale
14270     * containers.
14271     */
14272    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
14273        ArrayList<String> pkgList = new ArrayList<String>();
14274        Set<AsecInstallArgs> keys = processCids.keySet();
14275
14276        for (AsecInstallArgs args : keys) {
14277            String codePath = processCids.get(args);
14278            if (DEBUG_SD_INSTALL)
14279                Log.i(TAG, "Loading container : " + args.cid);
14280            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14281            try {
14282                // Make sure there are no container errors first.
14283                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
14284                    Slog.e(TAG, "Failed to mount cid : " + args.cid
14285                            + " when installing from sdcard");
14286                    continue;
14287                }
14288                // Check code path here.
14289                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
14290                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
14291                            + " does not match one in settings " + codePath);
14292                    continue;
14293                }
14294                // Parse package
14295                int parseFlags = mDefParseFlags;
14296                if (args.isExternalAsec()) {
14297                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
14298                }
14299                if (args.isFwdLocked()) {
14300                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
14301                }
14302
14303                synchronized (mInstallLock) {
14304                    PackageParser.Package pkg = null;
14305                    try {
14306                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
14307                    } catch (PackageManagerException e) {
14308                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
14309                    }
14310                    // Scan the package
14311                    if (pkg != null) {
14312                        /*
14313                         * TODO why is the lock being held? doPostInstall is
14314                         * called in other places without the lock. This needs
14315                         * to be straightened out.
14316                         */
14317                        // writer
14318                        synchronized (mPackages) {
14319                            retCode = PackageManager.INSTALL_SUCCEEDED;
14320                            pkgList.add(pkg.packageName);
14321                            // Post process args
14322                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
14323                                    pkg.applicationInfo.uid);
14324                        }
14325                    } else {
14326                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
14327                    }
14328                }
14329
14330            } finally {
14331                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
14332                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
14333                }
14334            }
14335        }
14336        // writer
14337        synchronized (mPackages) {
14338            // If the platform SDK has changed since the last time we booted,
14339            // we need to re-grant app permission to catch any new ones that
14340            // appear. This is really a hack, and means that apps can in some
14341            // cases get permissions that the user didn't initially explicitly
14342            // allow... it would be nice to have some better way to handle
14343            // this situation.
14344            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
14345            if (regrantPermissions)
14346                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
14347                        + mSdkVersion + "; regranting permissions for external storage");
14348            mSettings.mExternalSdkPlatform = mSdkVersion;
14349
14350            // Make sure group IDs have been assigned, and any permission
14351            // changes in other apps are accounted for
14352            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
14353                    | (regrantPermissions
14354                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
14355                            : 0));
14356
14357            mSettings.updateExternalDatabaseVersion();
14358
14359            // can downgrade to reader
14360            // Persist settings
14361            mSettings.writeLPr();
14362        }
14363        // Send a broadcast to let everyone know we are done processing
14364        if (pkgList.size() > 0) {
14365            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
14366        }
14367    }
14368
14369   /*
14370     * Utility method to unload a list of specified containers
14371     */
14372    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
14373        // Just unmount all valid containers.
14374        for (AsecInstallArgs arg : cidArgs) {
14375            synchronized (mInstallLock) {
14376                arg.doPostDeleteLI(false);
14377           }
14378       }
14379   }
14380
14381    /*
14382     * Unload packages mounted on external media. This involves deleting package
14383     * data from internal structures, sending broadcasts about diabled packages,
14384     * gc'ing to free up references, unmounting all secure containers
14385     * corresponding to packages on external media, and posting a
14386     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
14387     * that we always have to post this message if status has been requested no
14388     * matter what.
14389     */
14390    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
14391            final boolean reportStatus) {
14392        if (DEBUG_SD_INSTALL)
14393            Log.i(TAG, "unloading media packages");
14394        ArrayList<String> pkgList = new ArrayList<String>();
14395        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
14396        final Set<AsecInstallArgs> keys = processCids.keySet();
14397        for (AsecInstallArgs args : keys) {
14398            String pkgName = args.getPackageName();
14399            if (DEBUG_SD_INSTALL)
14400                Log.i(TAG, "Trying to unload pkg : " + pkgName);
14401            // Delete package internally
14402            PackageRemovedInfo outInfo = new PackageRemovedInfo();
14403            synchronized (mInstallLock) {
14404                boolean res = deletePackageLI(pkgName, null, false, null, null,
14405                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
14406                if (res) {
14407                    pkgList.add(pkgName);
14408                } else {
14409                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
14410                    failedList.add(args);
14411                }
14412            }
14413        }
14414
14415        // reader
14416        synchronized (mPackages) {
14417            // We didn't update the settings after removing each package;
14418            // write them now for all packages.
14419            mSettings.writeLPr();
14420        }
14421
14422        // We have to absolutely send UPDATED_MEDIA_STATUS only
14423        // after confirming that all the receivers processed the ordered
14424        // broadcast when packages get disabled, force a gc to clean things up.
14425        // and unload all the containers.
14426        if (pkgList.size() > 0) {
14427            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
14428                    new IIntentReceiver.Stub() {
14429                public void performReceive(Intent intent, int resultCode, String data,
14430                        Bundle extras, boolean ordered, boolean sticky,
14431                        int sendingUser) throws RemoteException {
14432                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
14433                            reportStatus ? 1 : 0, 1, keys);
14434                    mHandler.sendMessage(msg);
14435                }
14436            });
14437        } else {
14438            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
14439                    keys);
14440            mHandler.sendMessage(msg);
14441        }
14442    }
14443
14444    private void loadPrivatePackages(VolumeInfo vol) {
14445        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
14446        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
14447        synchronized (mInstallLock) {
14448        synchronized (mPackages) {
14449            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
14450            for (PackageSetting ps : packages) {
14451                final PackageParser.Package pkg;
14452                try {
14453                    pkg = scanPackageLI(ps.codePath, parseFlags, 0, 0, null);
14454                    loaded.add(pkg.applicationInfo);
14455                } catch (PackageManagerException e) {
14456                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
14457                }
14458            }
14459
14460            // TODO: regrant any permissions that changed based since original install
14461
14462            mSettings.writeLPr();
14463        }
14464        }
14465
14466        Slog.d(TAG, "Loaded packages " + loaded);
14467        sendResourcesChangedBroadcast(true, false, loaded, null);
14468    }
14469
14470    private void unloadPrivatePackages(VolumeInfo vol) {
14471        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
14472        synchronized (mInstallLock) {
14473        synchronized (mPackages) {
14474            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
14475            for (PackageSetting ps : packages) {
14476                if (ps.pkg == null) continue;
14477
14478                final ApplicationInfo info = ps.pkg.applicationInfo;
14479                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
14480                if (deletePackageLI(ps.name, null, false, null, null,
14481                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
14482                    unloaded.add(info);
14483                } else {
14484                    Slog.w(TAG, "Failed to unload " + ps.codePath);
14485                }
14486            }
14487
14488            mSettings.writeLPr();
14489        }
14490        }
14491
14492        Slog.d(TAG, "Unloaded packages " + unloaded);
14493        sendResourcesChangedBroadcast(false, false, unloaded, null);
14494    }
14495
14496    private void unfreezePackage(String packageName) {
14497        synchronized (mPackages) {
14498            final PackageSetting ps = mSettings.mPackages.get(packageName);
14499            if (ps != null) {
14500                ps.frozen = false;
14501            }
14502        }
14503    }
14504
14505    @Override
14506    public int movePackage(final String packageName, final String volumeUuid) {
14507        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
14508
14509        final int moveId = mNextMoveId.getAndIncrement();
14510        try {
14511            movePackageInternal(packageName, volumeUuid, moveId);
14512        } catch (PackageManagerException e) {
14513            Slog.d(TAG, "Failed to move " + packageName, e);
14514            mMoveCallbacks.notifyStatusChanged(moveId,
14515                    PackageManager.MOVE_FAILED_INTERNAL_ERROR);
14516        }
14517        return moveId;
14518    }
14519
14520    private void movePackageInternal(final String packageName, final String volumeUuid,
14521            final int moveId) throws PackageManagerException {
14522        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
14523        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14524        final PackageManager pm = mContext.getPackageManager();
14525
14526        final boolean currentAsec;
14527        final String currentVolumeUuid;
14528        final File codeFile;
14529        final String installerPackageName;
14530        final String packageAbiOverride;
14531        final int appId;
14532        final String seinfo;
14533        final String label;
14534
14535        // reader
14536        synchronized (mPackages) {
14537            final PackageParser.Package pkg = mPackages.get(packageName);
14538            final PackageSetting ps = mSettings.mPackages.get(packageName);
14539            if (pkg == null || ps == null) {
14540                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
14541            }
14542
14543            if (pkg.applicationInfo.isSystemApp()) {
14544                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
14545                        "Cannot move system application");
14546            }
14547
14548            if (Objects.equals(ps.volumeUuid, volumeUuid)) {
14549                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14550                        "Package already moved to " + volumeUuid);
14551            }
14552
14553            final File probe = new File(pkg.codePath);
14554            final File probeOat = new File(probe, "oat");
14555            if (!probe.isDirectory() || !probeOat.isDirectory()) {
14556                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14557                        "Move only supported for modern cluster style installs");
14558            }
14559
14560            if (ps.frozen) {
14561                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
14562                        "Failed to move already frozen package");
14563            }
14564            ps.frozen = true;
14565
14566            currentAsec = pkg.applicationInfo.isForwardLocked()
14567                    || pkg.applicationInfo.isExternalAsec();
14568            currentVolumeUuid = ps.volumeUuid;
14569            codeFile = new File(pkg.codePath);
14570            installerPackageName = ps.installerPackageName;
14571            packageAbiOverride = ps.cpuAbiOverrideString;
14572            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
14573            seinfo = pkg.applicationInfo.seinfo;
14574            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
14575        }
14576
14577        // Now that we're guarded by frozen state, kill app during move
14578        killApplication(packageName, appId, "move pkg");
14579
14580        final Bundle extras = new Bundle();
14581        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
14582        extras.putString(Intent.EXTRA_TITLE, label);
14583        mMoveCallbacks.notifyCreated(moveId, extras);
14584
14585        int installFlags;
14586        final boolean moveCompleteApp;
14587        final File measurePath;
14588
14589        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
14590            installFlags = INSTALL_INTERNAL;
14591            moveCompleteApp = !currentAsec;
14592            measurePath = Environment.getDataAppDirectory(volumeUuid);
14593        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
14594            installFlags = INSTALL_EXTERNAL;
14595            moveCompleteApp = false;
14596            measurePath = storage.getPrimaryPhysicalVolume().getPath();
14597        } else {
14598            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
14599            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
14600                    || !volume.isMountedWritable()) {
14601                unfreezePackage(packageName);
14602                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14603                        "Move location not mounted private volume");
14604            }
14605
14606            Preconditions.checkState(!currentAsec);
14607
14608            installFlags = INSTALL_INTERNAL;
14609            moveCompleteApp = true;
14610            measurePath = Environment.getDataAppDirectory(volumeUuid);
14611        }
14612
14613        final PackageStats stats = new PackageStats(null, -1);
14614        synchronized (mInstaller) {
14615            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
14616                unfreezePackage(packageName);
14617                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14618                        "Failed to measure package size");
14619            }
14620        }
14621
14622        Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " + stats.dataSize);
14623
14624        final long startFreeBytes = measurePath.getFreeSpace();
14625        final long sizeBytes;
14626        if (moveCompleteApp) {
14627            sizeBytes = stats.codeSize + stats.dataSize;
14628        } else {
14629            sizeBytes = stats.codeSize;
14630        }
14631
14632        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
14633            unfreezePackage(packageName);
14634            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14635                    "Not enough free space to move");
14636        }
14637
14638        mMoveCallbacks.notifyStatusChanged(moveId, 10);
14639
14640        final CountDownLatch installedLatch = new CountDownLatch(1);
14641        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
14642            @Override
14643            public void onUserActionRequired(Intent intent) throws RemoteException {
14644                throw new IllegalStateException();
14645            }
14646
14647            @Override
14648            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
14649                    Bundle extras) throws RemoteException {
14650                Slog.d(TAG, "Install result for move: "
14651                        + PackageManager.installStatusToString(returnCode, msg));
14652
14653                installedLatch.countDown();
14654
14655                // Regardless of success or failure of the move operation,
14656                // always unfreeze the package
14657                unfreezePackage(packageName);
14658
14659                final int status = PackageManager.installStatusToPublicStatus(returnCode);
14660                switch (status) {
14661                    case PackageInstaller.STATUS_SUCCESS:
14662                        mMoveCallbacks.notifyStatusChanged(moveId,
14663                                PackageManager.MOVE_SUCCEEDED);
14664                        break;
14665                    case PackageInstaller.STATUS_FAILURE_STORAGE:
14666                        mMoveCallbacks.notifyStatusChanged(moveId,
14667                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
14668                        break;
14669                    default:
14670                        mMoveCallbacks.notifyStatusChanged(moveId,
14671                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
14672                        break;
14673                }
14674            }
14675        };
14676
14677        final MoveInfo move;
14678        if (moveCompleteApp) {
14679            // Kick off a thread to report progress estimates
14680            new Thread() {
14681                @Override
14682                public void run() {
14683                    while (true) {
14684                        try {
14685                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
14686                                break;
14687                            }
14688                        } catch (InterruptedException ignored) {
14689                        }
14690
14691                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
14692                        final int progress = 10 + (int) MathUtils.constrain(
14693                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
14694                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
14695                    }
14696                }
14697            }.start();
14698
14699            final String dataAppName = codeFile.getName();
14700            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
14701                    dataAppName, appId, seinfo);
14702        } else {
14703            move = null;
14704        }
14705
14706        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
14707
14708        final Message msg = mHandler.obtainMessage(INIT_COPY);
14709        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
14710        msg.obj = new InstallParams(origin, move, installObserver, installFlags,
14711                installerPackageName, volumeUuid, null, user, packageAbiOverride);
14712        mHandler.sendMessage(msg);
14713    }
14714
14715    @Override
14716    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
14717        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
14718
14719        final int realMoveId = mNextMoveId.getAndIncrement();
14720        final Bundle extras = new Bundle();
14721        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
14722        mMoveCallbacks.notifyCreated(realMoveId, extras);
14723
14724        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
14725            @Override
14726            public void onCreated(int moveId, Bundle extras) {
14727                // Ignored
14728            }
14729
14730            @Override
14731            public void onStatusChanged(int moveId, int status, long estMillis) {
14732                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
14733            }
14734        };
14735
14736        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14737        storage.setPrimaryStorageUuid(volumeUuid, callback);
14738        return realMoveId;
14739    }
14740
14741    @Override
14742    public int getMoveStatus(int moveId) {
14743        mContext.enforceCallingOrSelfPermission(
14744                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
14745        return mMoveCallbacks.mLastStatus.get(moveId);
14746    }
14747
14748    @Override
14749    public void registerMoveCallback(IPackageMoveObserver callback) {
14750        mContext.enforceCallingOrSelfPermission(
14751                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
14752        mMoveCallbacks.register(callback);
14753    }
14754
14755    @Override
14756    public void unregisterMoveCallback(IPackageMoveObserver callback) {
14757        mContext.enforceCallingOrSelfPermission(
14758                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
14759        mMoveCallbacks.unregister(callback);
14760    }
14761
14762    @Override
14763    public boolean setInstallLocation(int loc) {
14764        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
14765                null);
14766        if (getInstallLocation() == loc) {
14767            return true;
14768        }
14769        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
14770                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
14771            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
14772                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
14773            return true;
14774        }
14775        return false;
14776   }
14777
14778    @Override
14779    public int getInstallLocation() {
14780        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14781                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
14782                PackageHelper.APP_INSTALL_AUTO);
14783    }
14784
14785    /** Called by UserManagerService */
14786    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
14787        mDirtyUsers.remove(userHandle);
14788        mSettings.removeUserLPw(userHandle);
14789        mPendingBroadcasts.remove(userHandle);
14790        if (mInstaller != null) {
14791            // Technically, we shouldn't be doing this with the package lock
14792            // held.  However, this is very rare, and there is already so much
14793            // other disk I/O going on, that we'll let it slide for now.
14794            final StorageManager storage = StorageManager.from(mContext);
14795            final List<VolumeInfo> vols = storage.getVolumes();
14796            for (VolumeInfo vol : vols) {
14797                if (vol.getType() == VolumeInfo.TYPE_PRIVATE && vol.isMountedWritable()) {
14798                    final String volumeUuid = vol.getFsUuid();
14799                    Slog.d(TAG, "Removing user data on volume " + volumeUuid);
14800                    mInstaller.removeUserDataDirs(volumeUuid, userHandle);
14801                }
14802            }
14803        }
14804        mUserNeedsBadging.delete(userHandle);
14805        removeUnusedPackagesLILPw(userManager, userHandle);
14806    }
14807
14808    /**
14809     * We're removing userHandle and would like to remove any downloaded packages
14810     * that are no longer in use by any other user.
14811     * @param userHandle the user being removed
14812     */
14813    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
14814        final boolean DEBUG_CLEAN_APKS = false;
14815        int [] users = userManager.getUserIdsLPr();
14816        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
14817        while (psit.hasNext()) {
14818            PackageSetting ps = psit.next();
14819            if (ps.pkg == null) {
14820                continue;
14821            }
14822            final String packageName = ps.pkg.packageName;
14823            // Skip over if system app
14824            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
14825                continue;
14826            }
14827            if (DEBUG_CLEAN_APKS) {
14828                Slog.i(TAG, "Checking package " + packageName);
14829            }
14830            boolean keep = false;
14831            for (int i = 0; i < users.length; i++) {
14832                if (users[i] != userHandle && ps.getInstalled(users[i])) {
14833                    keep = true;
14834                    if (DEBUG_CLEAN_APKS) {
14835                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
14836                                + users[i]);
14837                    }
14838                    break;
14839                }
14840            }
14841            if (!keep) {
14842                if (DEBUG_CLEAN_APKS) {
14843                    Slog.i(TAG, "  Removing package " + packageName);
14844                }
14845                mHandler.post(new Runnable() {
14846                    public void run() {
14847                        deletePackageX(packageName, userHandle, 0);
14848                    } //end run
14849                });
14850            }
14851        }
14852    }
14853
14854    /** Called by UserManagerService */
14855    void createNewUserLILPw(int userHandle, File path) {
14856        if (mInstaller != null) {
14857            mInstaller.createUserConfig(userHandle);
14858            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
14859        }
14860    }
14861
14862    void newUserCreatedLILPw(int userHandle) {
14863        // Adding a user requires updating runtime permissions for system apps.
14864        updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
14865    }
14866
14867    @Override
14868    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
14869        mContext.enforceCallingOrSelfPermission(
14870                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14871                "Only package verification agents can read the verifier device identity");
14872
14873        synchronized (mPackages) {
14874            return mSettings.getVerifierDeviceIdentityLPw();
14875        }
14876    }
14877
14878    @Override
14879    public void setPermissionEnforced(String permission, boolean enforced) {
14880        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
14881        if (READ_EXTERNAL_STORAGE.equals(permission)) {
14882            synchronized (mPackages) {
14883                if (mSettings.mReadExternalStorageEnforced == null
14884                        || mSettings.mReadExternalStorageEnforced != enforced) {
14885                    mSettings.mReadExternalStorageEnforced = enforced;
14886                    mSettings.writeLPr();
14887                }
14888            }
14889            // kill any non-foreground processes so we restart them and
14890            // grant/revoke the GID.
14891            final IActivityManager am = ActivityManagerNative.getDefault();
14892            if (am != null) {
14893                final long token = Binder.clearCallingIdentity();
14894                try {
14895                    am.killProcessesBelowForeground("setPermissionEnforcement");
14896                } catch (RemoteException e) {
14897                } finally {
14898                    Binder.restoreCallingIdentity(token);
14899                }
14900            }
14901        } else {
14902            throw new IllegalArgumentException("No selective enforcement for " + permission);
14903        }
14904    }
14905
14906    @Override
14907    @Deprecated
14908    public boolean isPermissionEnforced(String permission) {
14909        return true;
14910    }
14911
14912    @Override
14913    public boolean isStorageLow() {
14914        final long token = Binder.clearCallingIdentity();
14915        try {
14916            final DeviceStorageMonitorInternal
14917                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
14918            if (dsm != null) {
14919                return dsm.isMemoryLow();
14920            } else {
14921                return false;
14922            }
14923        } finally {
14924            Binder.restoreCallingIdentity(token);
14925        }
14926    }
14927
14928    @Override
14929    public IPackageInstaller getPackageInstaller() {
14930        return mInstallerService;
14931    }
14932
14933    private boolean userNeedsBadging(int userId) {
14934        int index = mUserNeedsBadging.indexOfKey(userId);
14935        if (index < 0) {
14936            final UserInfo userInfo;
14937            final long token = Binder.clearCallingIdentity();
14938            try {
14939                userInfo = sUserManager.getUserInfo(userId);
14940            } finally {
14941                Binder.restoreCallingIdentity(token);
14942            }
14943            final boolean b;
14944            if (userInfo != null && userInfo.isManagedProfile()) {
14945                b = true;
14946            } else {
14947                b = false;
14948            }
14949            mUserNeedsBadging.put(userId, b);
14950            return b;
14951        }
14952        return mUserNeedsBadging.valueAt(index);
14953    }
14954
14955    @Override
14956    public KeySet getKeySetByAlias(String packageName, String alias) {
14957        if (packageName == null || alias == null) {
14958            return null;
14959        }
14960        synchronized(mPackages) {
14961            final PackageParser.Package pkg = mPackages.get(packageName);
14962            if (pkg == null) {
14963                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
14964                throw new IllegalArgumentException("Unknown package: " + packageName);
14965            }
14966            KeySetManagerService ksms = mSettings.mKeySetManagerService;
14967            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
14968        }
14969    }
14970
14971    @Override
14972    public KeySet getSigningKeySet(String packageName) {
14973        if (packageName == null) {
14974            return null;
14975        }
14976        synchronized(mPackages) {
14977            final PackageParser.Package pkg = mPackages.get(packageName);
14978            if (pkg == null) {
14979                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
14980                throw new IllegalArgumentException("Unknown package: " + packageName);
14981            }
14982            if (pkg.applicationInfo.uid != Binder.getCallingUid()
14983                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
14984                throw new SecurityException("May not access signing KeySet of other apps.");
14985            }
14986            KeySetManagerService ksms = mSettings.mKeySetManagerService;
14987            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
14988        }
14989    }
14990
14991    @Override
14992    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
14993        if (packageName == null || ks == null) {
14994            return false;
14995        }
14996        synchronized(mPackages) {
14997            final PackageParser.Package pkg = mPackages.get(packageName);
14998            if (pkg == null) {
14999                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15000                throw new IllegalArgumentException("Unknown package: " + packageName);
15001            }
15002            IBinder ksh = ks.getToken();
15003            if (ksh instanceof KeySetHandle) {
15004                KeySetManagerService ksms = mSettings.mKeySetManagerService;
15005                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
15006            }
15007            return false;
15008        }
15009    }
15010
15011    @Override
15012    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
15013        if (packageName == null || ks == null) {
15014            return false;
15015        }
15016        synchronized(mPackages) {
15017            final PackageParser.Package pkg = mPackages.get(packageName);
15018            if (pkg == null) {
15019                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15020                throw new IllegalArgumentException("Unknown package: " + packageName);
15021            }
15022            IBinder ksh = ks.getToken();
15023            if (ksh instanceof KeySetHandle) {
15024                KeySetManagerService ksms = mSettings.mKeySetManagerService;
15025                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
15026            }
15027            return false;
15028        }
15029    }
15030
15031    public void getUsageStatsIfNoPackageUsageInfo() {
15032        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
15033            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
15034            if (usm == null) {
15035                throw new IllegalStateException("UsageStatsManager must be initialized");
15036            }
15037            long now = System.currentTimeMillis();
15038            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
15039            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
15040                String packageName = entry.getKey();
15041                PackageParser.Package pkg = mPackages.get(packageName);
15042                if (pkg == null) {
15043                    continue;
15044                }
15045                UsageStats usage = entry.getValue();
15046                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
15047                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
15048            }
15049        }
15050    }
15051
15052    /**
15053     * Check and throw if the given before/after packages would be considered a
15054     * downgrade.
15055     */
15056    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
15057            throws PackageManagerException {
15058        if (after.versionCode < before.mVersionCode) {
15059            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15060                    "Update version code " + after.versionCode + " is older than current "
15061                    + before.mVersionCode);
15062        } else if (after.versionCode == before.mVersionCode) {
15063            if (after.baseRevisionCode < before.baseRevisionCode) {
15064                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15065                        "Update base revision code " + after.baseRevisionCode
15066                        + " is older than current " + before.baseRevisionCode);
15067            }
15068
15069            if (!ArrayUtils.isEmpty(after.splitNames)) {
15070                for (int i = 0; i < after.splitNames.length; i++) {
15071                    final String splitName = after.splitNames[i];
15072                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
15073                    if (j != -1) {
15074                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
15075                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15076                                    "Update split " + splitName + " revision code "
15077                                    + after.splitRevisionCodes[i] + " is older than current "
15078                                    + before.splitRevisionCodes[j]);
15079                        }
15080                    }
15081                }
15082            }
15083        }
15084    }
15085
15086    private static class MoveCallbacks extends Handler {
15087        private static final int MSG_CREATED = 1;
15088        private static final int MSG_STATUS_CHANGED = 2;
15089
15090        private final RemoteCallbackList<IPackageMoveObserver>
15091                mCallbacks = new RemoteCallbackList<>();
15092
15093        private final SparseIntArray mLastStatus = new SparseIntArray();
15094
15095        public MoveCallbacks(Looper looper) {
15096            super(looper);
15097        }
15098
15099        public void register(IPackageMoveObserver callback) {
15100            mCallbacks.register(callback);
15101        }
15102
15103        public void unregister(IPackageMoveObserver callback) {
15104            mCallbacks.unregister(callback);
15105        }
15106
15107        @Override
15108        public void handleMessage(Message msg) {
15109            final SomeArgs args = (SomeArgs) msg.obj;
15110            final int n = mCallbacks.beginBroadcast();
15111            for (int i = 0; i < n; i++) {
15112                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
15113                try {
15114                    invokeCallback(callback, msg.what, args);
15115                } catch (RemoteException ignored) {
15116                }
15117            }
15118            mCallbacks.finishBroadcast();
15119            args.recycle();
15120        }
15121
15122        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
15123                throws RemoteException {
15124            switch (what) {
15125                case MSG_CREATED: {
15126                    callback.onCreated(args.argi1, (Bundle) args.arg2);
15127                    break;
15128                }
15129                case MSG_STATUS_CHANGED: {
15130                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
15131                    break;
15132                }
15133            }
15134        }
15135
15136        private void notifyCreated(int moveId, Bundle extras) {
15137            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
15138
15139            final SomeArgs args = SomeArgs.obtain();
15140            args.argi1 = moveId;
15141            args.arg2 = extras;
15142            obtainMessage(MSG_CREATED, args).sendToTarget();
15143        }
15144
15145        private void notifyStatusChanged(int moveId, int status) {
15146            notifyStatusChanged(moveId, status, -1);
15147        }
15148
15149        private void notifyStatusChanged(int moveId, int status, long estMillis) {
15150            Slog.v(TAG, "Move " + moveId + " status " + status);
15151
15152            final SomeArgs args = SomeArgs.obtain();
15153            args.argi1 = moveId;
15154            args.argi2 = status;
15155            args.arg3 = estMillis;
15156            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
15157
15158            synchronized (mLastStatus) {
15159                mLastStatus.put(moveId, status);
15160            }
15161        }
15162    }
15163}
15164