PackageManagerService.java revision fe112e7b388fe582a4e57c26fdf651511b0bbb5a
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            return;
3150        }
3151
3152        mContext.enforceCallingOrSelfPermission(
3153                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3154                "grantRuntimePermission");
3155
3156        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3157                "grantRuntimePermission");
3158
3159        boolean gidsChanged = false;
3160        final SettingBase sb;
3161
3162        synchronized (mPackages) {
3163            final PackageParser.Package pkg = mPackages.get(packageName);
3164            if (pkg == null) {
3165                throw new IllegalArgumentException("Unknown package: " + packageName);
3166            }
3167
3168            final BasePermission bp = mSettings.mPermissions.get(name);
3169            if (bp == null) {
3170                throw new IllegalArgumentException("Unknown permission: " + name);
3171            }
3172
3173            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3174
3175            sb = (SettingBase) pkg.mExtras;
3176            if (sb == null) {
3177                throw new IllegalArgumentException("Unknown package: " + packageName);
3178            }
3179
3180            final PermissionsState permissionsState = sb.getPermissionsState();
3181
3182            final int result = permissionsState.grantRuntimePermission(bp, userId);
3183            switch (result) {
3184                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3185                    return;
3186                }
3187
3188                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3189                    gidsChanged = true;
3190                }
3191                break;
3192            }
3193
3194            // Not critical if that is lost - app has to request again.
3195            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3196        }
3197
3198        if (gidsChanged) {
3199            killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED);
3200        }
3201    }
3202
3203    @Override
3204    public void revokeRuntimePermission(String packageName, String name, int userId) {
3205        if (!sUserManager.exists(userId)) {
3206            return;
3207        }
3208
3209        mContext.enforceCallingOrSelfPermission(
3210                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3211                "revokeRuntimePermission");
3212
3213        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3214                "revokeRuntimePermission");
3215
3216        final SettingBase sb;
3217
3218        synchronized (mPackages) {
3219            final PackageParser.Package pkg = mPackages.get(packageName);
3220            if (pkg == null) {
3221                throw new IllegalArgumentException("Unknown package: " + packageName);
3222            }
3223
3224            final BasePermission bp = mSettings.mPermissions.get(name);
3225            if (bp == null) {
3226                throw new IllegalArgumentException("Unknown permission: " + name);
3227            }
3228
3229            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3230
3231            sb = (SettingBase) pkg.mExtras;
3232            if (sb == null) {
3233                throw new IllegalArgumentException("Unknown package: " + packageName);
3234            }
3235
3236            final PermissionsState permissionsState = sb.getPermissionsState();
3237
3238            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3239                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3240                return;
3241            }
3242
3243            // Critical, after this call app should never have the permission.
3244            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3245        }
3246
3247        killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3248    }
3249
3250    @Override
3251    public int getPermissionFlags(String name, String packageName, int userId) {
3252        if (!sUserManager.exists(userId)) {
3253            return 0;
3254        }
3255
3256        mContext.enforceCallingOrSelfPermission(
3257                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3258                "getPermissionFlags");
3259
3260        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3261                "getPermissionFlags");
3262
3263        synchronized (mPackages) {
3264            final PackageParser.Package pkg = mPackages.get(packageName);
3265            if (pkg == null) {
3266                throw new IllegalArgumentException("Unknown package: " + packageName);
3267            }
3268
3269            final BasePermission bp = mSettings.mPermissions.get(name);
3270            if (bp == null) {
3271                throw new IllegalArgumentException("Unknown permission: " + name);
3272            }
3273
3274            SettingBase sb = (SettingBase) pkg.mExtras;
3275            if (sb == null) {
3276                throw new IllegalArgumentException("Unknown package: " + packageName);
3277            }
3278
3279            PermissionsState permissionsState = sb.getPermissionsState();
3280            return permissionsState.getPermissionFlags(name, userId);
3281        }
3282    }
3283
3284    @Override
3285    public void updatePermissionFlags(String name, String packageName, int flagMask,
3286            int flagValues, int userId) {
3287        if (!sUserManager.exists(userId)) {
3288            return;
3289        }
3290
3291        mContext.enforceCallingOrSelfPermission(
3292                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3293                "updatePermissionFlags");
3294
3295        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3296                "updatePermissionFlags");
3297
3298        // Only the system can change policy flags.
3299        if (getCallingUid() != Process.SYSTEM_UID) {
3300            flagMask &= ~PackageManager.FLAG_PERMISSION_POLICY_FIXED;
3301            flagValues &= ~PackageManager.FLAG_PERMISSION_POLICY_FIXED;
3302        }
3303
3304        // Only the package manager can change system flags.
3305        flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3306        flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3307
3308        synchronized (mPackages) {
3309            final PackageParser.Package pkg = mPackages.get(packageName);
3310            if (pkg == null) {
3311                throw new IllegalArgumentException("Unknown package: " + packageName);
3312            }
3313
3314            final BasePermission bp = mSettings.mPermissions.get(name);
3315            if (bp == null) {
3316                throw new IllegalArgumentException("Unknown permission: " + name);
3317            }
3318
3319            SettingBase sb = (SettingBase) pkg.mExtras;
3320            if (sb == null) {
3321                throw new IllegalArgumentException("Unknown package: " + packageName);
3322            }
3323
3324            PermissionsState permissionsState = sb.getPermissionsState();
3325
3326            // Only the package manager can change flags for system component permissions.
3327            final int flags = permissionsState.getPermissionFlags(bp.name, userId);
3328            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3329                return;
3330            }
3331
3332            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3333                // Install and runtime permissions are stored in different places,
3334                // so figure out what permission changed and persist the change.
3335                if (permissionsState.getInstallPermissionState(name) != null) {
3336                    scheduleWriteSettingsLocked();
3337                } else if (permissionsState.getRuntimePermissionState(name, userId) != null) {
3338                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3339                }
3340            }
3341        }
3342    }
3343
3344    @Override
3345    public boolean isProtectedBroadcast(String actionName) {
3346        synchronized (mPackages) {
3347            return mProtectedBroadcasts.contains(actionName);
3348        }
3349    }
3350
3351    @Override
3352    public int checkSignatures(String pkg1, String pkg2) {
3353        synchronized (mPackages) {
3354            final PackageParser.Package p1 = mPackages.get(pkg1);
3355            final PackageParser.Package p2 = mPackages.get(pkg2);
3356            if (p1 == null || p1.mExtras == null
3357                    || p2 == null || p2.mExtras == null) {
3358                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3359            }
3360            return compareSignatures(p1.mSignatures, p2.mSignatures);
3361        }
3362    }
3363
3364    @Override
3365    public int checkUidSignatures(int uid1, int uid2) {
3366        // Map to base uids.
3367        uid1 = UserHandle.getAppId(uid1);
3368        uid2 = UserHandle.getAppId(uid2);
3369        // reader
3370        synchronized (mPackages) {
3371            Signature[] s1;
3372            Signature[] s2;
3373            Object obj = mSettings.getUserIdLPr(uid1);
3374            if (obj != null) {
3375                if (obj instanceof SharedUserSetting) {
3376                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3377                } else if (obj instanceof PackageSetting) {
3378                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3379                } else {
3380                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3381                }
3382            } else {
3383                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3384            }
3385            obj = mSettings.getUserIdLPr(uid2);
3386            if (obj != null) {
3387                if (obj instanceof SharedUserSetting) {
3388                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3389                } else if (obj instanceof PackageSetting) {
3390                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3391                } else {
3392                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3393                }
3394            } else {
3395                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3396            }
3397            return compareSignatures(s1, s2);
3398        }
3399    }
3400
3401    private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) {
3402        final long identity = Binder.clearCallingIdentity();
3403        try {
3404            if (sb instanceof SharedUserSetting) {
3405                SharedUserSetting sus = (SharedUserSetting) sb;
3406                final int packageCount = sus.packages.size();
3407                for (int i = 0; i < packageCount; i++) {
3408                    PackageSetting susPs = sus.packages.valueAt(i);
3409                    if (userId == UserHandle.USER_ALL) {
3410                        killApplication(susPs.pkg.packageName, susPs.appId, reason);
3411                    } else {
3412                        final int uid = UserHandle.getUid(userId, susPs.appId);
3413                        killUid(uid, reason);
3414                    }
3415                }
3416            } else if (sb instanceof PackageSetting) {
3417                PackageSetting ps = (PackageSetting) sb;
3418                if (userId == UserHandle.USER_ALL) {
3419                    killApplication(ps.pkg.packageName, ps.appId, reason);
3420                } else {
3421                    final int uid = UserHandle.getUid(userId, ps.appId);
3422                    killUid(uid, reason);
3423                }
3424            }
3425        } finally {
3426            Binder.restoreCallingIdentity(identity);
3427        }
3428    }
3429
3430    private static void killUid(int uid, String reason) {
3431        IActivityManager am = ActivityManagerNative.getDefault();
3432        if (am != null) {
3433            try {
3434                am.killUid(uid, reason);
3435            } catch (RemoteException e) {
3436                /* ignore - same process */
3437            }
3438        }
3439    }
3440
3441    /**
3442     * Compares two sets of signatures. Returns:
3443     * <br />
3444     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3445     * <br />
3446     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3447     * <br />
3448     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3449     * <br />
3450     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3451     * <br />
3452     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3453     */
3454    static int compareSignatures(Signature[] s1, Signature[] s2) {
3455        if (s1 == null) {
3456            return s2 == null
3457                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3458                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3459        }
3460
3461        if (s2 == null) {
3462            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3463        }
3464
3465        if (s1.length != s2.length) {
3466            return PackageManager.SIGNATURE_NO_MATCH;
3467        }
3468
3469        // Since both signature sets are of size 1, we can compare without HashSets.
3470        if (s1.length == 1) {
3471            return s1[0].equals(s2[0]) ?
3472                    PackageManager.SIGNATURE_MATCH :
3473                    PackageManager.SIGNATURE_NO_MATCH;
3474        }
3475
3476        ArraySet<Signature> set1 = new ArraySet<Signature>();
3477        for (Signature sig : s1) {
3478            set1.add(sig);
3479        }
3480        ArraySet<Signature> set2 = new ArraySet<Signature>();
3481        for (Signature sig : s2) {
3482            set2.add(sig);
3483        }
3484        // Make sure s2 contains all signatures in s1.
3485        if (set1.equals(set2)) {
3486            return PackageManager.SIGNATURE_MATCH;
3487        }
3488        return PackageManager.SIGNATURE_NO_MATCH;
3489    }
3490
3491    /**
3492     * If the database version for this type of package (internal storage or
3493     * external storage) is less than the version where package signatures
3494     * were updated, return true.
3495     */
3496    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3497        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
3498                DatabaseVersion.SIGNATURE_END_ENTITY))
3499                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
3500                        DatabaseVersion.SIGNATURE_END_ENTITY));
3501    }
3502
3503    /**
3504     * Used for backward compatibility to make sure any packages with
3505     * certificate chains get upgraded to the new style. {@code existingSigs}
3506     * will be in the old format (since they were stored on disk from before the
3507     * system upgrade) and {@code scannedSigs} will be in the newer format.
3508     */
3509    private int compareSignaturesCompat(PackageSignatures existingSigs,
3510            PackageParser.Package scannedPkg) {
3511        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
3512            return PackageManager.SIGNATURE_NO_MATCH;
3513        }
3514
3515        ArraySet<Signature> existingSet = new ArraySet<Signature>();
3516        for (Signature sig : existingSigs.mSignatures) {
3517            existingSet.add(sig);
3518        }
3519        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
3520        for (Signature sig : scannedPkg.mSignatures) {
3521            try {
3522                Signature[] chainSignatures = sig.getChainSignatures();
3523                for (Signature chainSig : chainSignatures) {
3524                    scannedCompatSet.add(chainSig);
3525                }
3526            } catch (CertificateEncodingException e) {
3527                scannedCompatSet.add(sig);
3528            }
3529        }
3530        /*
3531         * Make sure the expanded scanned set contains all signatures in the
3532         * existing one.
3533         */
3534        if (scannedCompatSet.equals(existingSet)) {
3535            // Migrate the old signatures to the new scheme.
3536            existingSigs.assignSignatures(scannedPkg.mSignatures);
3537            // The new KeySets will be re-added later in the scanning process.
3538            synchronized (mPackages) {
3539                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
3540            }
3541            return PackageManager.SIGNATURE_MATCH;
3542        }
3543        return PackageManager.SIGNATURE_NO_MATCH;
3544    }
3545
3546    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3547        if (isExternal(scannedPkg)) {
3548            return mSettings.isExternalDatabaseVersionOlderThan(
3549                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3550        } else {
3551            return mSettings.isInternalDatabaseVersionOlderThan(
3552                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3553        }
3554    }
3555
3556    private int compareSignaturesRecover(PackageSignatures existingSigs,
3557            PackageParser.Package scannedPkg) {
3558        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
3559            return PackageManager.SIGNATURE_NO_MATCH;
3560        }
3561
3562        String msg = null;
3563        try {
3564            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
3565                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
3566                        + scannedPkg.packageName);
3567                return PackageManager.SIGNATURE_MATCH;
3568            }
3569        } catch (CertificateException e) {
3570            msg = e.getMessage();
3571        }
3572
3573        logCriticalInfo(Log.INFO,
3574                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
3575        return PackageManager.SIGNATURE_NO_MATCH;
3576    }
3577
3578    @Override
3579    public String[] getPackagesForUid(int uid) {
3580        uid = UserHandle.getAppId(uid);
3581        // reader
3582        synchronized (mPackages) {
3583            Object obj = mSettings.getUserIdLPr(uid);
3584            if (obj instanceof SharedUserSetting) {
3585                final SharedUserSetting sus = (SharedUserSetting) obj;
3586                final int N = sus.packages.size();
3587                final String[] res = new String[N];
3588                final Iterator<PackageSetting> it = sus.packages.iterator();
3589                int i = 0;
3590                while (it.hasNext()) {
3591                    res[i++] = it.next().name;
3592                }
3593                return res;
3594            } else if (obj instanceof PackageSetting) {
3595                final PackageSetting ps = (PackageSetting) obj;
3596                return new String[] { ps.name };
3597            }
3598        }
3599        return null;
3600    }
3601
3602    @Override
3603    public String getNameForUid(int uid) {
3604        // reader
3605        synchronized (mPackages) {
3606            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3607            if (obj instanceof SharedUserSetting) {
3608                final SharedUserSetting sus = (SharedUserSetting) obj;
3609                return sus.name + ":" + sus.userId;
3610            } else if (obj instanceof PackageSetting) {
3611                final PackageSetting ps = (PackageSetting) obj;
3612                return ps.name;
3613            }
3614        }
3615        return null;
3616    }
3617
3618    @Override
3619    public int getUidForSharedUser(String sharedUserName) {
3620        if(sharedUserName == null) {
3621            return -1;
3622        }
3623        // reader
3624        synchronized (mPackages) {
3625            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
3626            if (suid == null) {
3627                return -1;
3628            }
3629            return suid.userId;
3630        }
3631    }
3632
3633    @Override
3634    public int getFlagsForUid(int uid) {
3635        synchronized (mPackages) {
3636            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3637            if (obj instanceof SharedUserSetting) {
3638                final SharedUserSetting sus = (SharedUserSetting) obj;
3639                return sus.pkgFlags;
3640            } else if (obj instanceof PackageSetting) {
3641                final PackageSetting ps = (PackageSetting) obj;
3642                return ps.pkgFlags;
3643            }
3644        }
3645        return 0;
3646    }
3647
3648    @Override
3649    public int getPrivateFlagsForUid(int uid) {
3650        synchronized (mPackages) {
3651            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3652            if (obj instanceof SharedUserSetting) {
3653                final SharedUserSetting sus = (SharedUserSetting) obj;
3654                return sus.pkgPrivateFlags;
3655            } else if (obj instanceof PackageSetting) {
3656                final PackageSetting ps = (PackageSetting) obj;
3657                return ps.pkgPrivateFlags;
3658            }
3659        }
3660        return 0;
3661    }
3662
3663    @Override
3664    public boolean isUidPrivileged(int uid) {
3665        uid = UserHandle.getAppId(uid);
3666        // reader
3667        synchronized (mPackages) {
3668            Object obj = mSettings.getUserIdLPr(uid);
3669            if (obj instanceof SharedUserSetting) {
3670                final SharedUserSetting sus = (SharedUserSetting) obj;
3671                final Iterator<PackageSetting> it = sus.packages.iterator();
3672                while (it.hasNext()) {
3673                    if (it.next().isPrivileged()) {
3674                        return true;
3675                    }
3676                }
3677            } else if (obj instanceof PackageSetting) {
3678                final PackageSetting ps = (PackageSetting) obj;
3679                return ps.isPrivileged();
3680            }
3681        }
3682        return false;
3683    }
3684
3685    @Override
3686    public String[] getAppOpPermissionPackages(String permissionName) {
3687        synchronized (mPackages) {
3688            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
3689            if (pkgs == null) {
3690                return null;
3691            }
3692            return pkgs.toArray(new String[pkgs.size()]);
3693        }
3694    }
3695
3696    @Override
3697    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
3698            int flags, int userId) {
3699        if (!sUserManager.exists(userId)) return null;
3700        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
3701        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3702        return chooseBestActivity(intent, resolvedType, flags, query, userId);
3703    }
3704
3705    @Override
3706    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
3707            IntentFilter filter, int match, ComponentName activity) {
3708        final int userId = UserHandle.getCallingUserId();
3709        if (DEBUG_PREFERRED) {
3710            Log.v(TAG, "setLastChosenActivity intent=" + intent
3711                + " resolvedType=" + resolvedType
3712                + " flags=" + flags
3713                + " filter=" + filter
3714                + " match=" + match
3715                + " activity=" + activity);
3716            filter.dump(new PrintStreamPrinter(System.out), "    ");
3717        }
3718        intent.setComponent(null);
3719        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3720        // Find any earlier preferred or last chosen entries and nuke them
3721        findPreferredActivity(intent, resolvedType,
3722                flags, query, 0, false, true, false, userId);
3723        // Add the new activity as the last chosen for this filter
3724        addPreferredActivityInternal(filter, match, null, activity, false, userId,
3725                "Setting last chosen");
3726    }
3727
3728    @Override
3729    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
3730        final int userId = UserHandle.getCallingUserId();
3731        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
3732        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3733        return findPreferredActivity(intent, resolvedType, flags, query, 0,
3734                false, false, false, userId);
3735    }
3736
3737    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
3738            int flags, List<ResolveInfo> query, int userId) {
3739        if (query != null) {
3740            final int N = query.size();
3741            if (N == 1) {
3742                return query.get(0);
3743            } else if (N > 1) {
3744                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
3745                // If there is more than one activity with the same priority,
3746                // then let the user decide between them.
3747                ResolveInfo r0 = query.get(0);
3748                ResolveInfo r1 = query.get(1);
3749                if (DEBUG_INTENT_MATCHING || debug) {
3750                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
3751                            + r1.activityInfo.name + "=" + r1.priority);
3752                }
3753                // If the first activity has a higher priority, or a different
3754                // default, then it is always desireable to pick it.
3755                if (r0.priority != r1.priority
3756                        || r0.preferredOrder != r1.preferredOrder
3757                        || r0.isDefault != r1.isDefault) {
3758                    return query.get(0);
3759                }
3760                // If we have saved a preference for a preferred activity for
3761                // this Intent, use that.
3762                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
3763                        flags, query, r0.priority, true, false, debug, userId);
3764                if (ri != null) {
3765                    return ri;
3766                }
3767                if (userId != 0) {
3768                    ri = new ResolveInfo(mResolveInfo);
3769                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
3770                    ri.activityInfo.applicationInfo = new ApplicationInfo(
3771                            ri.activityInfo.applicationInfo);
3772                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
3773                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
3774                    return ri;
3775                }
3776                return mResolveInfo;
3777            }
3778        }
3779        return null;
3780    }
3781
3782    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
3783            int flags, List<ResolveInfo> query, boolean debug, int userId) {
3784        final int N = query.size();
3785        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
3786                .get(userId);
3787        // Get the list of persistent preferred activities that handle the intent
3788        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
3789        List<PersistentPreferredActivity> pprefs = ppir != null
3790                ? ppir.queryIntent(intent, resolvedType,
3791                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3792                : null;
3793        if (pprefs != null && pprefs.size() > 0) {
3794            final int M = pprefs.size();
3795            for (int i=0; i<M; i++) {
3796                final PersistentPreferredActivity ppa = pprefs.get(i);
3797                if (DEBUG_PREFERRED || debug) {
3798                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
3799                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
3800                            + "\n  component=" + ppa.mComponent);
3801                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3802                }
3803                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
3804                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3805                if (DEBUG_PREFERRED || debug) {
3806                    Slog.v(TAG, "Found persistent preferred activity:");
3807                    if (ai != null) {
3808                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3809                    } else {
3810                        Slog.v(TAG, "  null");
3811                    }
3812                }
3813                if (ai == null) {
3814                    // This previously registered persistent preferred activity
3815                    // component is no longer known. Ignore it and do NOT remove it.
3816                    continue;
3817                }
3818                for (int j=0; j<N; j++) {
3819                    final ResolveInfo ri = query.get(j);
3820                    if (!ri.activityInfo.applicationInfo.packageName
3821                            .equals(ai.applicationInfo.packageName)) {
3822                        continue;
3823                    }
3824                    if (!ri.activityInfo.name.equals(ai.name)) {
3825                        continue;
3826                    }
3827                    //  Found a persistent preference that can handle the intent.
3828                    if (DEBUG_PREFERRED || debug) {
3829                        Slog.v(TAG, "Returning persistent preferred activity: " +
3830                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3831                    }
3832                    return ri;
3833                }
3834            }
3835        }
3836        return null;
3837    }
3838
3839    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
3840            List<ResolveInfo> query, int priority, boolean always,
3841            boolean removeMatches, boolean debug, int userId) {
3842        if (!sUserManager.exists(userId)) return null;
3843        // writer
3844        synchronized (mPackages) {
3845            if (intent.getSelector() != null) {
3846                intent = intent.getSelector();
3847            }
3848            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3849
3850            // Try to find a matching persistent preferred activity.
3851            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
3852                    debug, userId);
3853
3854            // If a persistent preferred activity matched, use it.
3855            if (pri != null) {
3856                return pri;
3857            }
3858
3859            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
3860            // Get the list of preferred activities that handle the intent
3861            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
3862            List<PreferredActivity> prefs = pir != null
3863                    ? pir.queryIntent(intent, resolvedType,
3864                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3865                    : null;
3866            if (prefs != null && prefs.size() > 0) {
3867                boolean changed = false;
3868                try {
3869                    // First figure out how good the original match set is.
3870                    // We will only allow preferred activities that came
3871                    // from the same match quality.
3872                    int match = 0;
3873
3874                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
3875
3876                    final int N = query.size();
3877                    for (int j=0; j<N; j++) {
3878                        final ResolveInfo ri = query.get(j);
3879                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
3880                                + ": 0x" + Integer.toHexString(match));
3881                        if (ri.match > match) {
3882                            match = ri.match;
3883                        }
3884                    }
3885
3886                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
3887                            + Integer.toHexString(match));
3888
3889                    match &= IntentFilter.MATCH_CATEGORY_MASK;
3890                    final int M = prefs.size();
3891                    for (int i=0; i<M; i++) {
3892                        final PreferredActivity pa = prefs.get(i);
3893                        if (DEBUG_PREFERRED || debug) {
3894                            Slog.v(TAG, "Checking PreferredActivity ds="
3895                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
3896                                    + "\n  component=" + pa.mPref.mComponent);
3897                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3898                        }
3899                        if (pa.mPref.mMatch != match) {
3900                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
3901                                    + Integer.toHexString(pa.mPref.mMatch));
3902                            continue;
3903                        }
3904                        // If it's not an "always" type preferred activity and that's what we're
3905                        // looking for, skip it.
3906                        if (always && !pa.mPref.mAlways) {
3907                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
3908                            continue;
3909                        }
3910                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
3911                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3912                        if (DEBUG_PREFERRED || debug) {
3913                            Slog.v(TAG, "Found preferred activity:");
3914                            if (ai != null) {
3915                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3916                            } else {
3917                                Slog.v(TAG, "  null");
3918                            }
3919                        }
3920                        if (ai == null) {
3921                            // This previously registered preferred activity
3922                            // component is no longer known.  Most likely an update
3923                            // to the app was installed and in the new version this
3924                            // component no longer exists.  Clean it up by removing
3925                            // it from the preferred activities list, and skip it.
3926                            Slog.w(TAG, "Removing dangling preferred activity: "
3927                                    + pa.mPref.mComponent);
3928                            pir.removeFilter(pa);
3929                            changed = true;
3930                            continue;
3931                        }
3932                        for (int j=0; j<N; j++) {
3933                            final ResolveInfo ri = query.get(j);
3934                            if (!ri.activityInfo.applicationInfo.packageName
3935                                    .equals(ai.applicationInfo.packageName)) {
3936                                continue;
3937                            }
3938                            if (!ri.activityInfo.name.equals(ai.name)) {
3939                                continue;
3940                            }
3941
3942                            if (removeMatches) {
3943                                pir.removeFilter(pa);
3944                                changed = true;
3945                                if (DEBUG_PREFERRED) {
3946                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
3947                                }
3948                                break;
3949                            }
3950
3951                            // Okay we found a previously set preferred or last chosen app.
3952                            // If the result set is different from when this
3953                            // was created, we need to clear it and re-ask the
3954                            // user their preference, if we're looking for an "always" type entry.
3955                            if (always && !pa.mPref.sameSet(query)) {
3956                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
3957                                        + intent + " type " + resolvedType);
3958                                if (DEBUG_PREFERRED) {
3959                                    Slog.v(TAG, "Removing preferred activity since set changed "
3960                                            + pa.mPref.mComponent);
3961                                }
3962                                pir.removeFilter(pa);
3963                                // Re-add the filter as a "last chosen" entry (!always)
3964                                PreferredActivity lastChosen = new PreferredActivity(
3965                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
3966                                pir.addFilter(lastChosen);
3967                                changed = true;
3968                                return null;
3969                            }
3970
3971                            // Yay! Either the set matched or we're looking for the last chosen
3972                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
3973                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3974                            return ri;
3975                        }
3976                    }
3977                } finally {
3978                    if (changed) {
3979                        if (DEBUG_PREFERRED) {
3980                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
3981                        }
3982                        scheduleWritePackageRestrictionsLocked(userId);
3983                    }
3984                }
3985            }
3986        }
3987        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
3988        return null;
3989    }
3990
3991    /*
3992     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
3993     */
3994    @Override
3995    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
3996            int targetUserId) {
3997        mContext.enforceCallingOrSelfPermission(
3998                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
3999        List<CrossProfileIntentFilter> matches =
4000                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4001        if (matches != null) {
4002            int size = matches.size();
4003            for (int i = 0; i < size; i++) {
4004                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4005            }
4006        }
4007        return false;
4008    }
4009
4010    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4011            String resolvedType, int userId) {
4012        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4013        if (resolver != null) {
4014            return resolver.queryIntent(intent, resolvedType, false, userId);
4015        }
4016        return null;
4017    }
4018
4019    @Override
4020    public List<ResolveInfo> queryIntentActivities(Intent intent,
4021            String resolvedType, int flags, int userId) {
4022        if (!sUserManager.exists(userId)) return Collections.emptyList();
4023        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4024        ComponentName comp = intent.getComponent();
4025        if (comp == null) {
4026            if (intent.getSelector() != null) {
4027                intent = intent.getSelector();
4028                comp = intent.getComponent();
4029            }
4030        }
4031
4032        if (comp != null) {
4033            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4034            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4035            if (ai != null) {
4036                final ResolveInfo ri = new ResolveInfo();
4037                ri.activityInfo = ai;
4038                list.add(ri);
4039            }
4040            return list;
4041        }
4042
4043        // reader
4044        synchronized (mPackages) {
4045            final String pkgName = intent.getPackage();
4046            if (pkgName == null) {
4047                List<CrossProfileIntentFilter> matchingFilters =
4048                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4049                // Check for results that need to skip the current profile.
4050                ResolveInfo resolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4051                        resolvedType, flags, userId);
4052                if (resolveInfo != null && isUserEnabled(resolveInfo.targetUserId)) {
4053                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4054                    result.add(resolveInfo);
4055                    return filterIfNotPrimaryUser(result, userId);
4056                }
4057
4058                // Check for results in the current profile.
4059                List<ResolveInfo> result = mActivities.queryIntent(
4060                        intent, resolvedType, flags, userId);
4061
4062                // Check for cross profile results.
4063                resolveInfo = queryCrossProfileIntents(
4064                        matchingFilters, intent, resolvedType, flags, userId);
4065                if (resolveInfo != null && isUserEnabled(resolveInfo.targetUserId)) {
4066                    result.add(resolveInfo);
4067                    Collections.sort(result, mResolvePrioritySorter);
4068                }
4069                result = filterIfNotPrimaryUser(result, userId);
4070                if (result.size() > 1 && hasWebURI(intent)) {
4071                    return filterCandidatesWithDomainPreferedActivitiesLPr(flags, result);
4072                }
4073                return result;
4074            }
4075            final PackageParser.Package pkg = mPackages.get(pkgName);
4076            if (pkg != null) {
4077                return filterIfNotPrimaryUser(
4078                        mActivities.queryIntentForPackage(
4079                                intent, resolvedType, flags, pkg.activities, userId),
4080                        userId);
4081            }
4082            return new ArrayList<ResolveInfo>();
4083        }
4084    }
4085
4086    private boolean isUserEnabled(int userId) {
4087        long callingId = Binder.clearCallingIdentity();
4088        try {
4089            UserInfo userInfo = sUserManager.getUserInfo(userId);
4090            return userInfo != null && userInfo.isEnabled();
4091        } finally {
4092            Binder.restoreCallingIdentity(callingId);
4093        }
4094    }
4095
4096    /**
4097     * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
4098     *
4099     * @return filtered list
4100     */
4101    private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
4102        if (userId == UserHandle.USER_OWNER) {
4103            return resolveInfos;
4104        }
4105        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4106            ResolveInfo info = resolveInfos.get(i);
4107            if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
4108                resolveInfos.remove(i);
4109            }
4110        }
4111        return resolveInfos;
4112    }
4113
4114    private static boolean hasWebURI(Intent intent) {
4115        if (intent.getData() == null) {
4116            return false;
4117        }
4118        final String scheme = intent.getScheme();
4119        if (TextUtils.isEmpty(scheme)) {
4120            return false;
4121        }
4122        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4123    }
4124
4125    private List<ResolveInfo> filterCandidatesWithDomainPreferedActivitiesLPr(
4126            int flags, List<ResolveInfo> candidates) {
4127        if (DEBUG_PREFERRED) {
4128            Slog.v("TAG", "Filtering results with prefered activities. Candidates count: " +
4129                    candidates.size());
4130        }
4131
4132        final int userId = UserHandle.getCallingUserId();
4133        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4134        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4135        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4136        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4137
4138        synchronized (mPackages) {
4139            final int count = candidates.size();
4140            // First, try to use the domain prefered App
4141            for (int n=0; n<count; n++) {
4142                ResolveInfo info = candidates.get(n);
4143                String packageName = info.activityInfo.packageName;
4144                PackageSetting ps = mSettings.mPackages.get(packageName);
4145                if (ps != null) {
4146                    // Add to the special match all list (Browser use case)
4147                    if (info.handleAllWebDataURI) {
4148                        matchAllList.add(info);
4149                        continue;
4150                    }
4151                    // Try to get the status from User settings first
4152                    int status = getDomainVerificationStatusLPr(ps, userId);
4153                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4154                        result.add(info);
4155                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4156                        neverList.add(info);
4157                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4158                        undefinedList.add(info);
4159                    }
4160                }
4161            }
4162            // If there is nothing selected, add all candidates and remove the ones that the User
4163            // has explicitely put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state and
4164            // also remove any undefined ones and Browser Apps ones.
4165            // If there is still none after this pass, add all undefined one and Browser Apps and
4166            // let the User decide with the Disambiguation dialog if there are several ones.
4167            if (result.size() == 0) {
4168                result.addAll(candidates);
4169            }
4170            result.removeAll(neverList);
4171            result.removeAll(matchAllList);
4172            result.removeAll(undefinedList);
4173            if (result.size() == 0) {
4174                result.addAll(undefinedList);
4175                if ((flags & MATCH_ALL) != 0) {
4176                    result.addAll(matchAllList);
4177                } else {
4178                    // Try to add the Default Browser if we can
4179                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(
4180                            UserHandle.myUserId());
4181                    if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
4182                        boolean defaultBrowserFound = false;
4183                        final int browserCount = matchAllList.size();
4184                        for (int n=0; n<browserCount; n++) {
4185                            ResolveInfo browser = matchAllList.get(n);
4186                            if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) {
4187                                result.add(browser);
4188                                defaultBrowserFound = true;
4189                                break;
4190                            }
4191                        }
4192                        if (!defaultBrowserFound) {
4193                            result.addAll(matchAllList);
4194                        }
4195                    } else {
4196                        result.addAll(matchAllList);
4197                    }
4198                }
4199            }
4200        }
4201        if (DEBUG_PREFERRED) {
4202            Slog.v("TAG", "Filtered results with prefered activities. New candidates count: " +
4203                    result.size());
4204        }
4205        return result;
4206    }
4207
4208    private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4209        int status = ps.getDomainVerificationStatusForUser(userId);
4210        // if none available, get the master status
4211        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4212            if (ps.getIntentFilterVerificationInfo() != null) {
4213                status = ps.getIntentFilterVerificationInfo().getStatus();
4214            }
4215        }
4216        return status;
4217    }
4218
4219    private ResolveInfo querySkipCurrentProfileIntents(
4220            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4221            int flags, int sourceUserId) {
4222        if (matchingFilters != null) {
4223            int size = matchingFilters.size();
4224            for (int i = 0; i < size; i ++) {
4225                CrossProfileIntentFilter filter = matchingFilters.get(i);
4226                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4227                    // Checking if there are activities in the target user that can handle the
4228                    // intent.
4229                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4230                            flags, sourceUserId);
4231                    if (resolveInfo != null) {
4232                        return resolveInfo;
4233                    }
4234                }
4235            }
4236        }
4237        return null;
4238    }
4239
4240    // Return matching ResolveInfo if any for skip current profile intent filters.
4241    private ResolveInfo queryCrossProfileIntents(
4242            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4243            int flags, int sourceUserId) {
4244        if (matchingFilters != null) {
4245            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4246            // match the same intent. For performance reasons, it is better not to
4247            // run queryIntent twice for the same userId
4248            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4249            int size = matchingFilters.size();
4250            for (int i = 0; i < size; i++) {
4251                CrossProfileIntentFilter filter = matchingFilters.get(i);
4252                int targetUserId = filter.getTargetUserId();
4253                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4254                        && !alreadyTriedUserIds.get(targetUserId)) {
4255                    // Checking if there are activities in the target user that can handle the
4256                    // intent.
4257                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4258                            flags, sourceUserId);
4259                    if (resolveInfo != null) return resolveInfo;
4260                    alreadyTriedUserIds.put(targetUserId, true);
4261                }
4262            }
4263        }
4264        return null;
4265    }
4266
4267    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
4268            String resolvedType, int flags, int sourceUserId) {
4269        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4270                resolvedType, flags, filter.getTargetUserId());
4271        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
4272            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
4273        }
4274        return null;
4275    }
4276
4277    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
4278            int sourceUserId, int targetUserId) {
4279        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4280        String className;
4281        if (targetUserId == UserHandle.USER_OWNER) {
4282            className = FORWARD_INTENT_TO_USER_OWNER;
4283        } else {
4284            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4285        }
4286        ComponentName forwardingActivityComponentName = new ComponentName(
4287                mAndroidApplication.packageName, className);
4288        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
4289                sourceUserId);
4290        if (targetUserId == UserHandle.USER_OWNER) {
4291            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
4292            forwardingResolveInfo.noResourceId = true;
4293        }
4294        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
4295        forwardingResolveInfo.priority = 0;
4296        forwardingResolveInfo.preferredOrder = 0;
4297        forwardingResolveInfo.match = 0;
4298        forwardingResolveInfo.isDefault = true;
4299        forwardingResolveInfo.filter = filter;
4300        forwardingResolveInfo.targetUserId = targetUserId;
4301        return forwardingResolveInfo;
4302    }
4303
4304    @Override
4305    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
4306            Intent[] specifics, String[] specificTypes, Intent intent,
4307            String resolvedType, int flags, int userId) {
4308        if (!sUserManager.exists(userId)) return Collections.emptyList();
4309        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
4310                false, "query intent activity options");
4311        final String resultsAction = intent.getAction();
4312
4313        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
4314                | PackageManager.GET_RESOLVED_FILTER, userId);
4315
4316        if (DEBUG_INTENT_MATCHING) {
4317            Log.v(TAG, "Query " + intent + ": " + results);
4318        }
4319
4320        int specificsPos = 0;
4321        int N;
4322
4323        // todo: note that the algorithm used here is O(N^2).  This
4324        // isn't a problem in our current environment, but if we start running
4325        // into situations where we have more than 5 or 10 matches then this
4326        // should probably be changed to something smarter...
4327
4328        // First we go through and resolve each of the specific items
4329        // that were supplied, taking care of removing any corresponding
4330        // duplicate items in the generic resolve list.
4331        if (specifics != null) {
4332            for (int i=0; i<specifics.length; i++) {
4333                final Intent sintent = specifics[i];
4334                if (sintent == null) {
4335                    continue;
4336                }
4337
4338                if (DEBUG_INTENT_MATCHING) {
4339                    Log.v(TAG, "Specific #" + i + ": " + sintent);
4340                }
4341
4342                String action = sintent.getAction();
4343                if (resultsAction != null && resultsAction.equals(action)) {
4344                    // If this action was explicitly requested, then don't
4345                    // remove things that have it.
4346                    action = null;
4347                }
4348
4349                ResolveInfo ri = null;
4350                ActivityInfo ai = null;
4351
4352                ComponentName comp = sintent.getComponent();
4353                if (comp == null) {
4354                    ri = resolveIntent(
4355                        sintent,
4356                        specificTypes != null ? specificTypes[i] : null,
4357                            flags, userId);
4358                    if (ri == null) {
4359                        continue;
4360                    }
4361                    if (ri == mResolveInfo) {
4362                        // ACK!  Must do something better with this.
4363                    }
4364                    ai = ri.activityInfo;
4365                    comp = new ComponentName(ai.applicationInfo.packageName,
4366                            ai.name);
4367                } else {
4368                    ai = getActivityInfo(comp, flags, userId);
4369                    if (ai == null) {
4370                        continue;
4371                    }
4372                }
4373
4374                // Look for any generic query activities that are duplicates
4375                // of this specific one, and remove them from the results.
4376                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
4377                N = results.size();
4378                int j;
4379                for (j=specificsPos; j<N; j++) {
4380                    ResolveInfo sri = results.get(j);
4381                    if ((sri.activityInfo.name.equals(comp.getClassName())
4382                            && sri.activityInfo.applicationInfo.packageName.equals(
4383                                    comp.getPackageName()))
4384                        || (action != null && sri.filter.matchAction(action))) {
4385                        results.remove(j);
4386                        if (DEBUG_INTENT_MATCHING) Log.v(
4387                            TAG, "Removing duplicate item from " + j
4388                            + " due to specific " + specificsPos);
4389                        if (ri == null) {
4390                            ri = sri;
4391                        }
4392                        j--;
4393                        N--;
4394                    }
4395                }
4396
4397                // Add this specific item to its proper place.
4398                if (ri == null) {
4399                    ri = new ResolveInfo();
4400                    ri.activityInfo = ai;
4401                }
4402                results.add(specificsPos, ri);
4403                ri.specificIndex = i;
4404                specificsPos++;
4405            }
4406        }
4407
4408        // Now we go through the remaining generic results and remove any
4409        // duplicate actions that are found here.
4410        N = results.size();
4411        for (int i=specificsPos; i<N-1; i++) {
4412            final ResolveInfo rii = results.get(i);
4413            if (rii.filter == null) {
4414                continue;
4415            }
4416
4417            // Iterate over all of the actions of this result's intent
4418            // filter...  typically this should be just one.
4419            final Iterator<String> it = rii.filter.actionsIterator();
4420            if (it == null) {
4421                continue;
4422            }
4423            while (it.hasNext()) {
4424                final String action = it.next();
4425                if (resultsAction != null && resultsAction.equals(action)) {
4426                    // If this action was explicitly requested, then don't
4427                    // remove things that have it.
4428                    continue;
4429                }
4430                for (int j=i+1; j<N; j++) {
4431                    final ResolveInfo rij = results.get(j);
4432                    if (rij.filter != null && rij.filter.hasAction(action)) {
4433                        results.remove(j);
4434                        if (DEBUG_INTENT_MATCHING) Log.v(
4435                            TAG, "Removing duplicate item from " + j
4436                            + " due to action " + action + " at " + i);
4437                        j--;
4438                        N--;
4439                    }
4440                }
4441            }
4442
4443            // If the caller didn't request filter information, drop it now
4444            // so we don't have to marshall/unmarshall it.
4445            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4446                rii.filter = null;
4447            }
4448        }
4449
4450        // Filter out the caller activity if so requested.
4451        if (caller != null) {
4452            N = results.size();
4453            for (int i=0; i<N; i++) {
4454                ActivityInfo ainfo = results.get(i).activityInfo;
4455                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
4456                        && caller.getClassName().equals(ainfo.name)) {
4457                    results.remove(i);
4458                    break;
4459                }
4460            }
4461        }
4462
4463        // If the caller didn't request filter information,
4464        // drop them now so we don't have to
4465        // marshall/unmarshall it.
4466        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4467            N = results.size();
4468            for (int i=0; i<N; i++) {
4469                results.get(i).filter = null;
4470            }
4471        }
4472
4473        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
4474        return results;
4475    }
4476
4477    @Override
4478    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
4479            int userId) {
4480        if (!sUserManager.exists(userId)) return Collections.emptyList();
4481        ComponentName comp = intent.getComponent();
4482        if (comp == null) {
4483            if (intent.getSelector() != null) {
4484                intent = intent.getSelector();
4485                comp = intent.getComponent();
4486            }
4487        }
4488        if (comp != null) {
4489            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4490            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
4491            if (ai != null) {
4492                ResolveInfo ri = new ResolveInfo();
4493                ri.activityInfo = ai;
4494                list.add(ri);
4495            }
4496            return list;
4497        }
4498
4499        // reader
4500        synchronized (mPackages) {
4501            String pkgName = intent.getPackage();
4502            if (pkgName == null) {
4503                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
4504            }
4505            final PackageParser.Package pkg = mPackages.get(pkgName);
4506            if (pkg != null) {
4507                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
4508                        userId);
4509            }
4510            return null;
4511        }
4512    }
4513
4514    @Override
4515    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
4516        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
4517        if (!sUserManager.exists(userId)) return null;
4518        if (query != null) {
4519            if (query.size() >= 1) {
4520                // If there is more than one service with the same priority,
4521                // just arbitrarily pick the first one.
4522                return query.get(0);
4523            }
4524        }
4525        return null;
4526    }
4527
4528    @Override
4529    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
4530            int userId) {
4531        if (!sUserManager.exists(userId)) return Collections.emptyList();
4532        ComponentName comp = intent.getComponent();
4533        if (comp == null) {
4534            if (intent.getSelector() != null) {
4535                intent = intent.getSelector();
4536                comp = intent.getComponent();
4537            }
4538        }
4539        if (comp != null) {
4540            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4541            final ServiceInfo si = getServiceInfo(comp, flags, userId);
4542            if (si != null) {
4543                final ResolveInfo ri = new ResolveInfo();
4544                ri.serviceInfo = si;
4545                list.add(ri);
4546            }
4547            return list;
4548        }
4549
4550        // reader
4551        synchronized (mPackages) {
4552            String pkgName = intent.getPackage();
4553            if (pkgName == null) {
4554                return mServices.queryIntent(intent, resolvedType, flags, userId);
4555            }
4556            final PackageParser.Package pkg = mPackages.get(pkgName);
4557            if (pkg != null) {
4558                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
4559                        userId);
4560            }
4561            return null;
4562        }
4563    }
4564
4565    @Override
4566    public List<ResolveInfo> queryIntentContentProviders(
4567            Intent intent, String resolvedType, int flags, int userId) {
4568        if (!sUserManager.exists(userId)) return Collections.emptyList();
4569        ComponentName comp = intent.getComponent();
4570        if (comp == null) {
4571            if (intent.getSelector() != null) {
4572                intent = intent.getSelector();
4573                comp = intent.getComponent();
4574            }
4575        }
4576        if (comp != null) {
4577            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4578            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
4579            if (pi != null) {
4580                final ResolveInfo ri = new ResolveInfo();
4581                ri.providerInfo = pi;
4582                list.add(ri);
4583            }
4584            return list;
4585        }
4586
4587        // reader
4588        synchronized (mPackages) {
4589            String pkgName = intent.getPackage();
4590            if (pkgName == null) {
4591                return mProviders.queryIntent(intent, resolvedType, flags, userId);
4592            }
4593            final PackageParser.Package pkg = mPackages.get(pkgName);
4594            if (pkg != null) {
4595                return mProviders.queryIntentForPackage(
4596                        intent, resolvedType, flags, pkg.providers, userId);
4597            }
4598            return null;
4599        }
4600    }
4601
4602    @Override
4603    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
4604        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4605
4606        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
4607
4608        // writer
4609        synchronized (mPackages) {
4610            ArrayList<PackageInfo> list;
4611            if (listUninstalled) {
4612                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
4613                for (PackageSetting ps : mSettings.mPackages.values()) {
4614                    PackageInfo pi;
4615                    if (ps.pkg != null) {
4616                        pi = generatePackageInfo(ps.pkg, flags, userId);
4617                    } else {
4618                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
4619                    }
4620                    if (pi != null) {
4621                        list.add(pi);
4622                    }
4623                }
4624            } else {
4625                list = new ArrayList<PackageInfo>(mPackages.size());
4626                for (PackageParser.Package p : mPackages.values()) {
4627                    PackageInfo pi = generatePackageInfo(p, flags, userId);
4628                    if (pi != null) {
4629                        list.add(pi);
4630                    }
4631                }
4632            }
4633
4634            return new ParceledListSlice<PackageInfo>(list);
4635        }
4636    }
4637
4638    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
4639            String[] permissions, boolean[] tmp, int flags, int userId) {
4640        int numMatch = 0;
4641        final PermissionsState permissionsState = ps.getPermissionsState();
4642        for (int i=0; i<permissions.length; i++) {
4643            final String permission = permissions[i];
4644            if (permissionsState.hasPermission(permission, userId)) {
4645                tmp[i] = true;
4646                numMatch++;
4647            } else {
4648                tmp[i] = false;
4649            }
4650        }
4651        if (numMatch == 0) {
4652            return;
4653        }
4654        PackageInfo pi;
4655        if (ps.pkg != null) {
4656            pi = generatePackageInfo(ps.pkg, flags, userId);
4657        } else {
4658            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
4659        }
4660        // The above might return null in cases of uninstalled apps or install-state
4661        // skew across users/profiles.
4662        if (pi != null) {
4663            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
4664                if (numMatch == permissions.length) {
4665                    pi.requestedPermissions = permissions;
4666                } else {
4667                    pi.requestedPermissions = new String[numMatch];
4668                    numMatch = 0;
4669                    for (int i=0; i<permissions.length; i++) {
4670                        if (tmp[i]) {
4671                            pi.requestedPermissions[numMatch] = permissions[i];
4672                            numMatch++;
4673                        }
4674                    }
4675                }
4676            }
4677            list.add(pi);
4678        }
4679    }
4680
4681    @Override
4682    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
4683            String[] permissions, int flags, int userId) {
4684        if (!sUserManager.exists(userId)) return null;
4685        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4686
4687        // writer
4688        synchronized (mPackages) {
4689            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
4690            boolean[] tmpBools = new boolean[permissions.length];
4691            if (listUninstalled) {
4692                for (PackageSetting ps : mSettings.mPackages.values()) {
4693                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
4694                }
4695            } else {
4696                for (PackageParser.Package pkg : mPackages.values()) {
4697                    PackageSetting ps = (PackageSetting)pkg.mExtras;
4698                    if (ps != null) {
4699                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
4700                                userId);
4701                    }
4702                }
4703            }
4704
4705            return new ParceledListSlice<PackageInfo>(list);
4706        }
4707    }
4708
4709    @Override
4710    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
4711        if (!sUserManager.exists(userId)) return null;
4712        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4713
4714        // writer
4715        synchronized (mPackages) {
4716            ArrayList<ApplicationInfo> list;
4717            if (listUninstalled) {
4718                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
4719                for (PackageSetting ps : mSettings.mPackages.values()) {
4720                    ApplicationInfo ai;
4721                    if (ps.pkg != null) {
4722                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4723                                ps.readUserState(userId), userId);
4724                    } else {
4725                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
4726                    }
4727                    if (ai != null) {
4728                        list.add(ai);
4729                    }
4730                }
4731            } else {
4732                list = new ArrayList<ApplicationInfo>(mPackages.size());
4733                for (PackageParser.Package p : mPackages.values()) {
4734                    if (p.mExtras != null) {
4735                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
4736                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
4737                        if (ai != null) {
4738                            list.add(ai);
4739                        }
4740                    }
4741                }
4742            }
4743
4744            return new ParceledListSlice<ApplicationInfo>(list);
4745        }
4746    }
4747
4748    public List<ApplicationInfo> getPersistentApplications(int flags) {
4749        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
4750
4751        // reader
4752        synchronized (mPackages) {
4753            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
4754            final int userId = UserHandle.getCallingUserId();
4755            while (i.hasNext()) {
4756                final PackageParser.Package p = i.next();
4757                if (p.applicationInfo != null
4758                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
4759                        && (!mSafeMode || isSystemApp(p))) {
4760                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
4761                    if (ps != null) {
4762                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
4763                                ps.readUserState(userId), userId);
4764                        if (ai != null) {
4765                            finalList.add(ai);
4766                        }
4767                    }
4768                }
4769            }
4770        }
4771
4772        return finalList;
4773    }
4774
4775    @Override
4776    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
4777        if (!sUserManager.exists(userId)) return null;
4778        // reader
4779        synchronized (mPackages) {
4780            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
4781            PackageSetting ps = provider != null
4782                    ? mSettings.mPackages.get(provider.owner.packageName)
4783                    : null;
4784            return ps != null
4785                    && mSettings.isEnabledLPr(provider.info, flags, userId)
4786                    && (!mSafeMode || (provider.info.applicationInfo.flags
4787                            &ApplicationInfo.FLAG_SYSTEM) != 0)
4788                    ? PackageParser.generateProviderInfo(provider, flags,
4789                            ps.readUserState(userId), userId)
4790                    : null;
4791        }
4792    }
4793
4794    /**
4795     * @deprecated
4796     */
4797    @Deprecated
4798    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
4799        // reader
4800        synchronized (mPackages) {
4801            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
4802                    .entrySet().iterator();
4803            final int userId = UserHandle.getCallingUserId();
4804            while (i.hasNext()) {
4805                Map.Entry<String, PackageParser.Provider> entry = i.next();
4806                PackageParser.Provider p = entry.getValue();
4807                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
4808
4809                if (ps != null && p.syncable
4810                        && (!mSafeMode || (p.info.applicationInfo.flags
4811                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
4812                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
4813                            ps.readUserState(userId), userId);
4814                    if (info != null) {
4815                        outNames.add(entry.getKey());
4816                        outInfo.add(info);
4817                    }
4818                }
4819            }
4820        }
4821    }
4822
4823    @Override
4824    public List<ProviderInfo> queryContentProviders(String processName,
4825            int uid, int flags) {
4826        ArrayList<ProviderInfo> finalList = null;
4827        // reader
4828        synchronized (mPackages) {
4829            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
4830            final int userId = processName != null ?
4831                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
4832            while (i.hasNext()) {
4833                final PackageParser.Provider p = i.next();
4834                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
4835                if (ps != null && p.info.authority != null
4836                        && (processName == null
4837                                || (p.info.processName.equals(processName)
4838                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
4839                        && mSettings.isEnabledLPr(p.info, flags, userId)
4840                        && (!mSafeMode
4841                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
4842                    if (finalList == null) {
4843                        finalList = new ArrayList<ProviderInfo>(3);
4844                    }
4845                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
4846                            ps.readUserState(userId), userId);
4847                    if (info != null) {
4848                        finalList.add(info);
4849                    }
4850                }
4851            }
4852        }
4853
4854        if (finalList != null) {
4855            Collections.sort(finalList, mProviderInitOrderSorter);
4856        }
4857
4858        return finalList;
4859    }
4860
4861    @Override
4862    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
4863            int flags) {
4864        // reader
4865        synchronized (mPackages) {
4866            final PackageParser.Instrumentation i = mInstrumentation.get(name);
4867            return PackageParser.generateInstrumentationInfo(i, flags);
4868        }
4869    }
4870
4871    @Override
4872    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
4873            int flags) {
4874        ArrayList<InstrumentationInfo> finalList =
4875            new ArrayList<InstrumentationInfo>();
4876
4877        // reader
4878        synchronized (mPackages) {
4879            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
4880            while (i.hasNext()) {
4881                final PackageParser.Instrumentation p = i.next();
4882                if (targetPackage == null
4883                        || targetPackage.equals(p.info.targetPackage)) {
4884                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
4885                            flags);
4886                    if (ii != null) {
4887                        finalList.add(ii);
4888                    }
4889                }
4890            }
4891        }
4892
4893        return finalList;
4894    }
4895
4896    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
4897        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
4898        if (overlays == null) {
4899            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
4900            return;
4901        }
4902        for (PackageParser.Package opkg : overlays.values()) {
4903            // Not much to do if idmap fails: we already logged the error
4904            // and we certainly don't want to abort installation of pkg simply
4905            // because an overlay didn't fit properly. For these reasons,
4906            // ignore the return value of createIdmapForPackagePairLI.
4907            createIdmapForPackagePairLI(pkg, opkg);
4908        }
4909    }
4910
4911    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
4912            PackageParser.Package opkg) {
4913        if (!opkg.mTrustedOverlay) {
4914            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
4915                    opkg.baseCodePath + ": overlay not trusted");
4916            return false;
4917        }
4918        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
4919        if (overlaySet == null) {
4920            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
4921                    opkg.baseCodePath + " but target package has no known overlays");
4922            return false;
4923        }
4924        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4925        // TODO: generate idmap for split APKs
4926        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
4927            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
4928                    + opkg.baseCodePath);
4929            return false;
4930        }
4931        PackageParser.Package[] overlayArray =
4932            overlaySet.values().toArray(new PackageParser.Package[0]);
4933        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
4934            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
4935                return p1.mOverlayPriority - p2.mOverlayPriority;
4936            }
4937        };
4938        Arrays.sort(overlayArray, cmp);
4939
4940        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
4941        int i = 0;
4942        for (PackageParser.Package p : overlayArray) {
4943            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
4944        }
4945        return true;
4946    }
4947
4948    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
4949        final File[] files = dir.listFiles();
4950        if (ArrayUtils.isEmpty(files)) {
4951            Log.d(TAG, "No files in app dir " + dir);
4952            return;
4953        }
4954
4955        if (DEBUG_PACKAGE_SCANNING) {
4956            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
4957                    + " flags=0x" + Integer.toHexString(parseFlags));
4958        }
4959
4960        for (File file : files) {
4961            final boolean isPackage = (isApkFile(file) || file.isDirectory())
4962                    && !PackageInstallerService.isStageName(file.getName());
4963            if (!isPackage) {
4964                // Ignore entries which are not packages
4965                continue;
4966            }
4967            try {
4968                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
4969                        scanFlags, currentTime, null);
4970            } catch (PackageManagerException e) {
4971                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
4972
4973                // Delete invalid userdata apps
4974                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
4975                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
4976                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
4977                    if (file.isDirectory()) {
4978                        mInstaller.rmPackageDir(file.getAbsolutePath());
4979                    } else {
4980                        file.delete();
4981                    }
4982                }
4983            }
4984        }
4985    }
4986
4987    private static File getSettingsProblemFile() {
4988        File dataDir = Environment.getDataDirectory();
4989        File systemDir = new File(dataDir, "system");
4990        File fname = new File(systemDir, "uiderrors.txt");
4991        return fname;
4992    }
4993
4994    static void reportSettingsProblem(int priority, String msg) {
4995        logCriticalInfo(priority, msg);
4996    }
4997
4998    static void logCriticalInfo(int priority, String msg) {
4999        Slog.println(priority, TAG, msg);
5000        EventLogTags.writePmCriticalInfo(msg);
5001        try {
5002            File fname = getSettingsProblemFile();
5003            FileOutputStream out = new FileOutputStream(fname, true);
5004            PrintWriter pw = new FastPrintWriter(out);
5005            SimpleDateFormat formatter = new SimpleDateFormat();
5006            String dateString = formatter.format(new Date(System.currentTimeMillis()));
5007            pw.println(dateString + ": " + msg);
5008            pw.close();
5009            FileUtils.setPermissions(
5010                    fname.toString(),
5011                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5012                    -1, -1);
5013        } catch (java.io.IOException e) {
5014        }
5015    }
5016
5017    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5018            PackageParser.Package pkg, File srcFile, int parseFlags)
5019            throws PackageManagerException {
5020        if (ps != null
5021                && ps.codePath.equals(srcFile)
5022                && ps.timeStamp == srcFile.lastModified()
5023                && !isCompatSignatureUpdateNeeded(pkg)
5024                && !isRecoverSignatureUpdateNeeded(pkg)) {
5025            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5026            if (ps.signatures.mSignatures != null
5027                    && ps.signatures.mSignatures.length != 0
5028                    && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) {
5029                // Optimization: reuse the existing cached certificates
5030                // if the package appears to be unchanged.
5031                pkg.mSignatures = ps.signatures.mSignatures;
5032                KeySetManagerService ksms = mSettings.mKeySetManagerService;
5033                synchronized (mPackages) {
5034                    pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
5035                }
5036                return;
5037            }
5038
5039            Slog.w(TAG, "PackageSetting for " + ps.name
5040                    + " is missing signatures.  Collecting certs again to recover them.");
5041        } else {
5042            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
5043        }
5044
5045        try {
5046            pp.collectCertificates(pkg, parseFlags);
5047            pp.collectManifestDigest(pkg);
5048        } catch (PackageParserException e) {
5049            throw PackageManagerException.from(e);
5050        }
5051    }
5052
5053    /*
5054     *  Scan a package and return the newly parsed package.
5055     *  Returns null in case of errors and the error code is stored in mLastScanError
5056     */
5057    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
5058            long currentTime, UserHandle user) throws PackageManagerException {
5059        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
5060        parseFlags |= mDefParseFlags;
5061        PackageParser pp = new PackageParser();
5062        pp.setSeparateProcesses(mSeparateProcesses);
5063        pp.setOnlyCoreApps(mOnlyCore);
5064        pp.setDisplayMetrics(mMetrics);
5065
5066        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
5067            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
5068        }
5069
5070        final PackageParser.Package pkg;
5071        try {
5072            pkg = pp.parsePackage(scanFile, parseFlags);
5073        } catch (PackageParserException e) {
5074            throw PackageManagerException.from(e);
5075        }
5076
5077        PackageSetting ps = null;
5078        PackageSetting updatedPkg;
5079        // reader
5080        synchronized (mPackages) {
5081            // Look to see if we already know about this package.
5082            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
5083            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
5084                // This package has been renamed to its original name.  Let's
5085                // use that.
5086                ps = mSettings.peekPackageLPr(oldName);
5087            }
5088            // If there was no original package, see one for the real package name.
5089            if (ps == null) {
5090                ps = mSettings.peekPackageLPr(pkg.packageName);
5091            }
5092            // Check to see if this package could be hiding/updating a system
5093            // package.  Must look for it either under the original or real
5094            // package name depending on our state.
5095            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
5096            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
5097        }
5098        boolean updatedPkgBetter = false;
5099        // First check if this is a system package that may involve an update
5100        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5101            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
5102            // it needs to drop FLAG_PRIVILEGED.
5103            if (locationIsPrivileged(scanFile)) {
5104                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5105            } else {
5106                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5107            }
5108
5109            if (ps != null && !ps.codePath.equals(scanFile)) {
5110                // The path has changed from what was last scanned...  check the
5111                // version of the new path against what we have stored to determine
5112                // what to do.
5113                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
5114                if (pkg.mVersionCode <= ps.versionCode) {
5115                    // The system package has been updated and the code path does not match
5116                    // Ignore entry. Skip it.
5117                    Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5118                            + " ignored: updated version " + ps.versionCode
5119                            + " better than this " + pkg.mVersionCode);
5120                    if (!updatedPkg.codePath.equals(scanFile)) {
5121                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5122                                + ps.name + " changing from " + updatedPkg.codePathString
5123                                + " to " + scanFile);
5124                        updatedPkg.codePath = scanFile;
5125                        updatedPkg.codePathString = scanFile.toString();
5126                        updatedPkg.resourcePath = scanFile;
5127                        updatedPkg.resourcePathString = scanFile.toString();
5128                    }
5129                    updatedPkg.pkg = pkg;
5130                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null);
5131                } else {
5132                    // The current app on the system partition is better than
5133                    // what we have updated to on the data partition; switch
5134                    // back to the system partition version.
5135                    // At this point, its safely assumed that package installation for
5136                    // apps in system partition will go through. If not there won't be a working
5137                    // version of the app
5138                    // writer
5139                    synchronized (mPackages) {
5140                        // Just remove the loaded entries from package lists.
5141                        mPackages.remove(ps.name);
5142                    }
5143
5144                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5145                            + " reverting from " + ps.codePathString
5146                            + ": new version " + pkg.mVersionCode
5147                            + " better than installed " + ps.versionCode);
5148
5149                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5150                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5151                    synchronized (mInstallLock) {
5152                        args.cleanUpResourcesLI();
5153                    }
5154                    synchronized (mPackages) {
5155                        mSettings.enableSystemPackageLPw(ps.name);
5156                    }
5157                    updatedPkgBetter = true;
5158                }
5159            }
5160        }
5161
5162        if (updatedPkg != null) {
5163            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5164            // initially
5165            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5166
5167            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5168            // flag set initially
5169            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5170                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5171            }
5172        }
5173
5174        // Verify certificates against what was last scanned
5175        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5176
5177        /*
5178         * A new system app appeared, but we already had a non-system one of the
5179         * same name installed earlier.
5180         */
5181        boolean shouldHideSystemApp = false;
5182        if (updatedPkg == null && ps != null
5183                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5184            /*
5185             * Check to make sure the signatures match first. If they don't,
5186             * wipe the installed application and its data.
5187             */
5188            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5189                    != PackageManager.SIGNATURE_MATCH) {
5190                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5191                        + " signatures don't match existing userdata copy; removing");
5192                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5193                ps = null;
5194            } else {
5195                /*
5196                 * If the newly-added system app is an older version than the
5197                 * already installed version, hide it. It will be scanned later
5198                 * and re-added like an update.
5199                 */
5200                if (pkg.mVersionCode <= ps.versionCode) {
5201                    shouldHideSystemApp = true;
5202                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5203                            + " but new version " + pkg.mVersionCode + " better than installed "
5204                            + ps.versionCode + "; hiding system");
5205                } else {
5206                    /*
5207                     * The newly found system app is a newer version that the
5208                     * one previously installed. Simply remove the
5209                     * already-installed application and replace it with our own
5210                     * while keeping the application data.
5211                     */
5212                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5213                            + " reverting from " + ps.codePathString + ": new version "
5214                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5215                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5216                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5217                    synchronized (mInstallLock) {
5218                        args.cleanUpResourcesLI();
5219                    }
5220                }
5221            }
5222        }
5223
5224        // The apk is forward locked (not public) if its code and resources
5225        // are kept in different files. (except for app in either system or
5226        // vendor path).
5227        // TODO grab this value from PackageSettings
5228        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5229            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5230                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5231            }
5232        }
5233
5234        // TODO: extend to support forward-locked splits
5235        String resourcePath = null;
5236        String baseResourcePath = null;
5237        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5238            if (ps != null && ps.resourcePathString != null) {
5239                resourcePath = ps.resourcePathString;
5240                baseResourcePath = ps.resourcePathString;
5241            } else {
5242                // Should not happen at all. Just log an error.
5243                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5244            }
5245        } else {
5246            resourcePath = pkg.codePath;
5247            baseResourcePath = pkg.baseCodePath;
5248        }
5249
5250        // Set application objects path explicitly.
5251        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
5252        pkg.applicationInfo.setCodePath(pkg.codePath);
5253        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5254        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5255        pkg.applicationInfo.setResourcePath(resourcePath);
5256        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5257        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5258
5259        // Note that we invoke the following method only if we are about to unpack an application
5260        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5261                | SCAN_UPDATE_SIGNATURE, currentTime, user);
5262
5263        /*
5264         * If the system app should be overridden by a previously installed
5265         * data, hide the system app now and let the /data/app scan pick it up
5266         * again.
5267         */
5268        if (shouldHideSystemApp) {
5269            synchronized (mPackages) {
5270                /*
5271                 * We have to grant systems permissions before we hide, because
5272                 * grantPermissions will assume the package update is trying to
5273                 * expand its permissions.
5274                 */
5275                grantPermissionsLPw(pkg, true, pkg.packageName);
5276                mSettings.disableSystemPackageLPw(pkg.packageName);
5277            }
5278        }
5279
5280        return scannedPkg;
5281    }
5282
5283    private static String fixProcessName(String defProcessName,
5284            String processName, int uid) {
5285        if (processName == null) {
5286            return defProcessName;
5287        }
5288        return processName;
5289    }
5290
5291    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
5292            throws PackageManagerException {
5293        if (pkgSetting.signatures.mSignatures != null) {
5294            // Already existing package. Make sure signatures match
5295            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
5296                    == PackageManager.SIGNATURE_MATCH;
5297            if (!match) {
5298                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
5299                        == PackageManager.SIGNATURE_MATCH;
5300            }
5301            if (!match) {
5302                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
5303                        == PackageManager.SIGNATURE_MATCH;
5304            }
5305            if (!match) {
5306                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5307                        + pkg.packageName + " signatures do not match the "
5308                        + "previously installed version; ignoring!");
5309            }
5310        }
5311
5312        // Check for shared user signatures
5313        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
5314            // Already existing package. Make sure signatures match
5315            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5316                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
5317            if (!match) {
5318                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
5319                        == PackageManager.SIGNATURE_MATCH;
5320            }
5321            if (!match) {
5322                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
5323                        == PackageManager.SIGNATURE_MATCH;
5324            }
5325            if (!match) {
5326                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
5327                        "Package " + pkg.packageName
5328                        + " has no signatures that match those in shared user "
5329                        + pkgSetting.sharedUser.name + "; ignoring!");
5330            }
5331        }
5332    }
5333
5334    /**
5335     * Enforces that only the system UID or root's UID can call a method exposed
5336     * via Binder.
5337     *
5338     * @param message used as message if SecurityException is thrown
5339     * @throws SecurityException if the caller is not system or root
5340     */
5341    private static final void enforceSystemOrRoot(String message) {
5342        final int uid = Binder.getCallingUid();
5343        if (uid != Process.SYSTEM_UID && uid != 0) {
5344            throw new SecurityException(message);
5345        }
5346    }
5347
5348    @Override
5349    public void performBootDexOpt() {
5350        enforceSystemOrRoot("Only the system can request dexopt be performed");
5351
5352        // Before everything else, see whether we need to fstrim.
5353        try {
5354            IMountService ms = PackageHelper.getMountService();
5355            if (ms != null) {
5356                final boolean isUpgrade = isUpgrade();
5357                boolean doTrim = isUpgrade;
5358                if (doTrim) {
5359                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
5360                } else {
5361                    final long interval = android.provider.Settings.Global.getLong(
5362                            mContext.getContentResolver(),
5363                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
5364                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
5365                    if (interval > 0) {
5366                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
5367                        if (timeSinceLast > interval) {
5368                            doTrim = true;
5369                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
5370                                    + "; running immediately");
5371                        }
5372                    }
5373                }
5374                if (doTrim) {
5375                    if (!isFirstBoot()) {
5376                        try {
5377                            ActivityManagerNative.getDefault().showBootMessage(
5378                                    mContext.getResources().getString(
5379                                            R.string.android_upgrading_fstrim), true);
5380                        } catch (RemoteException e) {
5381                        }
5382                    }
5383                    ms.runMaintenance();
5384                }
5385            } else {
5386                Slog.e(TAG, "Mount service unavailable!");
5387            }
5388        } catch (RemoteException e) {
5389            // Can't happen; MountService is local
5390        }
5391
5392        final ArraySet<PackageParser.Package> pkgs;
5393        synchronized (mPackages) {
5394            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
5395        }
5396
5397        if (pkgs != null) {
5398            // Sort apps by importance for dexopt ordering. Important apps are given more priority
5399            // in case the device runs out of space.
5400            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
5401            // Give priority to core apps.
5402            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5403                PackageParser.Package pkg = it.next();
5404                if (pkg.coreApp) {
5405                    if (DEBUG_DEXOPT) {
5406                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
5407                    }
5408                    sortedPkgs.add(pkg);
5409                    it.remove();
5410                }
5411            }
5412            // Give priority to system apps that listen for pre boot complete.
5413            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
5414            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
5415            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5416                PackageParser.Package pkg = it.next();
5417                if (pkgNames.contains(pkg.packageName)) {
5418                    if (DEBUG_DEXOPT) {
5419                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
5420                    }
5421                    sortedPkgs.add(pkg);
5422                    it.remove();
5423                }
5424            }
5425            // Give priority to system apps.
5426            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5427                PackageParser.Package pkg = it.next();
5428                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
5429                    if (DEBUG_DEXOPT) {
5430                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
5431                    }
5432                    sortedPkgs.add(pkg);
5433                    it.remove();
5434                }
5435            }
5436            // Give priority to updated system apps.
5437            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5438                PackageParser.Package pkg = it.next();
5439                if (pkg.isUpdatedSystemApp()) {
5440                    if (DEBUG_DEXOPT) {
5441                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
5442                    }
5443                    sortedPkgs.add(pkg);
5444                    it.remove();
5445                }
5446            }
5447            // Give priority to apps that listen for boot complete.
5448            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
5449            pkgNames = getPackageNamesForIntent(intent);
5450            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5451                PackageParser.Package pkg = it.next();
5452                if (pkgNames.contains(pkg.packageName)) {
5453                    if (DEBUG_DEXOPT) {
5454                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
5455                    }
5456                    sortedPkgs.add(pkg);
5457                    it.remove();
5458                }
5459            }
5460            // Filter out packages that aren't recently used.
5461            filterRecentlyUsedApps(pkgs);
5462            // Add all remaining apps.
5463            for (PackageParser.Package pkg : pkgs) {
5464                if (DEBUG_DEXOPT) {
5465                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
5466                }
5467                sortedPkgs.add(pkg);
5468            }
5469
5470            // If we want to be lazy, filter everything that wasn't recently used.
5471            if (mLazyDexOpt) {
5472                filterRecentlyUsedApps(sortedPkgs);
5473            }
5474
5475            int i = 0;
5476            int total = sortedPkgs.size();
5477            File dataDir = Environment.getDataDirectory();
5478            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
5479            if (lowThreshold == 0) {
5480                throw new IllegalStateException("Invalid low memory threshold");
5481            }
5482            for (PackageParser.Package pkg : sortedPkgs) {
5483                long usableSpace = dataDir.getUsableSpace();
5484                if (usableSpace < lowThreshold) {
5485                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
5486                    break;
5487                }
5488                performBootDexOpt(pkg, ++i, total);
5489            }
5490        }
5491    }
5492
5493    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
5494        // Filter out packages that aren't recently used.
5495        //
5496        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
5497        // should do a full dexopt.
5498        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
5499            int total = pkgs.size();
5500            int skipped = 0;
5501            long now = System.currentTimeMillis();
5502            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
5503                PackageParser.Package pkg = i.next();
5504                long then = pkg.mLastPackageUsageTimeInMills;
5505                if (then + mDexOptLRUThresholdInMills < now) {
5506                    if (DEBUG_DEXOPT) {
5507                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
5508                              ((then == 0) ? "never" : new Date(then)));
5509                    }
5510                    i.remove();
5511                    skipped++;
5512                }
5513            }
5514            if (DEBUG_DEXOPT) {
5515                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
5516            }
5517        }
5518    }
5519
5520    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
5521        List<ResolveInfo> ris = null;
5522        try {
5523            ris = AppGlobals.getPackageManager().queryIntentReceivers(
5524                    intent, null, 0, UserHandle.USER_OWNER);
5525        } catch (RemoteException e) {
5526        }
5527        ArraySet<String> pkgNames = new ArraySet<String>();
5528        if (ris != null) {
5529            for (ResolveInfo ri : ris) {
5530                pkgNames.add(ri.activityInfo.packageName);
5531            }
5532        }
5533        return pkgNames;
5534    }
5535
5536    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
5537        if (DEBUG_DEXOPT) {
5538            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
5539        }
5540        if (!isFirstBoot()) {
5541            try {
5542                ActivityManagerNative.getDefault().showBootMessage(
5543                        mContext.getResources().getString(R.string.android_upgrading_apk,
5544                                curr, total), true);
5545            } catch (RemoteException e) {
5546            }
5547        }
5548        PackageParser.Package p = pkg;
5549        synchronized (mInstallLock) {
5550            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
5551                    false /* force dex */, false /* defer */, true /* include dependencies */);
5552        }
5553    }
5554
5555    @Override
5556    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
5557        return performDexOpt(packageName, instructionSet, false);
5558    }
5559
5560    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
5561        boolean dexopt = mLazyDexOpt || backgroundDexopt;
5562        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
5563        if (!dexopt && !updateUsage) {
5564            // We aren't going to dexopt or update usage, so bail early.
5565            return false;
5566        }
5567        PackageParser.Package p;
5568        final String targetInstructionSet;
5569        synchronized (mPackages) {
5570            p = mPackages.get(packageName);
5571            if (p == null) {
5572                return false;
5573            }
5574            if (updateUsage) {
5575                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
5576            }
5577            mPackageUsage.write(false);
5578            if (!dexopt) {
5579                // We aren't going to dexopt, so bail early.
5580                return false;
5581            }
5582
5583            targetInstructionSet = instructionSet != null ? instructionSet :
5584                    getPrimaryInstructionSet(p.applicationInfo);
5585            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
5586                return false;
5587            }
5588        }
5589
5590        synchronized (mInstallLock) {
5591            final String[] instructionSets = new String[] { targetInstructionSet };
5592            int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
5593                    false /* forceDex */, false /* defer */, true /* inclDependencies */);
5594            return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
5595        }
5596    }
5597
5598    public ArraySet<String> getPackagesThatNeedDexOpt() {
5599        ArraySet<String> pkgs = null;
5600        synchronized (mPackages) {
5601            for (PackageParser.Package p : mPackages.values()) {
5602                if (DEBUG_DEXOPT) {
5603                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
5604                }
5605                if (!p.mDexOptPerformed.isEmpty()) {
5606                    continue;
5607                }
5608                if (pkgs == null) {
5609                    pkgs = new ArraySet<String>();
5610                }
5611                pkgs.add(p.packageName);
5612            }
5613        }
5614        return pkgs;
5615    }
5616
5617    public void shutdown() {
5618        mPackageUsage.write(true);
5619    }
5620
5621    @Override
5622    public void forceDexOpt(String packageName) {
5623        enforceSystemOrRoot("forceDexOpt");
5624
5625        PackageParser.Package pkg;
5626        synchronized (mPackages) {
5627            pkg = mPackages.get(packageName);
5628            if (pkg == null) {
5629                throw new IllegalArgumentException("Missing package: " + packageName);
5630            }
5631        }
5632
5633        synchronized (mInstallLock) {
5634            final String[] instructionSets = new String[] {
5635                    getPrimaryInstructionSet(pkg.applicationInfo) };
5636            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
5637                    true /*forceDex*/, false /* defer */, true /* inclDependencies */);
5638            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
5639                throw new IllegalStateException("Failed to dexopt: " + res);
5640            }
5641        }
5642    }
5643
5644    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
5645        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
5646            Slog.w(TAG, "Unable to update from " + oldPkg.name
5647                    + " to " + newPkg.packageName
5648                    + ": old package not in system partition");
5649            return false;
5650        } else if (mPackages.get(oldPkg.name) != null) {
5651            Slog.w(TAG, "Unable to update from " + oldPkg.name
5652                    + " to " + newPkg.packageName
5653                    + ": old package still exists");
5654            return false;
5655        }
5656        return true;
5657    }
5658
5659    private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
5660        int[] users = sUserManager.getUserIds();
5661        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
5662        if (res < 0) {
5663            return res;
5664        }
5665        for (int user : users) {
5666            if (user != 0) {
5667                res = mInstaller.createUserData(volumeUuid, packageName,
5668                        UserHandle.getUid(user, uid), user, seinfo);
5669                if (res < 0) {
5670                    return res;
5671                }
5672            }
5673        }
5674        return res;
5675    }
5676
5677    private int removeDataDirsLI(String volumeUuid, String packageName) {
5678        int[] users = sUserManager.getUserIds();
5679        int res = 0;
5680        for (int user : users) {
5681            int resInner = mInstaller.remove(volumeUuid, packageName, user);
5682            if (resInner < 0) {
5683                res = resInner;
5684            }
5685        }
5686
5687        return res;
5688    }
5689
5690    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
5691        int[] users = sUserManager.getUserIds();
5692        int res = 0;
5693        for (int user : users) {
5694            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
5695            if (resInner < 0) {
5696                res = resInner;
5697            }
5698        }
5699        return res;
5700    }
5701
5702    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
5703            PackageParser.Package changingLib) {
5704        if (file.path != null) {
5705            usesLibraryFiles.add(file.path);
5706            return;
5707        }
5708        PackageParser.Package p = mPackages.get(file.apk);
5709        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
5710            // If we are doing this while in the middle of updating a library apk,
5711            // then we need to make sure to use that new apk for determining the
5712            // dependencies here.  (We haven't yet finished committing the new apk
5713            // to the package manager state.)
5714            if (p == null || p.packageName.equals(changingLib.packageName)) {
5715                p = changingLib;
5716            }
5717        }
5718        if (p != null) {
5719            usesLibraryFiles.addAll(p.getAllCodePaths());
5720        }
5721    }
5722
5723    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
5724            PackageParser.Package changingLib) throws PackageManagerException {
5725        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
5726            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
5727            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
5728            for (int i=0; i<N; i++) {
5729                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
5730                if (file == null) {
5731                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
5732                            "Package " + pkg.packageName + " requires unavailable shared library "
5733                            + pkg.usesLibraries.get(i) + "; failing!");
5734                }
5735                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
5736            }
5737            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
5738            for (int i=0; i<N; i++) {
5739                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
5740                if (file == null) {
5741                    Slog.w(TAG, "Package " + pkg.packageName
5742                            + " desires unavailable shared library "
5743                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
5744                } else {
5745                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
5746                }
5747            }
5748            N = usesLibraryFiles.size();
5749            if (N > 0) {
5750                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
5751            } else {
5752                pkg.usesLibraryFiles = null;
5753            }
5754        }
5755    }
5756
5757    private static boolean hasString(List<String> list, List<String> which) {
5758        if (list == null) {
5759            return false;
5760        }
5761        for (int i=list.size()-1; i>=0; i--) {
5762            for (int j=which.size()-1; j>=0; j--) {
5763                if (which.get(j).equals(list.get(i))) {
5764                    return true;
5765                }
5766            }
5767        }
5768        return false;
5769    }
5770
5771    private void updateAllSharedLibrariesLPw() {
5772        for (PackageParser.Package pkg : mPackages.values()) {
5773            try {
5774                updateSharedLibrariesLPw(pkg, null);
5775            } catch (PackageManagerException e) {
5776                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
5777            }
5778        }
5779    }
5780
5781    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
5782            PackageParser.Package changingPkg) {
5783        ArrayList<PackageParser.Package> res = null;
5784        for (PackageParser.Package pkg : mPackages.values()) {
5785            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
5786                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
5787                if (res == null) {
5788                    res = new ArrayList<PackageParser.Package>();
5789                }
5790                res.add(pkg);
5791                try {
5792                    updateSharedLibrariesLPw(pkg, changingPkg);
5793                } catch (PackageManagerException e) {
5794                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
5795                }
5796            }
5797        }
5798        return res;
5799    }
5800
5801    /**
5802     * Derive the value of the {@code cpuAbiOverride} based on the provided
5803     * value and an optional stored value from the package settings.
5804     */
5805    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
5806        String cpuAbiOverride = null;
5807
5808        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
5809            cpuAbiOverride = null;
5810        } else if (abiOverride != null) {
5811            cpuAbiOverride = abiOverride;
5812        } else if (settings != null) {
5813            cpuAbiOverride = settings.cpuAbiOverrideString;
5814        }
5815
5816        return cpuAbiOverride;
5817    }
5818
5819    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
5820            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5821        boolean success = false;
5822        try {
5823            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
5824                    currentTime, user);
5825            success = true;
5826            return res;
5827        } finally {
5828            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5829                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
5830            }
5831        }
5832    }
5833
5834    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
5835            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5836        final File scanFile = new File(pkg.codePath);
5837        if (pkg.applicationInfo.getCodePath() == null ||
5838                pkg.applicationInfo.getResourcePath() == null) {
5839            // Bail out. The resource and code paths haven't been set.
5840            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
5841                    "Code and resource paths haven't been set correctly");
5842        }
5843
5844        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5845            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
5846        } else {
5847            // Only allow system apps to be flagged as core apps.
5848            pkg.coreApp = false;
5849        }
5850
5851        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
5852            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5853        }
5854
5855        if (mCustomResolverComponentName != null &&
5856                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
5857            setUpCustomResolverActivity(pkg);
5858        }
5859
5860        if (pkg.packageName.equals("android")) {
5861            synchronized (mPackages) {
5862                if (mAndroidApplication != null) {
5863                    Slog.w(TAG, "*************************************************");
5864                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
5865                    Slog.w(TAG, " file=" + scanFile);
5866                    Slog.w(TAG, "*************************************************");
5867                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5868                            "Core android package being redefined.  Skipping.");
5869                }
5870
5871                // Set up information for our fall-back user intent resolution activity.
5872                mPlatformPackage = pkg;
5873                pkg.mVersionCode = mSdkVersion;
5874                mAndroidApplication = pkg.applicationInfo;
5875
5876                if (!mResolverReplaced) {
5877                    mResolveActivity.applicationInfo = mAndroidApplication;
5878                    mResolveActivity.name = ResolverActivity.class.getName();
5879                    mResolveActivity.packageName = mAndroidApplication.packageName;
5880                    mResolveActivity.processName = "system:ui";
5881                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
5882                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
5883                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
5884                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
5885                    mResolveActivity.exported = true;
5886                    mResolveActivity.enabled = true;
5887                    mResolveInfo.activityInfo = mResolveActivity;
5888                    mResolveInfo.priority = 0;
5889                    mResolveInfo.preferredOrder = 0;
5890                    mResolveInfo.match = 0;
5891                    mResolveComponentName = new ComponentName(
5892                            mAndroidApplication.packageName, mResolveActivity.name);
5893                }
5894            }
5895        }
5896
5897        if (DEBUG_PACKAGE_SCANNING) {
5898            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5899                Log.d(TAG, "Scanning package " + pkg.packageName);
5900        }
5901
5902        if (mPackages.containsKey(pkg.packageName)
5903                || mSharedLibraries.containsKey(pkg.packageName)) {
5904            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5905                    "Application package " + pkg.packageName
5906                    + " already installed.  Skipping duplicate.");
5907        }
5908
5909        // If we're only installing presumed-existing packages, require that the
5910        // scanned APK is both already known and at the path previously established
5911        // for it.  Previously unknown packages we pick up normally, but if we have an
5912        // a priori expectation about this package's install presence, enforce it.
5913        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
5914            PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
5915            if (known != null) {
5916                if (DEBUG_PACKAGE_SCANNING) {
5917                    Log.d(TAG, "Examining " + pkg.codePath
5918                            + " and requiring known paths " + known.codePathString
5919                            + " & " + known.resourcePathString);
5920                }
5921                if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
5922                        || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
5923                    throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
5924                            "Application package " + pkg.packageName
5925                            + " found at " + pkg.applicationInfo.getCodePath()
5926                            + " but expected at " + known.codePathString + "; ignoring.");
5927                }
5928            }
5929        }
5930
5931        // Initialize package source and resource directories
5932        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
5933        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
5934
5935        SharedUserSetting suid = null;
5936        PackageSetting pkgSetting = null;
5937
5938        if (!isSystemApp(pkg)) {
5939            // Only system apps can use these features.
5940            pkg.mOriginalPackages = null;
5941            pkg.mRealPackage = null;
5942            pkg.mAdoptPermissions = null;
5943        }
5944
5945        // writer
5946        synchronized (mPackages) {
5947            if (pkg.mSharedUserId != null) {
5948                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
5949                if (suid == null) {
5950                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5951                            "Creating application package " + pkg.packageName
5952                            + " for shared user failed");
5953                }
5954                if (DEBUG_PACKAGE_SCANNING) {
5955                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5956                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
5957                                + "): packages=" + suid.packages);
5958                }
5959            }
5960
5961            // Check if we are renaming from an original package name.
5962            PackageSetting origPackage = null;
5963            String realName = null;
5964            if (pkg.mOriginalPackages != null) {
5965                // This package may need to be renamed to a previously
5966                // installed name.  Let's check on that...
5967                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
5968                if (pkg.mOriginalPackages.contains(renamed)) {
5969                    // This package had originally been installed as the
5970                    // original name, and we have already taken care of
5971                    // transitioning to the new one.  Just update the new
5972                    // one to continue using the old name.
5973                    realName = pkg.mRealPackage;
5974                    if (!pkg.packageName.equals(renamed)) {
5975                        // Callers into this function may have already taken
5976                        // care of renaming the package; only do it here if
5977                        // it is not already done.
5978                        pkg.setPackageName(renamed);
5979                    }
5980
5981                } else {
5982                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
5983                        if ((origPackage = mSettings.peekPackageLPr(
5984                                pkg.mOriginalPackages.get(i))) != null) {
5985                            // We do have the package already installed under its
5986                            // original name...  should we use it?
5987                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
5988                                // New package is not compatible with original.
5989                                origPackage = null;
5990                                continue;
5991                            } else if (origPackage.sharedUser != null) {
5992                                // Make sure uid is compatible between packages.
5993                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
5994                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
5995                                            + " to " + pkg.packageName + ": old uid "
5996                                            + origPackage.sharedUser.name
5997                                            + " differs from " + pkg.mSharedUserId);
5998                                    origPackage = null;
5999                                    continue;
6000                                }
6001                            } else {
6002                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6003                                        + pkg.packageName + " to old name " + origPackage.name);
6004                            }
6005                            break;
6006                        }
6007                    }
6008                }
6009            }
6010
6011            if (mTransferedPackages.contains(pkg.packageName)) {
6012                Slog.w(TAG, "Package " + pkg.packageName
6013                        + " was transferred to another, but its .apk remains");
6014            }
6015
6016            // Just create the setting, don't add it yet. For already existing packages
6017            // the PkgSetting exists already and doesn't have to be created.
6018            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6019                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6020                    pkg.applicationInfo.primaryCpuAbi,
6021                    pkg.applicationInfo.secondaryCpuAbi,
6022                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6023                    user, false);
6024            if (pkgSetting == null) {
6025                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6026                        "Creating application package " + pkg.packageName + " failed");
6027            }
6028
6029            if (pkgSetting.origPackage != null) {
6030                // If we are first transitioning from an original package,
6031                // fix up the new package's name now.  We need to do this after
6032                // looking up the package under its new name, so getPackageLP
6033                // can take care of fiddling things correctly.
6034                pkg.setPackageName(origPackage.name);
6035
6036                // File a report about this.
6037                String msg = "New package " + pkgSetting.realName
6038                        + " renamed to replace old package " + pkgSetting.name;
6039                reportSettingsProblem(Log.WARN, msg);
6040
6041                // Make a note of it.
6042                mTransferedPackages.add(origPackage.name);
6043
6044                // No longer need to retain this.
6045                pkgSetting.origPackage = null;
6046            }
6047
6048            if (realName != null) {
6049                // Make a note of it.
6050                mTransferedPackages.add(pkg.packageName);
6051            }
6052
6053            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6054                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6055            }
6056
6057            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6058                // Check all shared libraries and map to their actual file path.
6059                // We only do this here for apps not on a system dir, because those
6060                // are the only ones that can fail an install due to this.  We
6061                // will take care of the system apps by updating all of their
6062                // library paths after the scan is done.
6063                updateSharedLibrariesLPw(pkg, null);
6064            }
6065
6066            if (mFoundPolicyFile) {
6067                SELinuxMMAC.assignSeinfoValue(pkg);
6068            }
6069
6070            pkg.applicationInfo.uid = pkgSetting.appId;
6071            pkg.mExtras = pkgSetting;
6072            if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) {
6073                try {
6074                    verifySignaturesLP(pkgSetting, pkg);
6075                    // We just determined the app is signed correctly, so bring
6076                    // over the latest parsed certs.
6077                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6078                } catch (PackageManagerException e) {
6079                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6080                        throw e;
6081                    }
6082                    // The signature has changed, but this package is in the system
6083                    // image...  let's recover!
6084                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6085                    // However...  if this package is part of a shared user, but it
6086                    // doesn't match the signature of the shared user, let's fail.
6087                    // What this means is that you can't change the signatures
6088                    // associated with an overall shared user, which doesn't seem all
6089                    // that unreasonable.
6090                    if (pkgSetting.sharedUser != null) {
6091                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6092                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
6093                            throw new PackageManagerException(
6094                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
6095                                            "Signature mismatch for shared user : "
6096                                            + pkgSetting.sharedUser);
6097                        }
6098                    }
6099                    // File a report about this.
6100                    String msg = "System package " + pkg.packageName
6101                        + " signature changed; retaining data.";
6102                    reportSettingsProblem(Log.WARN, msg);
6103                }
6104            } else {
6105                if (!checkUpgradeKeySetLP(pkgSetting, pkg)) {
6106                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
6107                            + pkg.packageName + " upgrade keys do not match the "
6108                            + "previously installed version");
6109                } else {
6110                    // We just determined the app is signed correctly, so bring
6111                    // over the latest parsed certs.
6112                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6113                }
6114            }
6115            // Verify that this new package doesn't have any content providers
6116            // that conflict with existing packages.  Only do this if the
6117            // package isn't already installed, since we don't want to break
6118            // things that are installed.
6119            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6120                final int N = pkg.providers.size();
6121                int i;
6122                for (i=0; i<N; i++) {
6123                    PackageParser.Provider p = pkg.providers.get(i);
6124                    if (p.info.authority != null) {
6125                        String names[] = p.info.authority.split(";");
6126                        for (int j = 0; j < names.length; j++) {
6127                            if (mProvidersByAuthority.containsKey(names[j])) {
6128                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6129                                final String otherPackageName =
6130                                        ((other != null && other.getComponentName() != null) ?
6131                                                other.getComponentName().getPackageName() : "?");
6132                                throw new PackageManagerException(
6133                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
6134                                                "Can't install because provider name " + names[j]
6135                                                + " (in package " + pkg.applicationInfo.packageName
6136                                                + ") is already used by " + otherPackageName);
6137                            }
6138                        }
6139                    }
6140                }
6141            }
6142
6143            if (pkg.mAdoptPermissions != null) {
6144                // This package wants to adopt ownership of permissions from
6145                // another package.
6146                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6147                    final String origName = pkg.mAdoptPermissions.get(i);
6148                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
6149                    if (orig != null) {
6150                        if (verifyPackageUpdateLPr(orig, pkg)) {
6151                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
6152                                    + pkg.packageName);
6153                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
6154                        }
6155                    }
6156                }
6157            }
6158        }
6159
6160        final String pkgName = pkg.packageName;
6161
6162        final long scanFileTime = scanFile.lastModified();
6163        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6164        pkg.applicationInfo.processName = fixProcessName(
6165                pkg.applicationInfo.packageName,
6166                pkg.applicationInfo.processName,
6167                pkg.applicationInfo.uid);
6168
6169        File dataPath;
6170        if (mPlatformPackage == pkg) {
6171            // The system package is special.
6172            dataPath = new File(Environment.getDataDirectory(), "system");
6173
6174            pkg.applicationInfo.dataDir = dataPath.getPath();
6175
6176        } else {
6177            // This is a normal package, need to make its data directory.
6178            dataPath = PackageManager.getDataDirForUser(pkg.volumeUuid, pkg.packageName,
6179                    UserHandle.USER_OWNER);
6180
6181            boolean uidError = false;
6182            if (dataPath.exists()) {
6183                int currentUid = 0;
6184                try {
6185                    StructStat stat = Os.stat(dataPath.getPath());
6186                    currentUid = stat.st_uid;
6187                } catch (ErrnoException e) {
6188                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6189                }
6190
6191                // If we have mismatched owners for the data path, we have a problem.
6192                if (currentUid != pkg.applicationInfo.uid) {
6193                    boolean recovered = false;
6194                    if (currentUid == 0) {
6195                        // The directory somehow became owned by root.  Wow.
6196                        // This is probably because the system was stopped while
6197                        // installd was in the middle of messing with its libs
6198                        // directory.  Ask installd to fix that.
6199                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
6200                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
6201                        if (ret >= 0) {
6202                            recovered = true;
6203                            String msg = "Package " + pkg.packageName
6204                                    + " unexpectedly changed to uid 0; recovered to " +
6205                                    + pkg.applicationInfo.uid;
6206                            reportSettingsProblem(Log.WARN, msg);
6207                        }
6208                    }
6209                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6210                            || (scanFlags&SCAN_BOOTING) != 0)) {
6211                        // If this is a system app, we can at least delete its
6212                        // current data so the application will still work.
6213                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
6214                        if (ret >= 0) {
6215                            // TODO: Kill the processes first
6216                            // Old data gone!
6217                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6218                                    ? "System package " : "Third party package ";
6219                            String msg = prefix + pkg.packageName
6220                                    + " has changed from uid: "
6221                                    + currentUid + " to "
6222                                    + pkg.applicationInfo.uid + "; old data erased";
6223                            reportSettingsProblem(Log.WARN, msg);
6224                            recovered = true;
6225
6226                            // And now re-install the app.
6227                            ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6228                                    pkg.applicationInfo.seinfo);
6229                            if (ret == -1) {
6230                                // Ack should not happen!
6231                                msg = prefix + pkg.packageName
6232                                        + " could not have data directory re-created after delete.";
6233                                reportSettingsProblem(Log.WARN, msg);
6234                                throw new PackageManagerException(
6235                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6236                            }
6237                        }
6238                        if (!recovered) {
6239                            mHasSystemUidErrors = true;
6240                        }
6241                    } else if (!recovered) {
6242                        // If we allow this install to proceed, we will be broken.
6243                        // Abort, abort!
6244                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
6245                                "scanPackageLI");
6246                    }
6247                    if (!recovered) {
6248                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
6249                            + pkg.applicationInfo.uid + "/fs_"
6250                            + currentUid;
6251                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
6252                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
6253                        String msg = "Package " + pkg.packageName
6254                                + " has mismatched uid: "
6255                                + currentUid + " on disk, "
6256                                + pkg.applicationInfo.uid + " in settings";
6257                        // writer
6258                        synchronized (mPackages) {
6259                            mSettings.mReadMessages.append(msg);
6260                            mSettings.mReadMessages.append('\n');
6261                            uidError = true;
6262                            if (!pkgSetting.uidError) {
6263                                reportSettingsProblem(Log.ERROR, msg);
6264                            }
6265                        }
6266                    }
6267                }
6268                pkg.applicationInfo.dataDir = dataPath.getPath();
6269                if (mShouldRestoreconData) {
6270                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
6271                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
6272                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
6273                }
6274            } else {
6275                if (DEBUG_PACKAGE_SCANNING) {
6276                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6277                        Log.v(TAG, "Want this data dir: " + dataPath);
6278                }
6279                //invoke installer to do the actual installation
6280                int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6281                        pkg.applicationInfo.seinfo);
6282                if (ret < 0) {
6283                    // Error from installer
6284                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6285                            "Unable to create data dirs [errorCode=" + ret + "]");
6286                }
6287
6288                if (dataPath.exists()) {
6289                    pkg.applicationInfo.dataDir = dataPath.getPath();
6290                } else {
6291                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
6292                    pkg.applicationInfo.dataDir = null;
6293                }
6294            }
6295
6296            pkgSetting.uidError = uidError;
6297        }
6298
6299        final String path = scanFile.getPath();
6300        final String codePath = pkg.applicationInfo.getCodePath();
6301        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
6302        if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
6303            setBundledAppAbisAndRoots(pkg, pkgSetting);
6304
6305            // If we haven't found any native libraries for the app, check if it has
6306            // renderscript code. We'll need to force the app to 32 bit if it has
6307            // renderscript bitcode.
6308            if (pkg.applicationInfo.primaryCpuAbi == null
6309                    && pkg.applicationInfo.secondaryCpuAbi == null
6310                    && Build.SUPPORTED_64_BIT_ABIS.length >  0) {
6311                NativeLibraryHelper.Handle handle = null;
6312                try {
6313                    handle = NativeLibraryHelper.Handle.create(scanFile);
6314                    if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
6315                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6316                    }
6317                } catch (IOException ioe) {
6318                    Slog.w(TAG, "Error scanning system app : " + ioe);
6319                } finally {
6320                    IoUtils.closeQuietly(handle);
6321                }
6322            }
6323
6324            setNativeLibraryPaths(pkg);
6325        } else {
6326            // TODO: We can probably be smarter about this stuff. For installed apps,
6327            // we can calculate this information at install time once and for all. For
6328            // system apps, we can probably assume that this information doesn't change
6329            // after the first boot scan. As things stand, we do lots of unnecessary work.
6330
6331            // Give ourselves some initial paths; we'll come back for another
6332            // pass once we've determined ABI below.
6333            setNativeLibraryPaths(pkg);
6334
6335            final boolean isAsec = pkg.isForwardLocked() || isExternal(pkg);
6336            final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
6337            final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
6338
6339            NativeLibraryHelper.Handle handle = null;
6340            try {
6341                handle = NativeLibraryHelper.Handle.create(scanFile);
6342                // TODO(multiArch): This can be null for apps that didn't go through the
6343                // usual installation process. We can calculate it again, like we
6344                // do during install time.
6345                //
6346                // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
6347                // unnecessary.
6348                final File nativeLibraryRoot = new File(nativeLibraryRootStr);
6349
6350                // Null out the abis so that they can be recalculated.
6351                pkg.applicationInfo.primaryCpuAbi = null;
6352                pkg.applicationInfo.secondaryCpuAbi = null;
6353                if (isMultiArch(pkg.applicationInfo)) {
6354                    // Warn if we've set an abiOverride for multi-lib packages..
6355                    // By definition, we need to copy both 32 and 64 bit libraries for
6356                    // such packages.
6357                    if (pkg.cpuAbiOverride != null
6358                            && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
6359                        Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
6360                    }
6361
6362                    int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
6363                    int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
6364                    if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
6365                        if (isAsec) {
6366                            abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
6367                        } else {
6368                            abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
6369                                    nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
6370                                    useIsaSpecificSubdirs);
6371                        }
6372                    }
6373
6374                    maybeThrowExceptionForMultiArchCopy(
6375                            "Error unpackaging 32 bit native libs for multiarch app.", abi32);
6376
6377                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
6378                        if (isAsec) {
6379                            abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
6380                        } else {
6381                            abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
6382                                    nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
6383                                    useIsaSpecificSubdirs);
6384                        }
6385                    }
6386
6387                    maybeThrowExceptionForMultiArchCopy(
6388                            "Error unpackaging 64 bit native libs for multiarch app.", abi64);
6389
6390                    if (abi64 >= 0) {
6391                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
6392                    }
6393
6394                    if (abi32 >= 0) {
6395                        final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
6396                        if (abi64 >= 0) {
6397                            pkg.applicationInfo.secondaryCpuAbi = abi;
6398                        } else {
6399                            pkg.applicationInfo.primaryCpuAbi = abi;
6400                        }
6401                    }
6402                } else {
6403                    String[] abiList = (cpuAbiOverride != null) ?
6404                            new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
6405
6406                    // Enable gross and lame hacks for apps that are built with old
6407                    // SDK tools. We must scan their APKs for renderscript bitcode and
6408                    // not launch them if it's present. Don't bother checking on devices
6409                    // that don't have 64 bit support.
6410                    boolean needsRenderScriptOverride = false;
6411                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
6412                            NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
6413                        abiList = Build.SUPPORTED_32_BIT_ABIS;
6414                        needsRenderScriptOverride = true;
6415                    }
6416
6417                    final int copyRet;
6418                    if (isAsec) {
6419                        copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
6420                    } else {
6421                        copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
6422                                nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
6423                    }
6424
6425                    if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
6426                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
6427                                "Error unpackaging native libs for app, errorCode=" + copyRet);
6428                    }
6429
6430                    if (copyRet >= 0) {
6431                        pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
6432                    } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
6433                        pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
6434                    } else if (needsRenderScriptOverride) {
6435                        pkg.applicationInfo.primaryCpuAbi = abiList[0];
6436                    }
6437                }
6438            } catch (IOException ioe) {
6439                Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
6440            } finally {
6441                IoUtils.closeQuietly(handle);
6442            }
6443
6444            // Now that we've calculated the ABIs and determined if it's an internal app,
6445            // we will go ahead and populate the nativeLibraryPath.
6446            setNativeLibraryPaths(pkg);
6447
6448            if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
6449            final int[] userIds = sUserManager.getUserIds();
6450            synchronized (mInstallLock) {
6451                // Create a native library symlink only if we have native libraries
6452                // and if the native libraries are 32 bit libraries. We do not provide
6453                // this symlink for 64 bit libraries.
6454                if (pkg.applicationInfo.primaryCpuAbi != null &&
6455                        !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
6456                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
6457                    for (int userId : userIds) {
6458                        if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
6459                                nativeLibPath, userId) < 0) {
6460                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
6461                                    "Failed linking native library dir (user=" + userId + ")");
6462                        }
6463                    }
6464                }
6465            }
6466        }
6467
6468        // This is a special case for the "system" package, where the ABI is
6469        // dictated by the zygote configuration (and init.rc). We should keep track
6470        // of this ABI so that we can deal with "normal" applications that run under
6471        // the same UID correctly.
6472        if (mPlatformPackage == pkg) {
6473            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
6474                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
6475        }
6476
6477        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6478        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6479        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
6480        // Copy the derived override back to the parsed package, so that we can
6481        // update the package settings accordingly.
6482        pkg.cpuAbiOverride = cpuAbiOverride;
6483
6484        if (DEBUG_ABI_SELECTION) {
6485            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
6486                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
6487                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
6488        }
6489
6490        // Push the derived path down into PackageSettings so we know what to
6491        // clean up at uninstall time.
6492        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
6493
6494        if (DEBUG_ABI_SELECTION) {
6495            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
6496                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
6497                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
6498        }
6499
6500        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
6501            // We don't do this here during boot because we can do it all
6502            // at once after scanning all existing packages.
6503            //
6504            // We also do this *before* we perform dexopt on this package, so that
6505            // we can avoid redundant dexopts, and also to make sure we've got the
6506            // code and package path correct.
6507            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
6508                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
6509        }
6510
6511        if ((scanFlags & SCAN_NO_DEX) == 0) {
6512            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
6513                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */);
6514            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6515                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
6516            }
6517        }
6518        if (mFactoryTest && pkg.requestedPermissions.contains(
6519                android.Manifest.permission.FACTORY_TEST)) {
6520            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
6521        }
6522
6523        ArrayList<PackageParser.Package> clientLibPkgs = null;
6524
6525        // writer
6526        synchronized (mPackages) {
6527            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6528                // Only system apps can add new shared libraries.
6529                if (pkg.libraryNames != null) {
6530                    for (int i=0; i<pkg.libraryNames.size(); i++) {
6531                        String name = pkg.libraryNames.get(i);
6532                        boolean allowed = false;
6533                        if (pkg.isUpdatedSystemApp()) {
6534                            // New library entries can only be added through the
6535                            // system image.  This is important to get rid of a lot
6536                            // of nasty edge cases: for example if we allowed a non-
6537                            // system update of the app to add a library, then uninstalling
6538                            // the update would make the library go away, and assumptions
6539                            // we made such as through app install filtering would now
6540                            // have allowed apps on the device which aren't compatible
6541                            // with it.  Better to just have the restriction here, be
6542                            // conservative, and create many fewer cases that can negatively
6543                            // impact the user experience.
6544                            final PackageSetting sysPs = mSettings
6545                                    .getDisabledSystemPkgLPr(pkg.packageName);
6546                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
6547                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
6548                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
6549                                        allowed = true;
6550                                        allowed = true;
6551                                        break;
6552                                    }
6553                                }
6554                            }
6555                        } else {
6556                            allowed = true;
6557                        }
6558                        if (allowed) {
6559                            if (!mSharedLibraries.containsKey(name)) {
6560                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
6561                            } else if (!name.equals(pkg.packageName)) {
6562                                Slog.w(TAG, "Package " + pkg.packageName + " library "
6563                                        + name + " already exists; skipping");
6564                            }
6565                        } else {
6566                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
6567                                    + name + " that is not declared on system image; skipping");
6568                        }
6569                    }
6570                    if ((scanFlags&SCAN_BOOTING) == 0) {
6571                        // If we are not booting, we need to update any applications
6572                        // that are clients of our shared library.  If we are booting,
6573                        // this will all be done once the scan is complete.
6574                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
6575                    }
6576                }
6577            }
6578        }
6579
6580        // We also need to dexopt any apps that are dependent on this library.  Note that
6581        // if these fail, we should abort the install since installing the library will
6582        // result in some apps being broken.
6583        if (clientLibPkgs != null) {
6584            if ((scanFlags & SCAN_NO_DEX) == 0) {
6585                for (int i = 0; i < clientLibPkgs.size(); i++) {
6586                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
6587                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
6588                            null /* instruction sets */, forceDex,
6589                            (scanFlags & SCAN_DEFER_DEX) != 0, false);
6590                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6591                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
6592                                "scanPackageLI failed to dexopt clientLibPkgs");
6593                    }
6594                }
6595            }
6596        }
6597
6598        // Also need to kill any apps that are dependent on the library.
6599        if (clientLibPkgs != null) {
6600            for (int i=0; i<clientLibPkgs.size(); i++) {
6601                PackageParser.Package clientPkg = clientLibPkgs.get(i);
6602                killApplication(clientPkg.applicationInfo.packageName,
6603                        clientPkg.applicationInfo.uid, "update lib");
6604            }
6605        }
6606
6607        // writer
6608        synchronized (mPackages) {
6609            // We don't expect installation to fail beyond this point
6610
6611            // Add the new setting to mSettings
6612            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
6613            // Add the new setting to mPackages
6614            mPackages.put(pkg.applicationInfo.packageName, pkg);
6615            // Make sure we don't accidentally delete its data.
6616            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
6617            while (iter.hasNext()) {
6618                PackageCleanItem item = iter.next();
6619                if (pkgName.equals(item.packageName)) {
6620                    iter.remove();
6621                }
6622            }
6623
6624            // Take care of first install / last update times.
6625            if (currentTime != 0) {
6626                if (pkgSetting.firstInstallTime == 0) {
6627                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
6628                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
6629                    pkgSetting.lastUpdateTime = currentTime;
6630                }
6631            } else if (pkgSetting.firstInstallTime == 0) {
6632                // We need *something*.  Take time time stamp of the file.
6633                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
6634            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
6635                if (scanFileTime != pkgSetting.timeStamp) {
6636                    // A package on the system image has changed; consider this
6637                    // to be an update.
6638                    pkgSetting.lastUpdateTime = scanFileTime;
6639                }
6640            }
6641
6642            // Add the package's KeySets to the global KeySetManagerService
6643            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6644            try {
6645                ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys);
6646                if (pkg.mKeySetMapping != null) {
6647                    ksms.addDefinedKeySetsToPackageLPw(pkg.packageName, pkg.mKeySetMapping);
6648                    if (pkg.mUpgradeKeySets != null) {
6649                        ksms.addUpgradeKeySetsToPackageLPw(pkg.packageName, pkg.mUpgradeKeySets);
6650                    }
6651                }
6652            } catch (NullPointerException e) {
6653                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
6654            } catch (IllegalArgumentException e) {
6655                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
6656            }
6657
6658            int N = pkg.providers.size();
6659            StringBuilder r = null;
6660            int i;
6661            for (i=0; i<N; i++) {
6662                PackageParser.Provider p = pkg.providers.get(i);
6663                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
6664                        p.info.processName, pkg.applicationInfo.uid);
6665                mProviders.addProvider(p);
6666                p.syncable = p.info.isSyncable;
6667                if (p.info.authority != null) {
6668                    String names[] = p.info.authority.split(";");
6669                    p.info.authority = null;
6670                    for (int j = 0; j < names.length; j++) {
6671                        if (j == 1 && p.syncable) {
6672                            // We only want the first authority for a provider to possibly be
6673                            // syncable, so if we already added this provider using a different
6674                            // authority clear the syncable flag. We copy the provider before
6675                            // changing it because the mProviders object contains a reference
6676                            // to a provider that we don't want to change.
6677                            // Only do this for the second authority since the resulting provider
6678                            // object can be the same for all future authorities for this provider.
6679                            p = new PackageParser.Provider(p);
6680                            p.syncable = false;
6681                        }
6682                        if (!mProvidersByAuthority.containsKey(names[j])) {
6683                            mProvidersByAuthority.put(names[j], p);
6684                            if (p.info.authority == null) {
6685                                p.info.authority = names[j];
6686                            } else {
6687                                p.info.authority = p.info.authority + ";" + names[j];
6688                            }
6689                            if (DEBUG_PACKAGE_SCANNING) {
6690                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6691                                    Log.d(TAG, "Registered content provider: " + names[j]
6692                                            + ", className = " + p.info.name + ", isSyncable = "
6693                                            + p.info.isSyncable);
6694                            }
6695                        } else {
6696                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6697                            Slog.w(TAG, "Skipping provider name " + names[j] +
6698                                    " (in package " + pkg.applicationInfo.packageName +
6699                                    "): name already used by "
6700                                    + ((other != null && other.getComponentName() != null)
6701                                            ? other.getComponentName().getPackageName() : "?"));
6702                        }
6703                    }
6704                }
6705                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6706                    if (r == null) {
6707                        r = new StringBuilder(256);
6708                    } else {
6709                        r.append(' ');
6710                    }
6711                    r.append(p.info.name);
6712                }
6713            }
6714            if (r != null) {
6715                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
6716            }
6717
6718            N = pkg.services.size();
6719            r = null;
6720            for (i=0; i<N; i++) {
6721                PackageParser.Service s = pkg.services.get(i);
6722                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
6723                        s.info.processName, pkg.applicationInfo.uid);
6724                mServices.addService(s);
6725                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6726                    if (r == null) {
6727                        r = new StringBuilder(256);
6728                    } else {
6729                        r.append(' ');
6730                    }
6731                    r.append(s.info.name);
6732                }
6733            }
6734            if (r != null) {
6735                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
6736            }
6737
6738            N = pkg.receivers.size();
6739            r = null;
6740            for (i=0; i<N; i++) {
6741                PackageParser.Activity a = pkg.receivers.get(i);
6742                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6743                        a.info.processName, pkg.applicationInfo.uid);
6744                mReceivers.addActivity(a, "receiver");
6745                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6746                    if (r == null) {
6747                        r = new StringBuilder(256);
6748                    } else {
6749                        r.append(' ');
6750                    }
6751                    r.append(a.info.name);
6752                }
6753            }
6754            if (r != null) {
6755                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
6756            }
6757
6758            N = pkg.activities.size();
6759            r = null;
6760            for (i=0; i<N; i++) {
6761                PackageParser.Activity a = pkg.activities.get(i);
6762                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6763                        a.info.processName, pkg.applicationInfo.uid);
6764                mActivities.addActivity(a, "activity");
6765                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6766                    if (r == null) {
6767                        r = new StringBuilder(256);
6768                    } else {
6769                        r.append(' ');
6770                    }
6771                    r.append(a.info.name);
6772                }
6773            }
6774            if (r != null) {
6775                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
6776            }
6777
6778            N = pkg.permissionGroups.size();
6779            r = null;
6780            for (i=0; i<N; i++) {
6781                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
6782                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
6783                if (cur == null) {
6784                    mPermissionGroups.put(pg.info.name, pg);
6785                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6786                        if (r == null) {
6787                            r = new StringBuilder(256);
6788                        } else {
6789                            r.append(' ');
6790                        }
6791                        r.append(pg.info.name);
6792                    }
6793                } else {
6794                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
6795                            + pg.info.packageName + " ignored: original from "
6796                            + cur.info.packageName);
6797                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6798                        if (r == null) {
6799                            r = new StringBuilder(256);
6800                        } else {
6801                            r.append(' ');
6802                        }
6803                        r.append("DUP:");
6804                        r.append(pg.info.name);
6805                    }
6806                }
6807            }
6808            if (r != null) {
6809                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
6810            }
6811
6812            N = pkg.permissions.size();
6813            r = null;
6814            for (i=0; i<N; i++) {
6815                PackageParser.Permission p = pkg.permissions.get(i);
6816
6817                // Now that permission groups have a special meaning, we ignore permission
6818                // groups for legacy apps to prevent unexpected behavior. In particular,
6819                // permissions for one app being granted to someone just becuase they happen
6820                // to be in a group defined by another app (before this had no implications).
6821                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
6822                    p.group = mPermissionGroups.get(p.info.group);
6823                    // Warn for a permission in an unknown group.
6824                    if (p.info.group != null && p.group == null) {
6825                        Slog.w(TAG, "Permission " + p.info.name + " from package "
6826                                + p.info.packageName + " in an unknown group " + p.info.group);
6827                    }
6828                }
6829
6830                ArrayMap<String, BasePermission> permissionMap =
6831                        p.tree ? mSettings.mPermissionTrees
6832                                : mSettings.mPermissions;
6833                BasePermission bp = permissionMap.get(p.info.name);
6834
6835                // Allow system apps to redefine non-system permissions
6836                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
6837                    final boolean currentOwnerIsSystem = (bp.perm != null
6838                            && isSystemApp(bp.perm.owner));
6839                    if (isSystemApp(p.owner)) {
6840                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
6841                            // It's a built-in permission and no owner, take ownership now
6842                            bp.packageSetting = pkgSetting;
6843                            bp.perm = p;
6844                            bp.uid = pkg.applicationInfo.uid;
6845                            bp.sourcePackage = p.info.packageName;
6846                        } else if (!currentOwnerIsSystem) {
6847                            String msg = "New decl " + p.owner + " of permission  "
6848                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
6849                            reportSettingsProblem(Log.WARN, msg);
6850                            bp = null;
6851                        }
6852                    }
6853                }
6854
6855                if (bp == null) {
6856                    bp = new BasePermission(p.info.name, p.info.packageName,
6857                            BasePermission.TYPE_NORMAL);
6858                    permissionMap.put(p.info.name, bp);
6859                }
6860
6861                if (bp.perm == null) {
6862                    if (bp.sourcePackage == null
6863                            || bp.sourcePackage.equals(p.info.packageName)) {
6864                        BasePermission tree = findPermissionTreeLP(p.info.name);
6865                        if (tree == null
6866                                || tree.sourcePackage.equals(p.info.packageName)) {
6867                            bp.packageSetting = pkgSetting;
6868                            bp.perm = p;
6869                            bp.uid = pkg.applicationInfo.uid;
6870                            bp.sourcePackage = p.info.packageName;
6871                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6872                                if (r == null) {
6873                                    r = new StringBuilder(256);
6874                                } else {
6875                                    r.append(' ');
6876                                }
6877                                r.append(p.info.name);
6878                            }
6879                        } else {
6880                            Slog.w(TAG, "Permission " + p.info.name + " from package "
6881                                    + p.info.packageName + " ignored: base tree "
6882                                    + tree.name + " is from package "
6883                                    + tree.sourcePackage);
6884                        }
6885                    } else {
6886                        Slog.w(TAG, "Permission " + p.info.name + " from package "
6887                                + p.info.packageName + " ignored: original from "
6888                                + bp.sourcePackage);
6889                    }
6890                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6891                    if (r == null) {
6892                        r = new StringBuilder(256);
6893                    } else {
6894                        r.append(' ');
6895                    }
6896                    r.append("DUP:");
6897                    r.append(p.info.name);
6898                }
6899                if (bp.perm == p) {
6900                    bp.protectionLevel = p.info.protectionLevel;
6901                }
6902            }
6903
6904            if (r != null) {
6905                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
6906            }
6907
6908            N = pkg.instrumentation.size();
6909            r = null;
6910            for (i=0; i<N; i++) {
6911                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6912                a.info.packageName = pkg.applicationInfo.packageName;
6913                a.info.sourceDir = pkg.applicationInfo.sourceDir;
6914                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
6915                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
6916                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
6917                a.info.dataDir = pkg.applicationInfo.dataDir;
6918
6919                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
6920                // need other information about the application, like the ABI and what not ?
6921                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
6922                mInstrumentation.put(a.getComponentName(), a);
6923                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6924                    if (r == null) {
6925                        r = new StringBuilder(256);
6926                    } else {
6927                        r.append(' ');
6928                    }
6929                    r.append(a.info.name);
6930                }
6931            }
6932            if (r != null) {
6933                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
6934            }
6935
6936            if (pkg.protectedBroadcasts != null) {
6937                N = pkg.protectedBroadcasts.size();
6938                for (i=0; i<N; i++) {
6939                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
6940                }
6941            }
6942
6943            pkgSetting.setTimeStamp(scanFileTime);
6944
6945            // Create idmap files for pairs of (packages, overlay packages).
6946            // Note: "android", ie framework-res.apk, is handled by native layers.
6947            if (pkg.mOverlayTarget != null) {
6948                // This is an overlay package.
6949                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
6950                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
6951                        mOverlays.put(pkg.mOverlayTarget,
6952                                new ArrayMap<String, PackageParser.Package>());
6953                    }
6954                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
6955                    map.put(pkg.packageName, pkg);
6956                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
6957                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
6958                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6959                                "scanPackageLI failed to createIdmap");
6960                    }
6961                }
6962            } else if (mOverlays.containsKey(pkg.packageName) &&
6963                    !pkg.packageName.equals("android")) {
6964                // This is a regular package, with one or more known overlay packages.
6965                createIdmapsForPackageLI(pkg);
6966            }
6967        }
6968
6969        return pkg;
6970    }
6971
6972    /**
6973     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
6974     * i.e, so that all packages can be run inside a single process if required.
6975     *
6976     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
6977     * this function will either try and make the ABI for all packages in {@code packagesForUser}
6978     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
6979     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
6980     * updating a package that belongs to a shared user.
6981     *
6982     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
6983     * adds unnecessary complexity.
6984     */
6985    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
6986            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
6987        String requiredInstructionSet = null;
6988        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
6989            requiredInstructionSet = VMRuntime.getInstructionSet(
6990                     scannedPackage.applicationInfo.primaryCpuAbi);
6991        }
6992
6993        PackageSetting requirer = null;
6994        for (PackageSetting ps : packagesForUser) {
6995            // If packagesForUser contains scannedPackage, we skip it. This will happen
6996            // when scannedPackage is an update of an existing package. Without this check,
6997            // we will never be able to change the ABI of any package belonging to a shared
6998            // user, even if it's compatible with other packages.
6999            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7000                if (ps.primaryCpuAbiString == null) {
7001                    continue;
7002                }
7003
7004                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7005                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7006                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7007                    // this but there's not much we can do.
7008                    String errorMessage = "Instruction set mismatch, "
7009                            + ((requirer == null) ? "[caller]" : requirer)
7010                            + " requires " + requiredInstructionSet + " whereas " + ps
7011                            + " requires " + instructionSet;
7012                    Slog.w(TAG, errorMessage);
7013                }
7014
7015                if (requiredInstructionSet == null) {
7016                    requiredInstructionSet = instructionSet;
7017                    requirer = ps;
7018                }
7019            }
7020        }
7021
7022        if (requiredInstructionSet != null) {
7023            String adjustedAbi;
7024            if (requirer != null) {
7025                // requirer != null implies that either scannedPackage was null or that scannedPackage
7026                // did not require an ABI, in which case we have to adjust scannedPackage to match
7027                // the ABI of the set (which is the same as requirer's ABI)
7028                adjustedAbi = requirer.primaryCpuAbiString;
7029                if (scannedPackage != null) {
7030                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7031                }
7032            } else {
7033                // requirer == null implies that we're updating all ABIs in the set to
7034                // match scannedPackage.
7035                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7036            }
7037
7038            for (PackageSetting ps : packagesForUser) {
7039                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7040                    if (ps.primaryCpuAbiString != null) {
7041                        continue;
7042                    }
7043
7044                    ps.primaryCpuAbiString = adjustedAbi;
7045                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7046                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7047                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7048
7049                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
7050                                null /* instruction sets */, forceDexOpt, deferDexOpt, true);
7051                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7052                            ps.primaryCpuAbiString = null;
7053                            ps.pkg.applicationInfo.primaryCpuAbi = null;
7054                            return;
7055                        } else {
7056                            mInstaller.rmdex(ps.codePathString,
7057                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
7058                        }
7059                    }
7060                }
7061            }
7062        }
7063    }
7064
7065    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7066        synchronized (mPackages) {
7067            mResolverReplaced = true;
7068            // Set up information for custom user intent resolution activity.
7069            mResolveActivity.applicationInfo = pkg.applicationInfo;
7070            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7071            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7072            mResolveActivity.processName = pkg.applicationInfo.packageName;
7073            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7074            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7075                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7076            mResolveActivity.theme = 0;
7077            mResolveActivity.exported = true;
7078            mResolveActivity.enabled = true;
7079            mResolveInfo.activityInfo = mResolveActivity;
7080            mResolveInfo.priority = 0;
7081            mResolveInfo.preferredOrder = 0;
7082            mResolveInfo.match = 0;
7083            mResolveComponentName = mCustomResolverComponentName;
7084            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7085                    mResolveComponentName);
7086        }
7087    }
7088
7089    private static String calculateBundledApkRoot(final String codePathString) {
7090        final File codePath = new File(codePathString);
7091        final File codeRoot;
7092        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7093            codeRoot = Environment.getRootDirectory();
7094        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7095            codeRoot = Environment.getOemDirectory();
7096        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7097            codeRoot = Environment.getVendorDirectory();
7098        } else {
7099            // Unrecognized code path; take its top real segment as the apk root:
7100            // e.g. /something/app/blah.apk => /something
7101            try {
7102                File f = codePath.getCanonicalFile();
7103                File parent = f.getParentFile();    // non-null because codePath is a file
7104                File tmp;
7105                while ((tmp = parent.getParentFile()) != null) {
7106                    f = parent;
7107                    parent = tmp;
7108                }
7109                codeRoot = f;
7110                Slog.w(TAG, "Unrecognized code path "
7111                        + codePath + " - using " + codeRoot);
7112            } catch (IOException e) {
7113                // Can't canonicalize the code path -- shenanigans?
7114                Slog.w(TAG, "Can't canonicalize code path " + codePath);
7115                return Environment.getRootDirectory().getPath();
7116            }
7117        }
7118        return codeRoot.getPath();
7119    }
7120
7121    /**
7122     * Derive and set the location of native libraries for the given package,
7123     * which varies depending on where and how the package was installed.
7124     */
7125    private void setNativeLibraryPaths(PackageParser.Package pkg) {
7126        final ApplicationInfo info = pkg.applicationInfo;
7127        final String codePath = pkg.codePath;
7128        final File codeFile = new File(codePath);
7129        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7130        final boolean asecApp = info.isForwardLocked() || isExternal(info);
7131
7132        info.nativeLibraryRootDir = null;
7133        info.nativeLibraryRootRequiresIsa = false;
7134        info.nativeLibraryDir = null;
7135        info.secondaryNativeLibraryDir = null;
7136
7137        if (isApkFile(codeFile)) {
7138            // Monolithic install
7139            if (bundledApp) {
7140                // If "/system/lib64/apkname" exists, assume that is the per-package
7141                // native library directory to use; otherwise use "/system/lib/apkname".
7142                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
7143                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
7144                        getPrimaryInstructionSet(info));
7145
7146                // This is a bundled system app so choose the path based on the ABI.
7147                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
7148                // is just the default path.
7149                final String apkName = deriveCodePathName(codePath);
7150                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
7151                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
7152                        apkName).getAbsolutePath();
7153
7154                if (info.secondaryCpuAbi != null) {
7155                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7156                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7157                            secondaryLibDir, apkName).getAbsolutePath();
7158                }
7159            } else if (asecApp) {
7160                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
7161                        .getAbsolutePath();
7162            } else {
7163                final String apkName = deriveCodePathName(codePath);
7164                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
7165                        .getAbsolutePath();
7166            }
7167
7168            info.nativeLibraryRootRequiresIsa = false;
7169            info.nativeLibraryDir = info.nativeLibraryRootDir;
7170        } else {
7171            // Cluster install
7172            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7173            info.nativeLibraryRootRequiresIsa = true;
7174
7175            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7176                    getPrimaryInstructionSet(info)).getAbsolutePath();
7177
7178            if (info.secondaryCpuAbi != null) {
7179                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7180                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7181            }
7182        }
7183    }
7184
7185    /**
7186     * Calculate the abis and roots for a bundled app. These can uniquely
7187     * be determined from the contents of the system partition, i.e whether
7188     * it contains 64 or 32 bit shared libraries etc. We do not validate any
7189     * of this information, and instead assume that the system was built
7190     * sensibly.
7191     */
7192    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
7193                                           PackageSetting pkgSetting) {
7194        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
7195
7196        // If "/system/lib64/apkname" exists, assume that is the per-package
7197        // native library directory to use; otherwise use "/system/lib/apkname".
7198        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
7199        setBundledAppAbi(pkg, apkRoot, apkName);
7200        // pkgSetting might be null during rescan following uninstall of updates
7201        // to a bundled app, so accommodate that possibility.  The settings in
7202        // that case will be established later from the parsed package.
7203        //
7204        // If the settings aren't null, sync them up with what we've just derived.
7205        // note that apkRoot isn't stored in the package settings.
7206        if (pkgSetting != null) {
7207            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7208            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7209        }
7210    }
7211
7212    /**
7213     * Deduces the ABI of a bundled app and sets the relevant fields on the
7214     * parsed pkg object.
7215     *
7216     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
7217     *        under which system libraries are installed.
7218     * @param apkName the name of the installed package.
7219     */
7220    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7221        final File codeFile = new File(pkg.codePath);
7222
7223        final boolean has64BitLibs;
7224        final boolean has32BitLibs;
7225        if (isApkFile(codeFile)) {
7226            // Monolithic install
7227            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7228            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7229        } else {
7230            // Cluster install
7231            final File rootDir = new File(codeFile, LIB_DIR_NAME);
7232            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7233                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7234                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7235                has64BitLibs = (new File(rootDir, isa)).exists();
7236            } else {
7237                has64BitLibs = false;
7238            }
7239            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7240                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7241                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7242                has32BitLibs = (new File(rootDir, isa)).exists();
7243            } else {
7244                has32BitLibs = false;
7245            }
7246        }
7247
7248        if (has64BitLibs && !has32BitLibs) {
7249            // The package has 64 bit libs, but not 32 bit libs. Its primary
7250            // ABI should be 64 bit. We can safely assume here that the bundled
7251            // native libraries correspond to the most preferred ABI in the list.
7252
7253            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7254            pkg.applicationInfo.secondaryCpuAbi = null;
7255        } else if (has32BitLibs && !has64BitLibs) {
7256            // The package has 32 bit libs but not 64 bit libs. Its primary
7257            // ABI should be 32 bit.
7258
7259            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7260            pkg.applicationInfo.secondaryCpuAbi = null;
7261        } else if (has32BitLibs && has64BitLibs) {
7262            // The application has both 64 and 32 bit bundled libraries. We check
7263            // here that the app declares multiArch support, and warn if it doesn't.
7264            //
7265            // We will be lenient here and record both ABIs. The primary will be the
7266            // ABI that's higher on the list, i.e, a device that's configured to prefer
7267            // 64 bit apps will see a 64 bit primary ABI,
7268
7269            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
7270                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
7271            }
7272
7273            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
7274                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7275                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7276            } else {
7277                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7278                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7279            }
7280        } else {
7281            pkg.applicationInfo.primaryCpuAbi = null;
7282            pkg.applicationInfo.secondaryCpuAbi = null;
7283        }
7284    }
7285
7286    private void killApplication(String pkgName, int appId, String reason) {
7287        // Request the ActivityManager to kill the process(only for existing packages)
7288        // so that we do not end up in a confused state while the user is still using the older
7289        // version of the application while the new one gets installed.
7290        IActivityManager am = ActivityManagerNative.getDefault();
7291        if (am != null) {
7292            try {
7293                am.killApplicationWithAppId(pkgName, appId, reason);
7294            } catch (RemoteException e) {
7295            }
7296        }
7297    }
7298
7299    void removePackageLI(PackageSetting ps, boolean chatty) {
7300        if (DEBUG_INSTALL) {
7301            if (chatty)
7302                Log.d(TAG, "Removing package " + ps.name);
7303        }
7304
7305        // writer
7306        synchronized (mPackages) {
7307            mPackages.remove(ps.name);
7308            final PackageParser.Package pkg = ps.pkg;
7309            if (pkg != null) {
7310                cleanPackageDataStructuresLILPw(pkg, chatty);
7311            }
7312        }
7313    }
7314
7315    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
7316        if (DEBUG_INSTALL) {
7317            if (chatty)
7318                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
7319        }
7320
7321        // writer
7322        synchronized (mPackages) {
7323            mPackages.remove(pkg.applicationInfo.packageName);
7324            cleanPackageDataStructuresLILPw(pkg, chatty);
7325        }
7326    }
7327
7328    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
7329        int N = pkg.providers.size();
7330        StringBuilder r = null;
7331        int i;
7332        for (i=0; i<N; i++) {
7333            PackageParser.Provider p = pkg.providers.get(i);
7334            mProviders.removeProvider(p);
7335            if (p.info.authority == null) {
7336
7337                /* There was another ContentProvider with this authority when
7338                 * this app was installed so this authority is null,
7339                 * Ignore it as we don't have to unregister the provider.
7340                 */
7341                continue;
7342            }
7343            String names[] = p.info.authority.split(";");
7344            for (int j = 0; j < names.length; j++) {
7345                if (mProvidersByAuthority.get(names[j]) == p) {
7346                    mProvidersByAuthority.remove(names[j]);
7347                    if (DEBUG_REMOVE) {
7348                        if (chatty)
7349                            Log.d(TAG, "Unregistered content provider: " + names[j]
7350                                    + ", className = " + p.info.name + ", isSyncable = "
7351                                    + p.info.isSyncable);
7352                    }
7353                }
7354            }
7355            if (DEBUG_REMOVE && chatty) {
7356                if (r == null) {
7357                    r = new StringBuilder(256);
7358                } else {
7359                    r.append(' ');
7360                }
7361                r.append(p.info.name);
7362            }
7363        }
7364        if (r != null) {
7365            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
7366        }
7367
7368        N = pkg.services.size();
7369        r = null;
7370        for (i=0; i<N; i++) {
7371            PackageParser.Service s = pkg.services.get(i);
7372            mServices.removeService(s);
7373            if (chatty) {
7374                if (r == null) {
7375                    r = new StringBuilder(256);
7376                } else {
7377                    r.append(' ');
7378                }
7379                r.append(s.info.name);
7380            }
7381        }
7382        if (r != null) {
7383            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
7384        }
7385
7386        N = pkg.receivers.size();
7387        r = null;
7388        for (i=0; i<N; i++) {
7389            PackageParser.Activity a = pkg.receivers.get(i);
7390            mReceivers.removeActivity(a, "receiver");
7391            if (DEBUG_REMOVE && chatty) {
7392                if (r == null) {
7393                    r = new StringBuilder(256);
7394                } else {
7395                    r.append(' ');
7396                }
7397                r.append(a.info.name);
7398            }
7399        }
7400        if (r != null) {
7401            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
7402        }
7403
7404        N = pkg.activities.size();
7405        r = null;
7406        for (i=0; i<N; i++) {
7407            PackageParser.Activity a = pkg.activities.get(i);
7408            mActivities.removeActivity(a, "activity");
7409            if (DEBUG_REMOVE && chatty) {
7410                if (r == null) {
7411                    r = new StringBuilder(256);
7412                } else {
7413                    r.append(' ');
7414                }
7415                r.append(a.info.name);
7416            }
7417        }
7418        if (r != null) {
7419            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
7420        }
7421
7422        N = pkg.permissions.size();
7423        r = null;
7424        for (i=0; i<N; i++) {
7425            PackageParser.Permission p = pkg.permissions.get(i);
7426            BasePermission bp = mSettings.mPermissions.get(p.info.name);
7427            if (bp == null) {
7428                bp = mSettings.mPermissionTrees.get(p.info.name);
7429            }
7430            if (bp != null && bp.perm == p) {
7431                bp.perm = null;
7432                if (DEBUG_REMOVE && chatty) {
7433                    if (r == null) {
7434                        r = new StringBuilder(256);
7435                    } else {
7436                        r.append(' ');
7437                    }
7438                    r.append(p.info.name);
7439                }
7440            }
7441            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7442                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
7443                if (appOpPerms != null) {
7444                    appOpPerms.remove(pkg.packageName);
7445                }
7446            }
7447        }
7448        if (r != null) {
7449            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
7450        }
7451
7452        N = pkg.requestedPermissions.size();
7453        r = null;
7454        for (i=0; i<N; i++) {
7455            String perm = pkg.requestedPermissions.get(i);
7456            BasePermission bp = mSettings.mPermissions.get(perm);
7457            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7458                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
7459                if (appOpPerms != null) {
7460                    appOpPerms.remove(pkg.packageName);
7461                    if (appOpPerms.isEmpty()) {
7462                        mAppOpPermissionPackages.remove(perm);
7463                    }
7464                }
7465            }
7466        }
7467        if (r != null) {
7468            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
7469        }
7470
7471        N = pkg.instrumentation.size();
7472        r = null;
7473        for (i=0; i<N; i++) {
7474            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7475            mInstrumentation.remove(a.getComponentName());
7476            if (DEBUG_REMOVE && chatty) {
7477                if (r == null) {
7478                    r = new StringBuilder(256);
7479                } else {
7480                    r.append(' ');
7481                }
7482                r.append(a.info.name);
7483            }
7484        }
7485        if (r != null) {
7486            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
7487        }
7488
7489        r = null;
7490        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7491            // Only system apps can hold shared libraries.
7492            if (pkg.libraryNames != null) {
7493                for (i=0; i<pkg.libraryNames.size(); i++) {
7494                    String name = pkg.libraryNames.get(i);
7495                    SharedLibraryEntry cur = mSharedLibraries.get(name);
7496                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
7497                        mSharedLibraries.remove(name);
7498                        if (DEBUG_REMOVE && chatty) {
7499                            if (r == null) {
7500                                r = new StringBuilder(256);
7501                            } else {
7502                                r.append(' ');
7503                            }
7504                            r.append(name);
7505                        }
7506                    }
7507                }
7508            }
7509        }
7510        if (r != null) {
7511            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
7512        }
7513    }
7514
7515    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
7516        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
7517            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
7518                return true;
7519            }
7520        }
7521        return false;
7522    }
7523
7524    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
7525    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
7526    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
7527
7528    private void updatePermissionsLPw(String changingPkg,
7529            PackageParser.Package pkgInfo, int flags) {
7530        // Make sure there are no dangling permission trees.
7531        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
7532        while (it.hasNext()) {
7533            final BasePermission bp = it.next();
7534            if (bp.packageSetting == null) {
7535                // We may not yet have parsed the package, so just see if
7536                // we still know about its settings.
7537                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
7538            }
7539            if (bp.packageSetting == null) {
7540                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
7541                        + " from package " + bp.sourcePackage);
7542                it.remove();
7543            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
7544                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
7545                    Slog.i(TAG, "Removing old permission tree: " + bp.name
7546                            + " from package " + bp.sourcePackage);
7547                    flags |= UPDATE_PERMISSIONS_ALL;
7548                    it.remove();
7549                }
7550            }
7551        }
7552
7553        // Make sure all dynamic permissions have been assigned to a package,
7554        // and make sure there are no dangling permissions.
7555        it = mSettings.mPermissions.values().iterator();
7556        while (it.hasNext()) {
7557            final BasePermission bp = it.next();
7558            if (bp.type == BasePermission.TYPE_DYNAMIC) {
7559                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
7560                        + bp.name + " pkg=" + bp.sourcePackage
7561                        + " info=" + bp.pendingInfo);
7562                if (bp.packageSetting == null && bp.pendingInfo != null) {
7563                    final BasePermission tree = findPermissionTreeLP(bp.name);
7564                    if (tree != null && tree.perm != null) {
7565                        bp.packageSetting = tree.packageSetting;
7566                        bp.perm = new PackageParser.Permission(tree.perm.owner,
7567                                new PermissionInfo(bp.pendingInfo));
7568                        bp.perm.info.packageName = tree.perm.info.packageName;
7569                        bp.perm.info.name = bp.name;
7570                        bp.uid = tree.uid;
7571                    }
7572                }
7573            }
7574            if (bp.packageSetting == null) {
7575                // We may not yet have parsed the package, so just see if
7576                // we still know about its settings.
7577                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
7578            }
7579            if (bp.packageSetting == null) {
7580                Slog.w(TAG, "Removing dangling permission: " + bp.name
7581                        + " from package " + bp.sourcePackage);
7582                it.remove();
7583            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
7584                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
7585                    Slog.i(TAG, "Removing old permission: " + bp.name
7586                            + " from package " + bp.sourcePackage);
7587                    flags |= UPDATE_PERMISSIONS_ALL;
7588                    it.remove();
7589                }
7590            }
7591        }
7592
7593        // Now update the permissions for all packages, in particular
7594        // replace the granted permissions of the system packages.
7595        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
7596            for (PackageParser.Package pkg : mPackages.values()) {
7597                if (pkg != pkgInfo) {
7598                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
7599                            changingPkg);
7600                }
7601            }
7602        }
7603
7604        if (pkgInfo != null) {
7605            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
7606        }
7607    }
7608
7609    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
7610            String packageOfInterest) {
7611        // IMPORTANT: There are two types of permissions: install and runtime.
7612        // Install time permissions are granted when the app is installed to
7613        // all device users and users added in the future. Runtime permissions
7614        // are granted at runtime explicitly to specific users. Normal and signature
7615        // protected permissions are install time permissions. Dangerous permissions
7616        // are install permissions if the app's target SDK is Lollipop MR1 or older,
7617        // otherwise they are runtime permissions. This function does not manage
7618        // runtime permissions except for the case an app targeting Lollipop MR1
7619        // being upgraded to target a newer SDK, in which case dangerous permissions
7620        // are transformed from install time to runtime ones.
7621
7622        final PackageSetting ps = (PackageSetting) pkg.mExtras;
7623        if (ps == null) {
7624            return;
7625        }
7626
7627        PermissionsState permissionsState = ps.getPermissionsState();
7628        PermissionsState origPermissions = permissionsState;
7629
7630        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
7631
7632        int[] upgradeUserIds = EMPTY_INT_ARRAY;
7633        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
7634
7635        boolean changedInstallPermission = false;
7636
7637        if (replace) {
7638            ps.installPermissionsFixed = false;
7639            if (!ps.isSharedUser()) {
7640                origPermissions = new PermissionsState(permissionsState);
7641                permissionsState.reset();
7642            }
7643        }
7644
7645        permissionsState.setGlobalGids(mGlobalGids);
7646
7647        final int N = pkg.requestedPermissions.size();
7648        for (int i=0; i<N; i++) {
7649            final String name = pkg.requestedPermissions.get(i);
7650            final BasePermission bp = mSettings.mPermissions.get(name);
7651
7652            if (DEBUG_INSTALL) {
7653                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
7654            }
7655
7656            if (bp == null || bp.packageSetting == null) {
7657                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7658                    Slog.w(TAG, "Unknown permission " + name
7659                            + " in package " + pkg.packageName);
7660                }
7661                continue;
7662            }
7663
7664            final String perm = bp.name;
7665            boolean allowedSig = false;
7666            int grant = GRANT_DENIED;
7667
7668            // Keep track of app op permissions.
7669            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7670                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
7671                if (pkgs == null) {
7672                    pkgs = new ArraySet<>();
7673                    mAppOpPermissionPackages.put(bp.name, pkgs);
7674                }
7675                pkgs.add(pkg.packageName);
7676            }
7677
7678            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
7679            switch (level) {
7680                case PermissionInfo.PROTECTION_NORMAL: {
7681                    // For all apps normal permissions are install time ones.
7682                    grant = GRANT_INSTALL;
7683                } break;
7684
7685                case PermissionInfo.PROTECTION_DANGEROUS: {
7686                    if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
7687                        // For legacy apps dangerous permissions are install time ones.
7688                        grant = GRANT_INSTALL;
7689                    } else if (ps.isSystem()) {
7690                        final int[] updatedUserIds = ps.getPermissionsUpdatedForUserIds();
7691                        if (origPermissions.hasInstallPermission(bp.name)) {
7692                            // If a system app had an install permission, then the app was
7693                            // upgraded and we grant the permissions as runtime to all users.
7694                            grant = GRANT_UPGRADE;
7695                            upgradeUserIds = currentUserIds;
7696                        } else if (!Arrays.equals(updatedUserIds, currentUserIds)) {
7697                            // If users changed since the last permissions update for a
7698                            // system app, we grant the permission as runtime to the new users.
7699                            grant = GRANT_UPGRADE;
7700                            upgradeUserIds = currentUserIds;
7701                            for (int userId : updatedUserIds) {
7702                                upgradeUserIds = ArrayUtils.removeInt(upgradeUserIds, userId);
7703                            }
7704                        } else {
7705                            // Otherwise, we grant the permission as runtime if the app
7706                            // already had it, i.e. we preserve runtime permissions.
7707                            grant = GRANT_RUNTIME;
7708                        }
7709                    } else if (origPermissions.hasInstallPermission(bp.name)) {
7710                        // For legacy apps that became modern, install becomes runtime.
7711                        grant = GRANT_UPGRADE;
7712                        upgradeUserIds = currentUserIds;
7713                    } else if (replace) {
7714                        // For upgraded modern apps keep runtime permissions unchanged.
7715                        grant = GRANT_RUNTIME;
7716                    }
7717                } break;
7718
7719                case PermissionInfo.PROTECTION_SIGNATURE: {
7720                    // For all apps signature permissions are install time ones.
7721                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
7722                    if (allowedSig) {
7723                        grant = GRANT_INSTALL;
7724                    }
7725                } break;
7726            }
7727
7728            if (DEBUG_INSTALL) {
7729                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
7730            }
7731
7732            if (grant != GRANT_DENIED) {
7733                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
7734                    // If this is an existing, non-system package, then
7735                    // we can't add any new permissions to it.
7736                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
7737                        // Except...  if this is a permission that was added
7738                        // to the platform (note: need to only do this when
7739                        // updating the platform).
7740                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
7741                            grant = GRANT_DENIED;
7742                        }
7743                    }
7744                }
7745
7746                switch (grant) {
7747                    case GRANT_INSTALL: {
7748                        // Grant an install permission.
7749                        if (permissionsState.grantInstallPermission(bp) !=
7750                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
7751                            changedInstallPermission = true;
7752                        }
7753                    } break;
7754
7755                    case GRANT_RUNTIME: {
7756                        // Grant previously granted runtime permissions.
7757                        for (int userId : UserManagerService.getInstance().getUserIds()) {
7758                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
7759                                PermissionState permissionState = origPermissions
7760                                        .getRuntimePermissionState(bp.name, userId);
7761                                final int flags = permissionState.getFlags();
7762                                if (permissionsState.grantRuntimePermission(bp, userId) ==
7763                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
7764                                    // If we cannot put the permission as it was, we have to write.
7765                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
7766                                            changedRuntimePermissionUserIds, userId);
7767                                } else {
7768                                    // System components not only get the permissions but
7769                                    // they are also fixed, so nothing can change that.
7770                                    final int newFlags = !isSystemComponentOrPersistentPrivApp(pkg)
7771                                            ? flags
7772                                            : flags | PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
7773                                    // Propagate the permission flags.
7774                                    permissionsState.updatePermissionFlags(bp, userId,
7775                                            newFlags, newFlags);
7776                                }
7777                            }
7778                        }
7779                    } break;
7780
7781                    case GRANT_UPGRADE: {
7782                        // Grant runtime permissions for a previously held install permission.
7783                        PermissionState permissionState = origPermissions
7784                                .getInstallPermissionState(bp.name);
7785                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
7786
7787                        origPermissions.revokeInstallPermission(bp);
7788                        // We will be transferring the permission flags, so clear them.
7789                        origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
7790                                PackageManager.MASK_PERMISSION_FLAGS, 0);
7791
7792                        // If the permission is not to be promoted to runtime we ignore it and
7793                        // also its other flags as they are not applicable to install permissions.
7794                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
7795                            for (int userId : upgradeUserIds) {
7796                                if (permissionsState.grantRuntimePermission(bp, userId) !=
7797                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
7798                                    // System components not only get the permissions but
7799                                    // they are also fixed so nothing can change that.
7800                                    final int newFlags = !isSystemComponentOrPersistentPrivApp(pkg)
7801                                            ? flags
7802                                            : flags | PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
7803                                    // Transfer the permission flags.
7804                                    permissionsState.updatePermissionFlags(bp, userId,
7805                                            newFlags, newFlags);
7806                                    // If we granted the permission, we have to write.
7807                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
7808                                            changedRuntimePermissionUserIds, userId);
7809                                }
7810                            }
7811                        }
7812                    } break;
7813
7814                    default: {
7815                        if (packageOfInterest == null
7816                                || packageOfInterest.equals(pkg.packageName)) {
7817                            Slog.w(TAG, "Not granting permission " + perm
7818                                    + " to package " + pkg.packageName
7819                                    + " because it was previously installed without");
7820                        }
7821                    } break;
7822                }
7823            } else {
7824                if (permissionsState.revokeInstallPermission(bp) !=
7825                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
7826                    // Also drop the permission flags.
7827                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
7828                            PackageManager.MASK_PERMISSION_FLAGS, 0);
7829                    changedInstallPermission = true;
7830                    Slog.i(TAG, "Un-granting permission " + perm
7831                            + " from package " + pkg.packageName
7832                            + " (protectionLevel=" + bp.protectionLevel
7833                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
7834                            + ")");
7835                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
7836                    // Don't print warning for app op permissions, since it is fine for them
7837                    // not to be granted, there is a UI for the user to decide.
7838                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7839                        Slog.w(TAG, "Not granting permission " + perm
7840                                + " to package " + pkg.packageName
7841                                + " (protectionLevel=" + bp.protectionLevel
7842                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
7843                                + ")");
7844                    }
7845                }
7846            }
7847        }
7848
7849        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
7850                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
7851            // This is the first that we have heard about this package, so the
7852            // permissions we have now selected are fixed until explicitly
7853            // changed.
7854            ps.installPermissionsFixed = true;
7855        }
7856
7857        ps.setPermissionsUpdatedForUserIds(currentUserIds);
7858
7859        // Persist the runtime permissions state for users with changes.
7860        for (int userId : changedRuntimePermissionUserIds) {
7861            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
7862        }
7863    }
7864
7865    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
7866        boolean allowed = false;
7867        final int NP = PackageParser.NEW_PERMISSIONS.length;
7868        for (int ip=0; ip<NP; ip++) {
7869            final PackageParser.NewPermissionInfo npi
7870                    = PackageParser.NEW_PERMISSIONS[ip];
7871            if (npi.name.equals(perm)
7872                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
7873                allowed = true;
7874                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
7875                        + pkg.packageName);
7876                break;
7877            }
7878        }
7879        return allowed;
7880    }
7881
7882    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
7883            BasePermission bp, PermissionsState origPermissions) {
7884        boolean allowed;
7885        allowed = (compareSignatures(
7886                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
7887                        == PackageManager.SIGNATURE_MATCH)
7888                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
7889                        == PackageManager.SIGNATURE_MATCH);
7890        if (!allowed && (bp.protectionLevel
7891                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
7892            if (isSystemApp(pkg)) {
7893                // For updated system applications, a system permission
7894                // is granted only if it had been defined by the original application.
7895                if (pkg.isUpdatedSystemApp()) {
7896                    final PackageSetting sysPs = mSettings
7897                            .getDisabledSystemPkgLPr(pkg.packageName);
7898                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
7899                        // If the original was granted this permission, we take
7900                        // that grant decision as read and propagate it to the
7901                        // update.
7902                        if (sysPs.isPrivileged()) {
7903                            allowed = true;
7904                        }
7905                    } else {
7906                        // The system apk may have been updated with an older
7907                        // version of the one on the data partition, but which
7908                        // granted a new system permission that it didn't have
7909                        // before.  In this case we do want to allow the app to
7910                        // now get the new permission if the ancestral apk is
7911                        // privileged to get it.
7912                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
7913                            for (int j=0;
7914                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
7915                                if (perm.equals(
7916                                        sysPs.pkg.requestedPermissions.get(j))) {
7917                                    allowed = true;
7918                                    break;
7919                                }
7920                            }
7921                        }
7922                    }
7923                } else {
7924                    allowed = isPrivilegedApp(pkg);
7925                }
7926            }
7927        }
7928        if (!allowed && (bp.protectionLevel
7929                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
7930            // For development permissions, a development permission
7931            // is granted only if it was already granted.
7932            allowed = origPermissions.hasInstallPermission(perm);
7933        }
7934        return allowed;
7935    }
7936
7937    final class ActivityIntentResolver
7938            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
7939        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7940                boolean defaultOnly, int userId) {
7941            if (!sUserManager.exists(userId)) return null;
7942            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7943            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7944        }
7945
7946        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7947                int userId) {
7948            if (!sUserManager.exists(userId)) return null;
7949            mFlags = flags;
7950            return super.queryIntent(intent, resolvedType,
7951                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7952        }
7953
7954        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7955                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
7956            if (!sUserManager.exists(userId)) return null;
7957            if (packageActivities == null) {
7958                return null;
7959            }
7960            mFlags = flags;
7961            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7962            final int N = packageActivities.size();
7963            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
7964                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
7965
7966            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
7967            for (int i = 0; i < N; ++i) {
7968                intentFilters = packageActivities.get(i).intents;
7969                if (intentFilters != null && intentFilters.size() > 0) {
7970                    PackageParser.ActivityIntentInfo[] array =
7971                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
7972                    intentFilters.toArray(array);
7973                    listCut.add(array);
7974                }
7975            }
7976            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7977        }
7978
7979        public final void addActivity(PackageParser.Activity a, String type) {
7980            final boolean systemApp = a.info.applicationInfo.isSystemApp();
7981            mActivities.put(a.getComponentName(), a);
7982            if (DEBUG_SHOW_INFO)
7983                Log.v(
7984                TAG, "  " + type + " " +
7985                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
7986            if (DEBUG_SHOW_INFO)
7987                Log.v(TAG, "    Class=" + a.info.name);
7988            final int NI = a.intents.size();
7989            for (int j=0; j<NI; j++) {
7990                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7991                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
7992                    intent.setPriority(0);
7993                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
7994                            + a.className + " with priority > 0, forcing to 0");
7995                }
7996                if (DEBUG_SHOW_INFO) {
7997                    Log.v(TAG, "    IntentFilter:");
7998                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7999                }
8000                if (!intent.debugCheck()) {
8001                    Log.w(TAG, "==> For Activity " + a.info.name);
8002                }
8003                addFilter(intent);
8004            }
8005        }
8006
8007        public final void removeActivity(PackageParser.Activity a, String type) {
8008            mActivities.remove(a.getComponentName());
8009            if (DEBUG_SHOW_INFO) {
8010                Log.v(TAG, "  " + type + " "
8011                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
8012                                : a.info.name) + ":");
8013                Log.v(TAG, "    Class=" + a.info.name);
8014            }
8015            final int NI = a.intents.size();
8016            for (int j=0; j<NI; j++) {
8017                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8018                if (DEBUG_SHOW_INFO) {
8019                    Log.v(TAG, "    IntentFilter:");
8020                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8021                }
8022                removeFilter(intent);
8023            }
8024        }
8025
8026        @Override
8027        protected boolean allowFilterResult(
8028                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
8029            ActivityInfo filterAi = filter.activity.info;
8030            for (int i=dest.size()-1; i>=0; i--) {
8031                ActivityInfo destAi = dest.get(i).activityInfo;
8032                if (destAi.name == filterAi.name
8033                        && destAi.packageName == filterAi.packageName) {
8034                    return false;
8035                }
8036            }
8037            return true;
8038        }
8039
8040        @Override
8041        protected ActivityIntentInfo[] newArray(int size) {
8042            return new ActivityIntentInfo[size];
8043        }
8044
8045        @Override
8046        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
8047            if (!sUserManager.exists(userId)) return true;
8048            PackageParser.Package p = filter.activity.owner;
8049            if (p != null) {
8050                PackageSetting ps = (PackageSetting)p.mExtras;
8051                if (ps != null) {
8052                    // System apps are never considered stopped for purposes of
8053                    // filtering, because there may be no way for the user to
8054                    // actually re-launch them.
8055                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
8056                            && ps.getStopped(userId);
8057                }
8058            }
8059            return false;
8060        }
8061
8062        @Override
8063        protected boolean isPackageForFilter(String packageName,
8064                PackageParser.ActivityIntentInfo info) {
8065            return packageName.equals(info.activity.owner.packageName);
8066        }
8067
8068        @Override
8069        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
8070                int match, int userId) {
8071            if (!sUserManager.exists(userId)) return null;
8072            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
8073                return null;
8074            }
8075            final PackageParser.Activity activity = info.activity;
8076            if (mSafeMode && (activity.info.applicationInfo.flags
8077                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8078                return null;
8079            }
8080            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
8081            if (ps == null) {
8082                return null;
8083            }
8084            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
8085                    ps.readUserState(userId), userId);
8086            if (ai == null) {
8087                return null;
8088            }
8089            final ResolveInfo res = new ResolveInfo();
8090            res.activityInfo = ai;
8091            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8092                res.filter = info;
8093            }
8094            if (info != null) {
8095                res.handleAllWebDataURI = info.handleAllWebDataURI();
8096            }
8097            res.priority = info.getPriority();
8098            res.preferredOrder = activity.owner.mPreferredOrder;
8099            //System.out.println("Result: " + res.activityInfo.className +
8100            //                   " = " + res.priority);
8101            res.match = match;
8102            res.isDefault = info.hasDefault;
8103            res.labelRes = info.labelRes;
8104            res.nonLocalizedLabel = info.nonLocalizedLabel;
8105            if (userNeedsBadging(userId)) {
8106                res.noResourceId = true;
8107            } else {
8108                res.icon = info.icon;
8109            }
8110            res.system = res.activityInfo.applicationInfo.isSystemApp();
8111            return res;
8112        }
8113
8114        @Override
8115        protected void sortResults(List<ResolveInfo> results) {
8116            Collections.sort(results, mResolvePrioritySorter);
8117        }
8118
8119        @Override
8120        protected void dumpFilter(PrintWriter out, String prefix,
8121                PackageParser.ActivityIntentInfo filter) {
8122            out.print(prefix); out.print(
8123                    Integer.toHexString(System.identityHashCode(filter.activity)));
8124                    out.print(' ');
8125                    filter.activity.printComponentShortName(out);
8126                    out.print(" filter ");
8127                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8128        }
8129
8130        @Override
8131        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
8132            return filter.activity;
8133        }
8134
8135        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8136            PackageParser.Activity activity = (PackageParser.Activity)label;
8137            out.print(prefix); out.print(
8138                    Integer.toHexString(System.identityHashCode(activity)));
8139                    out.print(' ');
8140                    activity.printComponentShortName(out);
8141            if (count > 1) {
8142                out.print(" ("); out.print(count); out.print(" filters)");
8143            }
8144            out.println();
8145        }
8146
8147//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8148//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8149//            final List<ResolveInfo> retList = Lists.newArrayList();
8150//            while (i.hasNext()) {
8151//                final ResolveInfo resolveInfo = i.next();
8152//                if (isEnabledLP(resolveInfo.activityInfo)) {
8153//                    retList.add(resolveInfo);
8154//                }
8155//            }
8156//            return retList;
8157//        }
8158
8159        // Keys are String (activity class name), values are Activity.
8160        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
8161                = new ArrayMap<ComponentName, PackageParser.Activity>();
8162        private int mFlags;
8163    }
8164
8165    private final class ServiceIntentResolver
8166            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
8167        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8168                boolean defaultOnly, int userId) {
8169            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8170            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8171        }
8172
8173        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8174                int userId) {
8175            if (!sUserManager.exists(userId)) return null;
8176            mFlags = flags;
8177            return super.queryIntent(intent, resolvedType,
8178                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8179        }
8180
8181        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8182                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
8183            if (!sUserManager.exists(userId)) return null;
8184            if (packageServices == null) {
8185                return null;
8186            }
8187            mFlags = flags;
8188            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8189            final int N = packageServices.size();
8190            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
8191                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
8192
8193            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
8194            for (int i = 0; i < N; ++i) {
8195                intentFilters = packageServices.get(i).intents;
8196                if (intentFilters != null && intentFilters.size() > 0) {
8197                    PackageParser.ServiceIntentInfo[] array =
8198                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
8199                    intentFilters.toArray(array);
8200                    listCut.add(array);
8201                }
8202            }
8203            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8204        }
8205
8206        public final void addService(PackageParser.Service s) {
8207            mServices.put(s.getComponentName(), s);
8208            if (DEBUG_SHOW_INFO) {
8209                Log.v(TAG, "  "
8210                        + (s.info.nonLocalizedLabel != null
8211                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8212                Log.v(TAG, "    Class=" + s.info.name);
8213            }
8214            final int NI = s.intents.size();
8215            int j;
8216            for (j=0; j<NI; j++) {
8217                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8218                if (DEBUG_SHOW_INFO) {
8219                    Log.v(TAG, "    IntentFilter:");
8220                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8221                }
8222                if (!intent.debugCheck()) {
8223                    Log.w(TAG, "==> For Service " + s.info.name);
8224                }
8225                addFilter(intent);
8226            }
8227        }
8228
8229        public final void removeService(PackageParser.Service s) {
8230            mServices.remove(s.getComponentName());
8231            if (DEBUG_SHOW_INFO) {
8232                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
8233                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8234                Log.v(TAG, "    Class=" + s.info.name);
8235            }
8236            final int NI = s.intents.size();
8237            int j;
8238            for (j=0; j<NI; j++) {
8239                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8240                if (DEBUG_SHOW_INFO) {
8241                    Log.v(TAG, "    IntentFilter:");
8242                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8243                }
8244                removeFilter(intent);
8245            }
8246        }
8247
8248        @Override
8249        protected boolean allowFilterResult(
8250                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
8251            ServiceInfo filterSi = filter.service.info;
8252            for (int i=dest.size()-1; i>=0; i--) {
8253                ServiceInfo destAi = dest.get(i).serviceInfo;
8254                if (destAi.name == filterSi.name
8255                        && destAi.packageName == filterSi.packageName) {
8256                    return false;
8257                }
8258            }
8259            return true;
8260        }
8261
8262        @Override
8263        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
8264            return new PackageParser.ServiceIntentInfo[size];
8265        }
8266
8267        @Override
8268        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
8269            if (!sUserManager.exists(userId)) return true;
8270            PackageParser.Package p = filter.service.owner;
8271            if (p != null) {
8272                PackageSetting ps = (PackageSetting)p.mExtras;
8273                if (ps != null) {
8274                    // System apps are never considered stopped for purposes of
8275                    // filtering, because there may be no way for the user to
8276                    // actually re-launch them.
8277                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8278                            && ps.getStopped(userId);
8279                }
8280            }
8281            return false;
8282        }
8283
8284        @Override
8285        protected boolean isPackageForFilter(String packageName,
8286                PackageParser.ServiceIntentInfo info) {
8287            return packageName.equals(info.service.owner.packageName);
8288        }
8289
8290        @Override
8291        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
8292                int match, int userId) {
8293            if (!sUserManager.exists(userId)) return null;
8294            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
8295            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
8296                return null;
8297            }
8298            final PackageParser.Service service = info.service;
8299            if (mSafeMode && (service.info.applicationInfo.flags
8300                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8301                return null;
8302            }
8303            PackageSetting ps = (PackageSetting) service.owner.mExtras;
8304            if (ps == null) {
8305                return null;
8306            }
8307            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
8308                    ps.readUserState(userId), userId);
8309            if (si == null) {
8310                return null;
8311            }
8312            final ResolveInfo res = new ResolveInfo();
8313            res.serviceInfo = si;
8314            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8315                res.filter = filter;
8316            }
8317            res.priority = info.getPriority();
8318            res.preferredOrder = service.owner.mPreferredOrder;
8319            res.match = match;
8320            res.isDefault = info.hasDefault;
8321            res.labelRes = info.labelRes;
8322            res.nonLocalizedLabel = info.nonLocalizedLabel;
8323            res.icon = info.icon;
8324            res.system = res.serviceInfo.applicationInfo.isSystemApp();
8325            return res;
8326        }
8327
8328        @Override
8329        protected void sortResults(List<ResolveInfo> results) {
8330            Collections.sort(results, mResolvePrioritySorter);
8331        }
8332
8333        @Override
8334        protected void dumpFilter(PrintWriter out, String prefix,
8335                PackageParser.ServiceIntentInfo filter) {
8336            out.print(prefix); out.print(
8337                    Integer.toHexString(System.identityHashCode(filter.service)));
8338                    out.print(' ');
8339                    filter.service.printComponentShortName(out);
8340                    out.print(" filter ");
8341                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8342        }
8343
8344        @Override
8345        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
8346            return filter.service;
8347        }
8348
8349        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8350            PackageParser.Service service = (PackageParser.Service)label;
8351            out.print(prefix); out.print(
8352                    Integer.toHexString(System.identityHashCode(service)));
8353                    out.print(' ');
8354                    service.printComponentShortName(out);
8355            if (count > 1) {
8356                out.print(" ("); out.print(count); out.print(" filters)");
8357            }
8358            out.println();
8359        }
8360
8361//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8362//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8363//            final List<ResolveInfo> retList = Lists.newArrayList();
8364//            while (i.hasNext()) {
8365//                final ResolveInfo resolveInfo = (ResolveInfo) i;
8366//                if (isEnabledLP(resolveInfo.serviceInfo)) {
8367//                    retList.add(resolveInfo);
8368//                }
8369//            }
8370//            return retList;
8371//        }
8372
8373        // Keys are String (activity class name), values are Activity.
8374        private final ArrayMap<ComponentName, PackageParser.Service> mServices
8375                = new ArrayMap<ComponentName, PackageParser.Service>();
8376        private int mFlags;
8377    };
8378
8379    private final class ProviderIntentResolver
8380            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
8381        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8382                boolean defaultOnly, int userId) {
8383            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8384            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8385        }
8386
8387        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8388                int userId) {
8389            if (!sUserManager.exists(userId))
8390                return null;
8391            mFlags = flags;
8392            return super.queryIntent(intent, resolvedType,
8393                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8394        }
8395
8396        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8397                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
8398            if (!sUserManager.exists(userId))
8399                return null;
8400            if (packageProviders == null) {
8401                return null;
8402            }
8403            mFlags = flags;
8404            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
8405            final int N = packageProviders.size();
8406            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
8407                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
8408
8409            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
8410            for (int i = 0; i < N; ++i) {
8411                intentFilters = packageProviders.get(i).intents;
8412                if (intentFilters != null && intentFilters.size() > 0) {
8413                    PackageParser.ProviderIntentInfo[] array =
8414                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
8415                    intentFilters.toArray(array);
8416                    listCut.add(array);
8417                }
8418            }
8419            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8420        }
8421
8422        public final void addProvider(PackageParser.Provider p) {
8423            if (mProviders.containsKey(p.getComponentName())) {
8424                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
8425                return;
8426            }
8427
8428            mProviders.put(p.getComponentName(), p);
8429            if (DEBUG_SHOW_INFO) {
8430                Log.v(TAG, "  "
8431                        + (p.info.nonLocalizedLabel != null
8432                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
8433                Log.v(TAG, "    Class=" + p.info.name);
8434            }
8435            final int NI = p.intents.size();
8436            int j;
8437            for (j = 0; j < NI; j++) {
8438                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
8439                if (DEBUG_SHOW_INFO) {
8440                    Log.v(TAG, "    IntentFilter:");
8441                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8442                }
8443                if (!intent.debugCheck()) {
8444                    Log.w(TAG, "==> For Provider " + p.info.name);
8445                }
8446                addFilter(intent);
8447            }
8448        }
8449
8450        public final void removeProvider(PackageParser.Provider p) {
8451            mProviders.remove(p.getComponentName());
8452            if (DEBUG_SHOW_INFO) {
8453                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
8454                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
8455                Log.v(TAG, "    Class=" + p.info.name);
8456            }
8457            final int NI = p.intents.size();
8458            int j;
8459            for (j = 0; j < NI; j++) {
8460                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
8461                if (DEBUG_SHOW_INFO) {
8462                    Log.v(TAG, "    IntentFilter:");
8463                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8464                }
8465                removeFilter(intent);
8466            }
8467        }
8468
8469        @Override
8470        protected boolean allowFilterResult(
8471                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
8472            ProviderInfo filterPi = filter.provider.info;
8473            for (int i = dest.size() - 1; i >= 0; i--) {
8474                ProviderInfo destPi = dest.get(i).providerInfo;
8475                if (destPi.name == filterPi.name
8476                        && destPi.packageName == filterPi.packageName) {
8477                    return false;
8478                }
8479            }
8480            return true;
8481        }
8482
8483        @Override
8484        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
8485            return new PackageParser.ProviderIntentInfo[size];
8486        }
8487
8488        @Override
8489        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
8490            if (!sUserManager.exists(userId))
8491                return true;
8492            PackageParser.Package p = filter.provider.owner;
8493            if (p != null) {
8494                PackageSetting ps = (PackageSetting) p.mExtras;
8495                if (ps != null) {
8496                    // System apps are never considered stopped for purposes of
8497                    // filtering, because there may be no way for the user to
8498                    // actually re-launch them.
8499                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8500                            && ps.getStopped(userId);
8501                }
8502            }
8503            return false;
8504        }
8505
8506        @Override
8507        protected boolean isPackageForFilter(String packageName,
8508                PackageParser.ProviderIntentInfo info) {
8509            return packageName.equals(info.provider.owner.packageName);
8510        }
8511
8512        @Override
8513        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
8514                int match, int userId) {
8515            if (!sUserManager.exists(userId))
8516                return null;
8517            final PackageParser.ProviderIntentInfo info = filter;
8518            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
8519                return null;
8520            }
8521            final PackageParser.Provider provider = info.provider;
8522            if (mSafeMode && (provider.info.applicationInfo.flags
8523                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
8524                return null;
8525            }
8526            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
8527            if (ps == null) {
8528                return null;
8529            }
8530            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
8531                    ps.readUserState(userId), userId);
8532            if (pi == null) {
8533                return null;
8534            }
8535            final ResolveInfo res = new ResolveInfo();
8536            res.providerInfo = pi;
8537            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
8538                res.filter = filter;
8539            }
8540            res.priority = info.getPriority();
8541            res.preferredOrder = provider.owner.mPreferredOrder;
8542            res.match = match;
8543            res.isDefault = info.hasDefault;
8544            res.labelRes = info.labelRes;
8545            res.nonLocalizedLabel = info.nonLocalizedLabel;
8546            res.icon = info.icon;
8547            res.system = res.providerInfo.applicationInfo.isSystemApp();
8548            return res;
8549        }
8550
8551        @Override
8552        protected void sortResults(List<ResolveInfo> results) {
8553            Collections.sort(results, mResolvePrioritySorter);
8554        }
8555
8556        @Override
8557        protected void dumpFilter(PrintWriter out, String prefix,
8558                PackageParser.ProviderIntentInfo filter) {
8559            out.print(prefix);
8560            out.print(
8561                    Integer.toHexString(System.identityHashCode(filter.provider)));
8562            out.print(' ');
8563            filter.provider.printComponentShortName(out);
8564            out.print(" filter ");
8565            out.println(Integer.toHexString(System.identityHashCode(filter)));
8566        }
8567
8568        @Override
8569        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
8570            return filter.provider;
8571        }
8572
8573        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8574            PackageParser.Provider provider = (PackageParser.Provider)label;
8575            out.print(prefix); out.print(
8576                    Integer.toHexString(System.identityHashCode(provider)));
8577                    out.print(' ');
8578                    provider.printComponentShortName(out);
8579            if (count > 1) {
8580                out.print(" ("); out.print(count); out.print(" filters)");
8581            }
8582            out.println();
8583        }
8584
8585        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
8586                = new ArrayMap<ComponentName, PackageParser.Provider>();
8587        private int mFlags;
8588    };
8589
8590    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
8591            new Comparator<ResolveInfo>() {
8592        public int compare(ResolveInfo r1, ResolveInfo r2) {
8593            int v1 = r1.priority;
8594            int v2 = r2.priority;
8595            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
8596            if (v1 != v2) {
8597                return (v1 > v2) ? -1 : 1;
8598            }
8599            v1 = r1.preferredOrder;
8600            v2 = r2.preferredOrder;
8601            if (v1 != v2) {
8602                return (v1 > v2) ? -1 : 1;
8603            }
8604            if (r1.isDefault != r2.isDefault) {
8605                return r1.isDefault ? -1 : 1;
8606            }
8607            v1 = r1.match;
8608            v2 = r2.match;
8609            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
8610            if (v1 != v2) {
8611                return (v1 > v2) ? -1 : 1;
8612            }
8613            if (r1.system != r2.system) {
8614                return r1.system ? -1 : 1;
8615            }
8616            return 0;
8617        }
8618    };
8619
8620    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
8621            new Comparator<ProviderInfo>() {
8622        public int compare(ProviderInfo p1, ProviderInfo p2) {
8623            final int v1 = p1.initOrder;
8624            final int v2 = p2.initOrder;
8625            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
8626        }
8627    };
8628
8629    final void sendPackageBroadcast(final String action, final String pkg,
8630            final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
8631            final int[] userIds) {
8632        mHandler.post(new Runnable() {
8633            @Override
8634            public void run() {
8635                try {
8636                    final IActivityManager am = ActivityManagerNative.getDefault();
8637                    if (am == null) return;
8638                    final int[] resolvedUserIds;
8639                    if (userIds == null) {
8640                        resolvedUserIds = am.getRunningUserIds();
8641                    } else {
8642                        resolvedUserIds = userIds;
8643                    }
8644                    for (int id : resolvedUserIds) {
8645                        final Intent intent = new Intent(action,
8646                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
8647                        if (extras != null) {
8648                            intent.putExtras(extras);
8649                        }
8650                        if (targetPkg != null) {
8651                            intent.setPackage(targetPkg);
8652                        }
8653                        // Modify the UID when posting to other users
8654                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
8655                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
8656                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
8657                            intent.putExtra(Intent.EXTRA_UID, uid);
8658                        }
8659                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
8660                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
8661                        if (DEBUG_BROADCASTS) {
8662                            RuntimeException here = new RuntimeException("here");
8663                            here.fillInStackTrace();
8664                            Slog.d(TAG, "Sending to user " + id + ": "
8665                                    + intent.toShortString(false, true, false, false)
8666                                    + " " + intent.getExtras(), here);
8667                        }
8668                        am.broadcastIntent(null, intent, null, finishedReceiver,
8669                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
8670                                finishedReceiver != null, false, id);
8671                    }
8672                } catch (RemoteException ex) {
8673                }
8674            }
8675        });
8676    }
8677
8678    /**
8679     * Check if the external storage media is available. This is true if there
8680     * is a mounted external storage medium or if the external storage is
8681     * emulated.
8682     */
8683    private boolean isExternalMediaAvailable() {
8684        return mMediaMounted || Environment.isExternalStorageEmulated();
8685    }
8686
8687    @Override
8688    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
8689        // writer
8690        synchronized (mPackages) {
8691            if (!isExternalMediaAvailable()) {
8692                // If the external storage is no longer mounted at this point,
8693                // the caller may not have been able to delete all of this
8694                // packages files and can not delete any more.  Bail.
8695                return null;
8696            }
8697            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
8698            if (lastPackage != null) {
8699                pkgs.remove(lastPackage);
8700            }
8701            if (pkgs.size() > 0) {
8702                return pkgs.get(0);
8703            }
8704        }
8705        return null;
8706    }
8707
8708    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
8709        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
8710                userId, andCode ? 1 : 0, packageName);
8711        if (mSystemReady) {
8712            msg.sendToTarget();
8713        } else {
8714            if (mPostSystemReadyMessages == null) {
8715                mPostSystemReadyMessages = new ArrayList<>();
8716            }
8717            mPostSystemReadyMessages.add(msg);
8718        }
8719    }
8720
8721    void startCleaningPackages() {
8722        // reader
8723        synchronized (mPackages) {
8724            if (!isExternalMediaAvailable()) {
8725                return;
8726            }
8727            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
8728                return;
8729            }
8730        }
8731        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
8732        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
8733        IActivityManager am = ActivityManagerNative.getDefault();
8734        if (am != null) {
8735            try {
8736                am.startService(null, intent, null, UserHandle.USER_OWNER);
8737            } catch (RemoteException e) {
8738            }
8739        }
8740    }
8741
8742    @Override
8743    public void installPackage(String originPath, IPackageInstallObserver2 observer,
8744            int installFlags, String installerPackageName, VerificationParams verificationParams,
8745            String packageAbiOverride) {
8746        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
8747                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
8748    }
8749
8750    @Override
8751    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
8752            int installFlags, String installerPackageName, VerificationParams verificationParams,
8753            String packageAbiOverride, int userId) {
8754        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
8755
8756        final int callingUid = Binder.getCallingUid();
8757        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
8758
8759        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
8760            try {
8761                if (observer != null) {
8762                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
8763                }
8764            } catch (RemoteException re) {
8765            }
8766            return;
8767        }
8768
8769        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
8770            installFlags |= PackageManager.INSTALL_FROM_ADB;
8771
8772        } else {
8773            // Caller holds INSTALL_PACKAGES permission, so we're less strict
8774            // about installerPackageName.
8775
8776            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
8777            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
8778        }
8779
8780        UserHandle user;
8781        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
8782            user = UserHandle.ALL;
8783        } else {
8784            user = new UserHandle(userId);
8785        }
8786
8787        // Only system components can circumvent runtime permissions when installing.
8788        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
8789                && mContext.checkCallingOrSelfPermission(Manifest.permission
8790                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
8791            throw new SecurityException("You need the "
8792                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
8793                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
8794        }
8795
8796        verificationParams.setInstallerUid(callingUid);
8797
8798        final File originFile = new File(originPath);
8799        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
8800
8801        final Message msg = mHandler.obtainMessage(INIT_COPY);
8802        msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName,
8803                null, verificationParams, user, packageAbiOverride);
8804        mHandler.sendMessage(msg);
8805    }
8806
8807    void installStage(String packageName, File stagedDir, String stagedCid,
8808            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
8809            String installerPackageName, int installerUid, UserHandle user) {
8810        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
8811                params.referrerUri, installerUid, null);
8812
8813        final OriginInfo origin;
8814        if (stagedDir != null) {
8815            origin = OriginInfo.fromStagedFile(stagedDir);
8816        } else {
8817            origin = OriginInfo.fromStagedContainer(stagedCid);
8818        }
8819
8820        final Message msg = mHandler.obtainMessage(INIT_COPY);
8821        msg.obj = new InstallParams(origin, null, observer, params.installFlags,
8822                installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride);
8823        mHandler.sendMessage(msg);
8824    }
8825
8826    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
8827        Bundle extras = new Bundle(1);
8828        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
8829
8830        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
8831                packageName, extras, null, null, new int[] {userId});
8832        try {
8833            IActivityManager am = ActivityManagerNative.getDefault();
8834            final boolean isSystem =
8835                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
8836            if (isSystem && am.isUserRunning(userId, false)) {
8837                // The just-installed/enabled app is bundled on the system, so presumed
8838                // to be able to run automatically without needing an explicit launch.
8839                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
8840                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
8841                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
8842                        .setPackage(packageName);
8843                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
8844                        android.app.AppOpsManager.OP_NONE, false, false, userId);
8845            }
8846        } catch (RemoteException e) {
8847            // shouldn't happen
8848            Slog.w(TAG, "Unable to bootstrap installed package", e);
8849        }
8850    }
8851
8852    @Override
8853    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
8854            int userId) {
8855        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
8856        PackageSetting pkgSetting;
8857        final int uid = Binder.getCallingUid();
8858        enforceCrossUserPermission(uid, userId, true, true,
8859                "setApplicationHiddenSetting for user " + userId);
8860
8861        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
8862            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
8863            return false;
8864        }
8865
8866        long callingId = Binder.clearCallingIdentity();
8867        try {
8868            boolean sendAdded = false;
8869            boolean sendRemoved = false;
8870            // writer
8871            synchronized (mPackages) {
8872                pkgSetting = mSettings.mPackages.get(packageName);
8873                if (pkgSetting == null) {
8874                    return false;
8875                }
8876                if (pkgSetting.getHidden(userId) != hidden) {
8877                    pkgSetting.setHidden(hidden, userId);
8878                    mSettings.writePackageRestrictionsLPr(userId);
8879                    if (hidden) {
8880                        sendRemoved = true;
8881                    } else {
8882                        sendAdded = true;
8883                    }
8884                }
8885            }
8886            if (sendAdded) {
8887                sendPackageAddedForUser(packageName, pkgSetting, userId);
8888                return true;
8889            }
8890            if (sendRemoved) {
8891                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
8892                        "hiding pkg");
8893                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
8894            }
8895        } finally {
8896            Binder.restoreCallingIdentity(callingId);
8897        }
8898        return false;
8899    }
8900
8901    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
8902            int userId) {
8903        final PackageRemovedInfo info = new PackageRemovedInfo();
8904        info.removedPackage = packageName;
8905        info.removedUsers = new int[] {userId};
8906        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
8907        info.sendBroadcast(false, false, false);
8908    }
8909
8910    /**
8911     * Returns true if application is not found or there was an error. Otherwise it returns
8912     * the hidden state of the package for the given user.
8913     */
8914    @Override
8915    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
8916        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
8917        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
8918                false, "getApplicationHidden for user " + userId);
8919        PackageSetting pkgSetting;
8920        long callingId = Binder.clearCallingIdentity();
8921        try {
8922            // writer
8923            synchronized (mPackages) {
8924                pkgSetting = mSettings.mPackages.get(packageName);
8925                if (pkgSetting == null) {
8926                    return true;
8927                }
8928                return pkgSetting.getHidden(userId);
8929            }
8930        } finally {
8931            Binder.restoreCallingIdentity(callingId);
8932        }
8933    }
8934
8935    /**
8936     * @hide
8937     */
8938    @Override
8939    public int installExistingPackageAsUser(String packageName, int userId) {
8940        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
8941                null);
8942        PackageSetting pkgSetting;
8943        final int uid = Binder.getCallingUid();
8944        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
8945                + userId);
8946        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
8947            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
8948        }
8949
8950        long callingId = Binder.clearCallingIdentity();
8951        try {
8952            boolean sendAdded = false;
8953
8954            // writer
8955            synchronized (mPackages) {
8956                pkgSetting = mSettings.mPackages.get(packageName);
8957                if (pkgSetting == null) {
8958                    return PackageManager.INSTALL_FAILED_INVALID_URI;
8959                }
8960                if (!pkgSetting.getInstalled(userId)) {
8961                    pkgSetting.setInstalled(true, userId);
8962                    pkgSetting.setHidden(false, userId);
8963                    mSettings.writePackageRestrictionsLPr(userId);
8964                    sendAdded = true;
8965                }
8966            }
8967
8968            if (sendAdded) {
8969                sendPackageAddedForUser(packageName, pkgSetting, userId);
8970            }
8971        } finally {
8972            Binder.restoreCallingIdentity(callingId);
8973        }
8974
8975        return PackageManager.INSTALL_SUCCEEDED;
8976    }
8977
8978    boolean isUserRestricted(int userId, String restrictionKey) {
8979        Bundle restrictions = sUserManager.getUserRestrictions(userId);
8980        if (restrictions.getBoolean(restrictionKey, false)) {
8981            Log.w(TAG, "User is restricted: " + restrictionKey);
8982            return true;
8983        }
8984        return false;
8985    }
8986
8987    @Override
8988    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
8989        mContext.enforceCallingOrSelfPermission(
8990                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8991                "Only package verification agents can verify applications");
8992
8993        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
8994        final PackageVerificationResponse response = new PackageVerificationResponse(
8995                verificationCode, Binder.getCallingUid());
8996        msg.arg1 = id;
8997        msg.obj = response;
8998        mHandler.sendMessage(msg);
8999    }
9000
9001    @Override
9002    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
9003            long millisecondsToDelay) {
9004        mContext.enforceCallingOrSelfPermission(
9005                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9006                "Only package verification agents can extend verification timeouts");
9007
9008        final PackageVerificationState state = mPendingVerification.get(id);
9009        final PackageVerificationResponse response = new PackageVerificationResponse(
9010                verificationCodeAtTimeout, Binder.getCallingUid());
9011
9012        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
9013            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
9014        }
9015        if (millisecondsToDelay < 0) {
9016            millisecondsToDelay = 0;
9017        }
9018        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9019                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9020            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9021        }
9022
9023        if ((state != null) && !state.timeoutExtended()) {
9024            state.extendTimeout();
9025
9026            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9027            msg.arg1 = id;
9028            msg.obj = response;
9029            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
9030        }
9031    }
9032
9033    private void broadcastPackageVerified(int verificationId, Uri packageUri,
9034            int verificationCode, UserHandle user) {
9035        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
9036        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
9037        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9038        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9039        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
9040
9041        mContext.sendBroadcastAsUser(intent, user,
9042                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
9043    }
9044
9045    private ComponentName matchComponentForVerifier(String packageName,
9046            List<ResolveInfo> receivers) {
9047        ActivityInfo targetReceiver = null;
9048
9049        final int NR = receivers.size();
9050        for (int i = 0; i < NR; i++) {
9051            final ResolveInfo info = receivers.get(i);
9052            if (info.activityInfo == null) {
9053                continue;
9054            }
9055
9056            if (packageName.equals(info.activityInfo.packageName)) {
9057                targetReceiver = info.activityInfo;
9058                break;
9059            }
9060        }
9061
9062        if (targetReceiver == null) {
9063            return null;
9064        }
9065
9066        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
9067    }
9068
9069    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
9070            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
9071        if (pkgInfo.verifiers.length == 0) {
9072            return null;
9073        }
9074
9075        final int N = pkgInfo.verifiers.length;
9076        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
9077        for (int i = 0; i < N; i++) {
9078            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
9079
9080            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
9081                    receivers);
9082            if (comp == null) {
9083                continue;
9084            }
9085
9086            final int verifierUid = getUidForVerifier(verifierInfo);
9087            if (verifierUid == -1) {
9088                continue;
9089            }
9090
9091            if (DEBUG_VERIFY) {
9092                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
9093                        + " with the correct signature");
9094            }
9095            sufficientVerifiers.add(comp);
9096            verificationState.addSufficientVerifier(verifierUid);
9097        }
9098
9099        return sufficientVerifiers;
9100    }
9101
9102    private int getUidForVerifier(VerifierInfo verifierInfo) {
9103        synchronized (mPackages) {
9104            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
9105            if (pkg == null) {
9106                return -1;
9107            } else if (pkg.mSignatures.length != 1) {
9108                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9109                        + " has more than one signature; ignoring");
9110                return -1;
9111            }
9112
9113            /*
9114             * If the public key of the package's signature does not match
9115             * our expected public key, then this is a different package and
9116             * we should skip.
9117             */
9118
9119            final byte[] expectedPublicKey;
9120            try {
9121                final Signature verifierSig = pkg.mSignatures[0];
9122                final PublicKey publicKey = verifierSig.getPublicKey();
9123                expectedPublicKey = publicKey.getEncoded();
9124            } catch (CertificateException e) {
9125                return -1;
9126            }
9127
9128            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
9129
9130            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
9131                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9132                        + " does not have the expected public key; ignoring");
9133                return -1;
9134            }
9135
9136            return pkg.applicationInfo.uid;
9137        }
9138    }
9139
9140    @Override
9141    public void finishPackageInstall(int token) {
9142        enforceSystemOrRoot("Only the system is allowed to finish installs");
9143
9144        if (DEBUG_INSTALL) {
9145            Slog.v(TAG, "BM finishing package install for " + token);
9146        }
9147
9148        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9149        mHandler.sendMessage(msg);
9150    }
9151
9152    /**
9153     * Get the verification agent timeout.
9154     *
9155     * @return verification timeout in milliseconds
9156     */
9157    private long getVerificationTimeout() {
9158        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
9159                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
9160                DEFAULT_VERIFICATION_TIMEOUT);
9161    }
9162
9163    /**
9164     * Get the default verification agent response code.
9165     *
9166     * @return default verification response code
9167     */
9168    private int getDefaultVerificationResponse() {
9169        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9170                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
9171                DEFAULT_VERIFICATION_RESPONSE);
9172    }
9173
9174    /**
9175     * Check whether or not package verification has been enabled.
9176     *
9177     * @return true if verification should be performed
9178     */
9179    private boolean isVerificationEnabled(int userId, int installFlags) {
9180        if (!DEFAULT_VERIFY_ENABLE) {
9181            return false;
9182        }
9183
9184        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
9185
9186        // Check if installing from ADB
9187        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
9188            // Do not run verification in a test harness environment
9189            if (ActivityManager.isRunningInTestHarness()) {
9190                return false;
9191            }
9192            if (ensureVerifyAppsEnabled) {
9193                return true;
9194            }
9195            // Check if the developer does not want package verification for ADB installs
9196            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9197                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
9198                return false;
9199            }
9200        }
9201
9202        if (ensureVerifyAppsEnabled) {
9203            return true;
9204        }
9205
9206        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9207                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9208    }
9209
9210    @Override
9211    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9212            throws RemoteException {
9213        mContext.enforceCallingOrSelfPermission(
9214                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9215                "Only intentfilter verification agents can verify applications");
9216
9217        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9218        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9219                Binder.getCallingUid(), verificationCode, failedDomains);
9220        msg.arg1 = id;
9221        msg.obj = response;
9222        mHandler.sendMessage(msg);
9223    }
9224
9225    @Override
9226    public int getIntentVerificationStatus(String packageName, int userId) {
9227        synchronized (mPackages) {
9228            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
9229        }
9230    }
9231
9232    @Override
9233    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
9234        boolean result = false;
9235        synchronized (mPackages) {
9236            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
9237        }
9238        if (result) {
9239            scheduleWritePackageRestrictionsLocked(userId);
9240        }
9241        return result;
9242    }
9243
9244    @Override
9245    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
9246        synchronized (mPackages) {
9247            return mSettings.getIntentFilterVerificationsLPr(packageName);
9248        }
9249    }
9250
9251    @Override
9252    public List<IntentFilter> getAllIntentFilters(String packageName) {
9253        if (TextUtils.isEmpty(packageName)) {
9254            return Collections.<IntentFilter>emptyList();
9255        }
9256        synchronized (mPackages) {
9257            PackageParser.Package pkg = mPackages.get(packageName);
9258            if (pkg == null || pkg.activities == null) {
9259                return Collections.<IntentFilter>emptyList();
9260            }
9261            final int count = pkg.activities.size();
9262            ArrayList<IntentFilter> result = new ArrayList<>();
9263            for (int n=0; n<count; n++) {
9264                PackageParser.Activity activity = pkg.activities.get(n);
9265                if (activity.intents != null || activity.intents.size() > 0) {
9266                    result.addAll(activity.intents);
9267                }
9268            }
9269            return result;
9270        }
9271    }
9272
9273    @Override
9274    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
9275        synchronized (mPackages) {
9276            boolean result = mSettings.setDefaultBrowserPackageNameLPr(packageName, userId);
9277            if (packageName != null) {
9278                result |= updateIntentVerificationStatus(packageName,
9279                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
9280                        UserHandle.myUserId());
9281            }
9282            return result;
9283        }
9284    }
9285
9286    @Override
9287    public String getDefaultBrowserPackageName(int userId) {
9288        synchronized (mPackages) {
9289            return mSettings.getDefaultBrowserPackageNameLPw(userId);
9290        }
9291    }
9292
9293    /**
9294     * Get the "allow unknown sources" setting.
9295     *
9296     * @return the current "allow unknown sources" setting
9297     */
9298    private int getUnknownSourcesSettings() {
9299        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9300                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
9301                -1);
9302    }
9303
9304    @Override
9305    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
9306        final int uid = Binder.getCallingUid();
9307        // writer
9308        synchronized (mPackages) {
9309            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
9310            if (targetPackageSetting == null) {
9311                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
9312            }
9313
9314            PackageSetting installerPackageSetting;
9315            if (installerPackageName != null) {
9316                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
9317                if (installerPackageSetting == null) {
9318                    throw new IllegalArgumentException("Unknown installer package: "
9319                            + installerPackageName);
9320                }
9321            } else {
9322                installerPackageSetting = null;
9323            }
9324
9325            Signature[] callerSignature;
9326            Object obj = mSettings.getUserIdLPr(uid);
9327            if (obj != null) {
9328                if (obj instanceof SharedUserSetting) {
9329                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
9330                } else if (obj instanceof PackageSetting) {
9331                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
9332                } else {
9333                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
9334                }
9335            } else {
9336                throw new SecurityException("Unknown calling uid " + uid);
9337            }
9338
9339            // Verify: can't set installerPackageName to a package that is
9340            // not signed with the same cert as the caller.
9341            if (installerPackageSetting != null) {
9342                if (compareSignatures(callerSignature,
9343                        installerPackageSetting.signatures.mSignatures)
9344                        != PackageManager.SIGNATURE_MATCH) {
9345                    throw new SecurityException(
9346                            "Caller does not have same cert as new installer package "
9347                            + installerPackageName);
9348                }
9349            }
9350
9351            // Verify: if target already has an installer package, it must
9352            // be signed with the same cert as the caller.
9353            if (targetPackageSetting.installerPackageName != null) {
9354                PackageSetting setting = mSettings.mPackages.get(
9355                        targetPackageSetting.installerPackageName);
9356                // If the currently set package isn't valid, then it's always
9357                // okay to change it.
9358                if (setting != null) {
9359                    if (compareSignatures(callerSignature,
9360                            setting.signatures.mSignatures)
9361                            != PackageManager.SIGNATURE_MATCH) {
9362                        throw new SecurityException(
9363                                "Caller does not have same cert as old installer package "
9364                                + targetPackageSetting.installerPackageName);
9365                    }
9366                }
9367            }
9368
9369            // Okay!
9370            targetPackageSetting.installerPackageName = installerPackageName;
9371            scheduleWriteSettingsLocked();
9372        }
9373    }
9374
9375    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
9376        // Queue up an async operation since the package installation may take a little while.
9377        mHandler.post(new Runnable() {
9378            public void run() {
9379                mHandler.removeCallbacks(this);
9380                 // Result object to be returned
9381                PackageInstalledInfo res = new PackageInstalledInfo();
9382                res.returnCode = currentStatus;
9383                res.uid = -1;
9384                res.pkg = null;
9385                res.removedInfo = new PackageRemovedInfo();
9386                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
9387                    args.doPreInstall(res.returnCode);
9388                    synchronized (mInstallLock) {
9389                        installPackageLI(args, res);
9390                    }
9391                    args.doPostInstall(res.returnCode, res.uid);
9392                }
9393
9394                // A restore should be performed at this point if (a) the install
9395                // succeeded, (b) the operation is not an update, and (c) the new
9396                // package has not opted out of backup participation.
9397                final boolean update = res.removedInfo.removedPackage != null;
9398                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
9399                boolean doRestore = !update
9400                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
9401
9402                // Set up the post-install work request bookkeeping.  This will be used
9403                // and cleaned up by the post-install event handling regardless of whether
9404                // there's a restore pass performed.  Token values are >= 1.
9405                int token;
9406                if (mNextInstallToken < 0) mNextInstallToken = 1;
9407                token = mNextInstallToken++;
9408
9409                PostInstallData data = new PostInstallData(args, res);
9410                mRunningInstalls.put(token, data);
9411                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
9412
9413                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
9414                    // Pass responsibility to the Backup Manager.  It will perform a
9415                    // restore if appropriate, then pass responsibility back to the
9416                    // Package Manager to run the post-install observer callbacks
9417                    // and broadcasts.
9418                    IBackupManager bm = IBackupManager.Stub.asInterface(
9419                            ServiceManager.getService(Context.BACKUP_SERVICE));
9420                    if (bm != null) {
9421                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
9422                                + " to BM for possible restore");
9423                        try {
9424                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
9425                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
9426                            } else {
9427                                doRestore = false;
9428                            }
9429                        } catch (RemoteException e) {
9430                            // can't happen; the backup manager is local
9431                        } catch (Exception e) {
9432                            Slog.e(TAG, "Exception trying to enqueue restore", e);
9433                            doRestore = false;
9434                        }
9435                    } else {
9436                        Slog.e(TAG, "Backup Manager not found!");
9437                        doRestore = false;
9438                    }
9439                }
9440
9441                if (!doRestore) {
9442                    // No restore possible, or the Backup Manager was mysteriously not
9443                    // available -- just fire the post-install work request directly.
9444                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
9445                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9446                    mHandler.sendMessage(msg);
9447                }
9448            }
9449        });
9450    }
9451
9452    private abstract class HandlerParams {
9453        private static final int MAX_RETRIES = 4;
9454
9455        /**
9456         * Number of times startCopy() has been attempted and had a non-fatal
9457         * error.
9458         */
9459        private int mRetries = 0;
9460
9461        /** User handle for the user requesting the information or installation. */
9462        private final UserHandle mUser;
9463
9464        HandlerParams(UserHandle user) {
9465            mUser = user;
9466        }
9467
9468        UserHandle getUser() {
9469            return mUser;
9470        }
9471
9472        final boolean startCopy() {
9473            boolean res;
9474            try {
9475                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
9476
9477                if (++mRetries > MAX_RETRIES) {
9478                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
9479                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
9480                    handleServiceError();
9481                    return false;
9482                } else {
9483                    handleStartCopy();
9484                    res = true;
9485                }
9486            } catch (RemoteException e) {
9487                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
9488                mHandler.sendEmptyMessage(MCS_RECONNECT);
9489                res = false;
9490            }
9491            handleReturnCode();
9492            return res;
9493        }
9494
9495        final void serviceError() {
9496            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
9497            handleServiceError();
9498            handleReturnCode();
9499        }
9500
9501        abstract void handleStartCopy() throws RemoteException;
9502        abstract void handleServiceError();
9503        abstract void handleReturnCode();
9504    }
9505
9506    class MeasureParams extends HandlerParams {
9507        private final PackageStats mStats;
9508        private boolean mSuccess;
9509
9510        private final IPackageStatsObserver mObserver;
9511
9512        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
9513            super(new UserHandle(stats.userHandle));
9514            mObserver = observer;
9515            mStats = stats;
9516        }
9517
9518        @Override
9519        public String toString() {
9520            return "MeasureParams{"
9521                + Integer.toHexString(System.identityHashCode(this))
9522                + " " + mStats.packageName + "}";
9523        }
9524
9525        @Override
9526        void handleStartCopy() throws RemoteException {
9527            synchronized (mInstallLock) {
9528                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
9529            }
9530
9531            if (mSuccess) {
9532                final boolean mounted;
9533                if (Environment.isExternalStorageEmulated()) {
9534                    mounted = true;
9535                } else {
9536                    final String status = Environment.getExternalStorageState();
9537                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
9538                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
9539                }
9540
9541                if (mounted) {
9542                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
9543
9544                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
9545                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
9546
9547                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
9548                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
9549
9550                    // Always subtract cache size, since it's a subdirectory
9551                    mStats.externalDataSize -= mStats.externalCacheSize;
9552
9553                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
9554                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
9555
9556                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
9557                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
9558                }
9559            }
9560        }
9561
9562        @Override
9563        void handleReturnCode() {
9564            if (mObserver != null) {
9565                try {
9566                    mObserver.onGetStatsCompleted(mStats, mSuccess);
9567                } catch (RemoteException e) {
9568                    Slog.i(TAG, "Observer no longer exists.");
9569                }
9570            }
9571        }
9572
9573        @Override
9574        void handleServiceError() {
9575            Slog.e(TAG, "Could not measure application " + mStats.packageName
9576                            + " external storage");
9577        }
9578    }
9579
9580    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
9581            throws RemoteException {
9582        long result = 0;
9583        for (File path : paths) {
9584            result += mcs.calculateDirectorySize(path.getAbsolutePath());
9585        }
9586        return result;
9587    }
9588
9589    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
9590        for (File path : paths) {
9591            try {
9592                mcs.clearDirectory(path.getAbsolutePath());
9593            } catch (RemoteException e) {
9594            }
9595        }
9596    }
9597
9598    static class OriginInfo {
9599        /**
9600         * Location where install is coming from, before it has been
9601         * copied/renamed into place. This could be a single monolithic APK
9602         * file, or a cluster directory. This location may be untrusted.
9603         */
9604        final File file;
9605        final String cid;
9606
9607        /**
9608         * Flag indicating that {@link #file} or {@link #cid} has already been
9609         * staged, meaning downstream users don't need to defensively copy the
9610         * contents.
9611         */
9612        final boolean staged;
9613
9614        /**
9615         * Flag indicating that {@link #file} or {@link #cid} is an already
9616         * installed app that is being moved.
9617         */
9618        final boolean existing;
9619
9620        final String resolvedPath;
9621        final File resolvedFile;
9622
9623        static OriginInfo fromNothing() {
9624            return new OriginInfo(null, null, false, false);
9625        }
9626
9627        static OriginInfo fromUntrustedFile(File file) {
9628            return new OriginInfo(file, null, false, false);
9629        }
9630
9631        static OriginInfo fromExistingFile(File file) {
9632            return new OriginInfo(file, null, false, true);
9633        }
9634
9635        static OriginInfo fromStagedFile(File file) {
9636            return new OriginInfo(file, null, true, false);
9637        }
9638
9639        static OriginInfo fromStagedContainer(String cid) {
9640            return new OriginInfo(null, cid, true, false);
9641        }
9642
9643        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
9644            this.file = file;
9645            this.cid = cid;
9646            this.staged = staged;
9647            this.existing = existing;
9648
9649            if (cid != null) {
9650                resolvedPath = PackageHelper.getSdDir(cid);
9651                resolvedFile = new File(resolvedPath);
9652            } else if (file != null) {
9653                resolvedPath = file.getAbsolutePath();
9654                resolvedFile = file;
9655            } else {
9656                resolvedPath = null;
9657                resolvedFile = null;
9658            }
9659        }
9660    }
9661
9662    class MoveInfo {
9663        final int moveId;
9664        final String fromUuid;
9665        final String toUuid;
9666        final String packageName;
9667        final String dataAppName;
9668        final int appId;
9669        final String seinfo;
9670
9671        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
9672                String dataAppName, int appId, String seinfo) {
9673            this.moveId = moveId;
9674            this.fromUuid = fromUuid;
9675            this.toUuid = toUuid;
9676            this.packageName = packageName;
9677            this.dataAppName = dataAppName;
9678            this.appId = appId;
9679            this.seinfo = seinfo;
9680        }
9681    }
9682
9683    class InstallParams extends HandlerParams {
9684        final OriginInfo origin;
9685        final MoveInfo move;
9686        final IPackageInstallObserver2 observer;
9687        int installFlags;
9688        final String installerPackageName;
9689        final String volumeUuid;
9690        final VerificationParams verificationParams;
9691        private InstallArgs mArgs;
9692        private int mRet;
9693        final String packageAbiOverride;
9694
9695        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
9696                int installFlags, String installerPackageName, String volumeUuid,
9697                VerificationParams verificationParams, UserHandle user, String packageAbiOverride) {
9698            super(user);
9699            this.origin = origin;
9700            this.move = move;
9701            this.observer = observer;
9702            this.installFlags = installFlags;
9703            this.installerPackageName = installerPackageName;
9704            this.volumeUuid = volumeUuid;
9705            this.verificationParams = verificationParams;
9706            this.packageAbiOverride = packageAbiOverride;
9707        }
9708
9709        @Override
9710        public String toString() {
9711            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
9712                    + " file=" + origin.file + " cid=" + origin.cid + "}";
9713        }
9714
9715        public ManifestDigest getManifestDigest() {
9716            if (verificationParams == null) {
9717                return null;
9718            }
9719            return verificationParams.getManifestDigest();
9720        }
9721
9722        private int installLocationPolicy(PackageInfoLite pkgLite) {
9723            String packageName = pkgLite.packageName;
9724            int installLocation = pkgLite.installLocation;
9725            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9726            // reader
9727            synchronized (mPackages) {
9728                PackageParser.Package pkg = mPackages.get(packageName);
9729                if (pkg != null) {
9730                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
9731                        // Check for downgrading.
9732                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
9733                            try {
9734                                checkDowngrade(pkg, pkgLite);
9735                            } catch (PackageManagerException e) {
9736                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
9737                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
9738                            }
9739                        }
9740                        // Check for updated system application.
9741                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
9742                            if (onSd) {
9743                                Slog.w(TAG, "Cannot install update to system app on sdcard");
9744                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
9745                            }
9746                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
9747                        } else {
9748                            if (onSd) {
9749                                // Install flag overrides everything.
9750                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
9751                            }
9752                            // If current upgrade specifies particular preference
9753                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
9754                                // Application explicitly specified internal.
9755                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
9756                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
9757                                // App explictly prefers external. Let policy decide
9758                            } else {
9759                                // Prefer previous location
9760                                if (isExternal(pkg)) {
9761                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
9762                                }
9763                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
9764                            }
9765                        }
9766                    } else {
9767                        // Invalid install. Return error code
9768                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
9769                    }
9770                }
9771            }
9772            // All the special cases have been taken care of.
9773            // Return result based on recommended install location.
9774            if (onSd) {
9775                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
9776            }
9777            return pkgLite.recommendedInstallLocation;
9778        }
9779
9780        /*
9781         * Invoke remote method to get package information and install
9782         * location values. Override install location based on default
9783         * policy if needed and then create install arguments based
9784         * on the install location.
9785         */
9786        public void handleStartCopy() throws RemoteException {
9787            int ret = PackageManager.INSTALL_SUCCEEDED;
9788
9789            // If we're already staged, we've firmly committed to an install location
9790            if (origin.staged) {
9791                if (origin.file != null) {
9792                    installFlags |= PackageManager.INSTALL_INTERNAL;
9793                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
9794                } else if (origin.cid != null) {
9795                    installFlags |= PackageManager.INSTALL_EXTERNAL;
9796                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
9797                } else {
9798                    throw new IllegalStateException("Invalid stage location");
9799                }
9800            }
9801
9802            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9803            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
9804
9805            PackageInfoLite pkgLite = null;
9806
9807            if (onInt && onSd) {
9808                // Check if both bits are set.
9809                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
9810                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
9811            } else {
9812                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
9813                        packageAbiOverride);
9814
9815                /*
9816                 * If we have too little free space, try to free cache
9817                 * before giving up.
9818                 */
9819                if (!origin.staged && pkgLite.recommendedInstallLocation
9820                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
9821                    // TODO: focus freeing disk space on the target device
9822                    final StorageManager storage = StorageManager.from(mContext);
9823                    final long lowThreshold = storage.getStorageLowBytes(
9824                            Environment.getDataDirectory());
9825
9826                    final long sizeBytes = mContainerService.calculateInstalledSize(
9827                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
9828
9829                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
9830                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
9831                                installFlags, packageAbiOverride);
9832                    }
9833
9834                    /*
9835                     * The cache free must have deleted the file we
9836                     * downloaded to install.
9837                     *
9838                     * TODO: fix the "freeCache" call to not delete
9839                     *       the file we care about.
9840                     */
9841                    if (pkgLite.recommendedInstallLocation
9842                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
9843                        pkgLite.recommendedInstallLocation
9844                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
9845                    }
9846                }
9847            }
9848
9849            if (ret == PackageManager.INSTALL_SUCCEEDED) {
9850                int loc = pkgLite.recommendedInstallLocation;
9851                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
9852                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
9853                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
9854                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
9855                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
9856                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9857                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
9858                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
9859                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
9860                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
9861                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
9862                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
9863                } else {
9864                    // Override with defaults if needed.
9865                    loc = installLocationPolicy(pkgLite);
9866                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
9867                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
9868                    } else if (!onSd && !onInt) {
9869                        // Override install location with flags
9870                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
9871                            // Set the flag to install on external media.
9872                            installFlags |= PackageManager.INSTALL_EXTERNAL;
9873                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
9874                        } else {
9875                            // Make sure the flag for installing on external
9876                            // media is unset
9877                            installFlags |= PackageManager.INSTALL_INTERNAL;
9878                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
9879                        }
9880                    }
9881                }
9882            }
9883
9884            final InstallArgs args = createInstallArgs(this);
9885            mArgs = args;
9886
9887            if (ret == PackageManager.INSTALL_SUCCEEDED) {
9888                 /*
9889                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
9890                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
9891                 */
9892                int userIdentifier = getUser().getIdentifier();
9893                if (userIdentifier == UserHandle.USER_ALL
9894                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
9895                    userIdentifier = UserHandle.USER_OWNER;
9896                }
9897
9898                /*
9899                 * Determine if we have any installed package verifiers. If we
9900                 * do, then we'll defer to them to verify the packages.
9901                 */
9902                final int requiredUid = mRequiredVerifierPackage == null ? -1
9903                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
9904                if (!origin.existing && requiredUid != -1
9905                        && isVerificationEnabled(userIdentifier, installFlags)) {
9906                    final Intent verification = new Intent(
9907                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
9908                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
9909                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
9910                            PACKAGE_MIME_TYPE);
9911                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9912
9913                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
9914                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
9915                            0 /* TODO: Which userId? */);
9916
9917                    if (DEBUG_VERIFY) {
9918                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
9919                                + verification.toString() + " with " + pkgLite.verifiers.length
9920                                + " optional verifiers");
9921                    }
9922
9923                    final int verificationId = mPendingVerificationToken++;
9924
9925                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9926
9927                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
9928                            installerPackageName);
9929
9930                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
9931                            installFlags);
9932
9933                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
9934                            pkgLite.packageName);
9935
9936                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
9937                            pkgLite.versionCode);
9938
9939                    if (verificationParams != null) {
9940                        if (verificationParams.getVerificationURI() != null) {
9941                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
9942                                 verificationParams.getVerificationURI());
9943                        }
9944                        if (verificationParams.getOriginatingURI() != null) {
9945                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
9946                                  verificationParams.getOriginatingURI());
9947                        }
9948                        if (verificationParams.getReferrer() != null) {
9949                            verification.putExtra(Intent.EXTRA_REFERRER,
9950                                  verificationParams.getReferrer());
9951                        }
9952                        if (verificationParams.getOriginatingUid() >= 0) {
9953                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
9954                                  verificationParams.getOriginatingUid());
9955                        }
9956                        if (verificationParams.getInstallerUid() >= 0) {
9957                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
9958                                  verificationParams.getInstallerUid());
9959                        }
9960                    }
9961
9962                    final PackageVerificationState verificationState = new PackageVerificationState(
9963                            requiredUid, args);
9964
9965                    mPendingVerification.append(verificationId, verificationState);
9966
9967                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
9968                            receivers, verificationState);
9969
9970                    /*
9971                     * If any sufficient verifiers were listed in the package
9972                     * manifest, attempt to ask them.
9973                     */
9974                    if (sufficientVerifiers != null) {
9975                        final int N = sufficientVerifiers.size();
9976                        if (N == 0) {
9977                            Slog.i(TAG, "Additional verifiers required, but none installed.");
9978                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
9979                        } else {
9980                            for (int i = 0; i < N; i++) {
9981                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
9982
9983                                final Intent sufficientIntent = new Intent(verification);
9984                                sufficientIntent.setComponent(verifierComponent);
9985
9986                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
9987                            }
9988                        }
9989                    }
9990
9991                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
9992                            mRequiredVerifierPackage, receivers);
9993                    if (ret == PackageManager.INSTALL_SUCCEEDED
9994                            && mRequiredVerifierPackage != null) {
9995                        /*
9996                         * Send the intent to the required verification agent,
9997                         * but only start the verification timeout after the
9998                         * target BroadcastReceivers have run.
9999                         */
10000                        verification.setComponent(requiredVerifierComponent);
10001                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
10002                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10003                                new BroadcastReceiver() {
10004                                    @Override
10005                                    public void onReceive(Context context, Intent intent) {
10006                                        final Message msg = mHandler
10007                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
10008                                        msg.arg1 = verificationId;
10009                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
10010                                    }
10011                                }, null, 0, null, null);
10012
10013                        /*
10014                         * We don't want the copy to proceed until verification
10015                         * succeeds, so null out this field.
10016                         */
10017                        mArgs = null;
10018                    }
10019                } else {
10020                    /*
10021                     * No package verification is enabled, so immediately start
10022                     * the remote call to initiate copy using temporary file.
10023                     */
10024                    ret = args.copyApk(mContainerService, true);
10025                }
10026            }
10027
10028            mRet = ret;
10029        }
10030
10031        @Override
10032        void handleReturnCode() {
10033            // If mArgs is null, then MCS couldn't be reached. When it
10034            // reconnects, it will try again to install. At that point, this
10035            // will succeed.
10036            if (mArgs != null) {
10037                processPendingInstall(mArgs, mRet);
10038            }
10039        }
10040
10041        @Override
10042        void handleServiceError() {
10043            mArgs = createInstallArgs(this);
10044            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10045        }
10046
10047        public boolean isForwardLocked() {
10048            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10049        }
10050    }
10051
10052    /**
10053     * Used during creation of InstallArgs
10054     *
10055     * @param installFlags package installation flags
10056     * @return true if should be installed on external storage
10057     */
10058    private static boolean installOnExternalAsec(int installFlags) {
10059        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
10060            return false;
10061        }
10062        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
10063            return true;
10064        }
10065        return false;
10066    }
10067
10068    /**
10069     * Used during creation of InstallArgs
10070     *
10071     * @param installFlags package installation flags
10072     * @return true if should be installed as forward locked
10073     */
10074    private static boolean installForwardLocked(int installFlags) {
10075        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10076    }
10077
10078    private InstallArgs createInstallArgs(InstallParams params) {
10079        if (params.move != null) {
10080            return new MoveInstallArgs(params);
10081        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
10082            return new AsecInstallArgs(params);
10083        } else {
10084            return new FileInstallArgs(params);
10085        }
10086    }
10087
10088    /**
10089     * Create args that describe an existing installed package. Typically used
10090     * when cleaning up old installs, or used as a move source.
10091     */
10092    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
10093            String resourcePath, String[] instructionSets) {
10094        final boolean isInAsec;
10095        if (installOnExternalAsec(installFlags)) {
10096            /* Apps on SD card are always in ASEC containers. */
10097            isInAsec = true;
10098        } else if (installForwardLocked(installFlags)
10099                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
10100            /*
10101             * Forward-locked apps are only in ASEC containers if they're the
10102             * new style
10103             */
10104            isInAsec = true;
10105        } else {
10106            isInAsec = false;
10107        }
10108
10109        if (isInAsec) {
10110            return new AsecInstallArgs(codePath, instructionSets,
10111                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
10112        } else {
10113            return new FileInstallArgs(codePath, resourcePath, instructionSets);
10114        }
10115    }
10116
10117    static abstract class InstallArgs {
10118        /** @see InstallParams#origin */
10119        final OriginInfo origin;
10120        /** @see InstallParams#move */
10121        final MoveInfo move;
10122
10123        final IPackageInstallObserver2 observer;
10124        // Always refers to PackageManager flags only
10125        final int installFlags;
10126        final String installerPackageName;
10127        final String volumeUuid;
10128        final ManifestDigest manifestDigest;
10129        final UserHandle user;
10130        final String abiOverride;
10131
10132        // The list of instruction sets supported by this app. This is currently
10133        // only used during the rmdex() phase to clean up resources. We can get rid of this
10134        // if we move dex files under the common app path.
10135        /* nullable */ String[] instructionSets;
10136
10137        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10138                int installFlags, String installerPackageName, String volumeUuid,
10139                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
10140                String abiOverride) {
10141            this.origin = origin;
10142            this.move = move;
10143            this.installFlags = installFlags;
10144            this.observer = observer;
10145            this.installerPackageName = installerPackageName;
10146            this.volumeUuid = volumeUuid;
10147            this.manifestDigest = manifestDigest;
10148            this.user = user;
10149            this.instructionSets = instructionSets;
10150            this.abiOverride = abiOverride;
10151        }
10152
10153        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
10154        abstract int doPreInstall(int status);
10155
10156        /**
10157         * Rename package into final resting place. All paths on the given
10158         * scanned package should be updated to reflect the rename.
10159         */
10160        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
10161        abstract int doPostInstall(int status, int uid);
10162
10163        /** @see PackageSettingBase#codePathString */
10164        abstract String getCodePath();
10165        /** @see PackageSettingBase#resourcePathString */
10166        abstract String getResourcePath();
10167
10168        // Need installer lock especially for dex file removal.
10169        abstract void cleanUpResourcesLI();
10170        abstract boolean doPostDeleteLI(boolean delete);
10171
10172        /**
10173         * Called before the source arguments are copied. This is used mostly
10174         * for MoveParams when it needs to read the source file to put it in the
10175         * destination.
10176         */
10177        int doPreCopy() {
10178            return PackageManager.INSTALL_SUCCEEDED;
10179        }
10180
10181        /**
10182         * Called after the source arguments are copied. This is used mostly for
10183         * MoveParams when it needs to read the source file to put it in the
10184         * destination.
10185         *
10186         * @return
10187         */
10188        int doPostCopy(int uid) {
10189            return PackageManager.INSTALL_SUCCEEDED;
10190        }
10191
10192        protected boolean isFwdLocked() {
10193            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10194        }
10195
10196        protected boolean isExternalAsec() {
10197            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10198        }
10199
10200        UserHandle getUser() {
10201            return user;
10202        }
10203    }
10204
10205    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
10206        if (!allCodePaths.isEmpty()) {
10207            if (instructionSets == null) {
10208                throw new IllegalStateException("instructionSet == null");
10209            }
10210            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
10211            for (String codePath : allCodePaths) {
10212                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
10213                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
10214                    if (retCode < 0) {
10215                        Slog.w(TAG, "Couldn't remove dex file for package: "
10216                                + " at location " + codePath + ", retcode=" + retCode);
10217                        // we don't consider this to be a failure of the core package deletion
10218                    }
10219                }
10220            }
10221        }
10222    }
10223
10224    /**
10225     * Logic to handle installation of non-ASEC applications, including copying
10226     * and renaming logic.
10227     */
10228    class FileInstallArgs extends InstallArgs {
10229        private File codeFile;
10230        private File resourceFile;
10231
10232        // Example topology:
10233        // /data/app/com.example/base.apk
10234        // /data/app/com.example/split_foo.apk
10235        // /data/app/com.example/lib/arm/libfoo.so
10236        // /data/app/com.example/lib/arm64/libfoo.so
10237        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
10238
10239        /** New install */
10240        FileInstallArgs(InstallParams params) {
10241            super(params.origin, params.move, params.observer, params.installFlags,
10242                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10243                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10244            if (isFwdLocked()) {
10245                throw new IllegalArgumentException("Forward locking only supported in ASEC");
10246            }
10247        }
10248
10249        /** Existing install */
10250        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
10251            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
10252                    null);
10253            this.codeFile = (codePath != null) ? new File(codePath) : null;
10254            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
10255        }
10256
10257        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10258            if (origin.staged) {
10259                Slog.d(TAG, origin.file + " already staged; skipping copy");
10260                codeFile = origin.file;
10261                resourceFile = origin.file;
10262                return PackageManager.INSTALL_SUCCEEDED;
10263            }
10264
10265            try {
10266                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
10267                codeFile = tempDir;
10268                resourceFile = tempDir;
10269            } catch (IOException e) {
10270                Slog.w(TAG, "Failed to create copy file: " + e);
10271                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10272            }
10273
10274            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
10275                @Override
10276                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
10277                    if (!FileUtils.isValidExtFilename(name)) {
10278                        throw new IllegalArgumentException("Invalid filename: " + name);
10279                    }
10280                    try {
10281                        final File file = new File(codeFile, name);
10282                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
10283                                O_RDWR | O_CREAT, 0644);
10284                        Os.chmod(file.getAbsolutePath(), 0644);
10285                        return new ParcelFileDescriptor(fd);
10286                    } catch (ErrnoException e) {
10287                        throw new RemoteException("Failed to open: " + e.getMessage());
10288                    }
10289                }
10290            };
10291
10292            int ret = PackageManager.INSTALL_SUCCEEDED;
10293            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
10294            if (ret != PackageManager.INSTALL_SUCCEEDED) {
10295                Slog.e(TAG, "Failed to copy package");
10296                return ret;
10297            }
10298
10299            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
10300            NativeLibraryHelper.Handle handle = null;
10301            try {
10302                handle = NativeLibraryHelper.Handle.create(codeFile);
10303                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
10304                        abiOverride);
10305            } catch (IOException e) {
10306                Slog.e(TAG, "Copying native libraries failed", e);
10307                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10308            } finally {
10309                IoUtils.closeQuietly(handle);
10310            }
10311
10312            return ret;
10313        }
10314
10315        int doPreInstall(int status) {
10316            if (status != PackageManager.INSTALL_SUCCEEDED) {
10317                cleanUp();
10318            }
10319            return status;
10320        }
10321
10322        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10323            if (status != PackageManager.INSTALL_SUCCEEDED) {
10324                cleanUp();
10325                return false;
10326            }
10327
10328            final File targetDir = codeFile.getParentFile();
10329            final File beforeCodeFile = codeFile;
10330            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
10331
10332            Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
10333            try {
10334                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
10335            } catch (ErrnoException e) {
10336                Slog.d(TAG, "Failed to rename", e);
10337                return false;
10338            }
10339
10340            if (!SELinux.restoreconRecursive(afterCodeFile)) {
10341                Slog.d(TAG, "Failed to restorecon");
10342                return false;
10343            }
10344
10345            // Reflect the rename internally
10346            codeFile = afterCodeFile;
10347            resourceFile = afterCodeFile;
10348
10349            // Reflect the rename in scanned details
10350            pkg.codePath = afterCodeFile.getAbsolutePath();
10351            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10352                    pkg.baseCodePath);
10353            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10354                    pkg.splitCodePaths);
10355
10356            // Reflect the rename in app info
10357            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10358            pkg.applicationInfo.setCodePath(pkg.codePath);
10359            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10360            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10361            pkg.applicationInfo.setResourcePath(pkg.codePath);
10362            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10363            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10364
10365            return true;
10366        }
10367
10368        int doPostInstall(int status, int uid) {
10369            if (status != PackageManager.INSTALL_SUCCEEDED) {
10370                cleanUp();
10371            }
10372            return status;
10373        }
10374
10375        @Override
10376        String getCodePath() {
10377            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
10378        }
10379
10380        @Override
10381        String getResourcePath() {
10382            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
10383        }
10384
10385        private boolean cleanUp() {
10386            if (codeFile == null || !codeFile.exists()) {
10387                return false;
10388            }
10389
10390            if (codeFile.isDirectory()) {
10391                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
10392            } else {
10393                codeFile.delete();
10394            }
10395
10396            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
10397                resourceFile.delete();
10398            }
10399
10400            return true;
10401        }
10402
10403        void cleanUpResourcesLI() {
10404            // Try enumerating all code paths before deleting
10405            List<String> allCodePaths = Collections.EMPTY_LIST;
10406            if (codeFile != null && codeFile.exists()) {
10407                try {
10408                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
10409                    allCodePaths = pkg.getAllCodePaths();
10410                } catch (PackageParserException e) {
10411                    // Ignored; we tried our best
10412                }
10413            }
10414
10415            cleanUp();
10416            removeDexFiles(allCodePaths, instructionSets);
10417        }
10418
10419        boolean doPostDeleteLI(boolean delete) {
10420            // XXX err, shouldn't we respect the delete flag?
10421            cleanUpResourcesLI();
10422            return true;
10423        }
10424    }
10425
10426    private boolean isAsecExternal(String cid) {
10427        final String asecPath = PackageHelper.getSdFilesystem(cid);
10428        return !asecPath.startsWith(mAsecInternalPath);
10429    }
10430
10431    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
10432            PackageManagerException {
10433        if (copyRet < 0) {
10434            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
10435                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
10436                throw new PackageManagerException(copyRet, message);
10437            }
10438        }
10439    }
10440
10441    /**
10442     * Extract the MountService "container ID" from the full code path of an
10443     * .apk.
10444     */
10445    static String cidFromCodePath(String fullCodePath) {
10446        int eidx = fullCodePath.lastIndexOf("/");
10447        String subStr1 = fullCodePath.substring(0, eidx);
10448        int sidx = subStr1.lastIndexOf("/");
10449        return subStr1.substring(sidx+1, eidx);
10450    }
10451
10452    /**
10453     * Logic to handle installation of ASEC applications, including copying and
10454     * renaming logic.
10455     */
10456    class AsecInstallArgs extends InstallArgs {
10457        static final String RES_FILE_NAME = "pkg.apk";
10458        static final String PUBLIC_RES_FILE_NAME = "res.zip";
10459
10460        String cid;
10461        String packagePath;
10462        String resourcePath;
10463
10464        /** New install */
10465        AsecInstallArgs(InstallParams params) {
10466            super(params.origin, params.move, params.observer, params.installFlags,
10467                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10468                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10469        }
10470
10471        /** Existing install */
10472        AsecInstallArgs(String fullCodePath, String[] instructionSets,
10473                        boolean isExternal, boolean isForwardLocked) {
10474            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
10475                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
10476                    instructionSets, null);
10477            // Hackily pretend we're still looking at a full code path
10478            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
10479                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
10480            }
10481
10482            // Extract cid from fullCodePath
10483            int eidx = fullCodePath.lastIndexOf("/");
10484            String subStr1 = fullCodePath.substring(0, eidx);
10485            int sidx = subStr1.lastIndexOf("/");
10486            cid = subStr1.substring(sidx+1, eidx);
10487            setMountPath(subStr1);
10488        }
10489
10490        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
10491            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
10492                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
10493                    instructionSets, null);
10494            this.cid = cid;
10495            setMountPath(PackageHelper.getSdDir(cid));
10496        }
10497
10498        void createCopyFile() {
10499            cid = mInstallerService.allocateExternalStageCidLegacy();
10500        }
10501
10502        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10503            if (origin.staged) {
10504                Slog.d(TAG, origin.cid + " already staged; skipping copy");
10505                cid = origin.cid;
10506                setMountPath(PackageHelper.getSdDir(cid));
10507                return PackageManager.INSTALL_SUCCEEDED;
10508            }
10509
10510            if (temp) {
10511                createCopyFile();
10512            } else {
10513                /*
10514                 * Pre-emptively destroy the container since it's destroyed if
10515                 * copying fails due to it existing anyway.
10516                 */
10517                PackageHelper.destroySdDir(cid);
10518            }
10519
10520            final String newMountPath = imcs.copyPackageToContainer(
10521                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
10522                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
10523
10524            if (newMountPath != null) {
10525                setMountPath(newMountPath);
10526                return PackageManager.INSTALL_SUCCEEDED;
10527            } else {
10528                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10529            }
10530        }
10531
10532        @Override
10533        String getCodePath() {
10534            return packagePath;
10535        }
10536
10537        @Override
10538        String getResourcePath() {
10539            return resourcePath;
10540        }
10541
10542        int doPreInstall(int status) {
10543            if (status != PackageManager.INSTALL_SUCCEEDED) {
10544                // Destroy container
10545                PackageHelper.destroySdDir(cid);
10546            } else {
10547                boolean mounted = PackageHelper.isContainerMounted(cid);
10548                if (!mounted) {
10549                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
10550                            Process.SYSTEM_UID);
10551                    if (newMountPath != null) {
10552                        setMountPath(newMountPath);
10553                    } else {
10554                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10555                    }
10556                }
10557            }
10558            return status;
10559        }
10560
10561        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10562            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
10563            String newMountPath = null;
10564            if (PackageHelper.isContainerMounted(cid)) {
10565                // Unmount the container
10566                if (!PackageHelper.unMountSdDir(cid)) {
10567                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
10568                    return false;
10569                }
10570            }
10571            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
10572                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
10573                        " which might be stale. Will try to clean up.");
10574                // Clean up the stale container and proceed to recreate.
10575                if (!PackageHelper.destroySdDir(newCacheId)) {
10576                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
10577                    return false;
10578                }
10579                // Successfully cleaned up stale container. Try to rename again.
10580                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
10581                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
10582                            + " inspite of cleaning it up.");
10583                    return false;
10584                }
10585            }
10586            if (!PackageHelper.isContainerMounted(newCacheId)) {
10587                Slog.w(TAG, "Mounting container " + newCacheId);
10588                newMountPath = PackageHelper.mountSdDir(newCacheId,
10589                        getEncryptKey(), Process.SYSTEM_UID);
10590            } else {
10591                newMountPath = PackageHelper.getSdDir(newCacheId);
10592            }
10593            if (newMountPath == null) {
10594                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
10595                return false;
10596            }
10597            Log.i(TAG, "Succesfully renamed " + cid +
10598                    " to " + newCacheId +
10599                    " at new path: " + newMountPath);
10600            cid = newCacheId;
10601
10602            final File beforeCodeFile = new File(packagePath);
10603            setMountPath(newMountPath);
10604            final File afterCodeFile = new File(packagePath);
10605
10606            // Reflect the rename in scanned details
10607            pkg.codePath = afterCodeFile.getAbsolutePath();
10608            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10609                    pkg.baseCodePath);
10610            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10611                    pkg.splitCodePaths);
10612
10613            // Reflect the rename in app info
10614            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10615            pkg.applicationInfo.setCodePath(pkg.codePath);
10616            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10617            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10618            pkg.applicationInfo.setResourcePath(pkg.codePath);
10619            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10620            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10621
10622            return true;
10623        }
10624
10625        private void setMountPath(String mountPath) {
10626            final File mountFile = new File(mountPath);
10627
10628            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
10629            if (monolithicFile.exists()) {
10630                packagePath = monolithicFile.getAbsolutePath();
10631                if (isFwdLocked()) {
10632                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
10633                } else {
10634                    resourcePath = packagePath;
10635                }
10636            } else {
10637                packagePath = mountFile.getAbsolutePath();
10638                resourcePath = packagePath;
10639            }
10640        }
10641
10642        int doPostInstall(int status, int uid) {
10643            if (status != PackageManager.INSTALL_SUCCEEDED) {
10644                cleanUp();
10645            } else {
10646                final int groupOwner;
10647                final String protectedFile;
10648                if (isFwdLocked()) {
10649                    groupOwner = UserHandle.getSharedAppGid(uid);
10650                    protectedFile = RES_FILE_NAME;
10651                } else {
10652                    groupOwner = -1;
10653                    protectedFile = null;
10654                }
10655
10656                if (uid < Process.FIRST_APPLICATION_UID
10657                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
10658                    Slog.e(TAG, "Failed to finalize " + cid);
10659                    PackageHelper.destroySdDir(cid);
10660                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10661                }
10662
10663                boolean mounted = PackageHelper.isContainerMounted(cid);
10664                if (!mounted) {
10665                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
10666                }
10667            }
10668            return status;
10669        }
10670
10671        private void cleanUp() {
10672            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
10673
10674            // Destroy secure container
10675            PackageHelper.destroySdDir(cid);
10676        }
10677
10678        private List<String> getAllCodePaths() {
10679            final File codeFile = new File(getCodePath());
10680            if (codeFile != null && codeFile.exists()) {
10681                try {
10682                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
10683                    return pkg.getAllCodePaths();
10684                } catch (PackageParserException e) {
10685                    // Ignored; we tried our best
10686                }
10687            }
10688            return Collections.EMPTY_LIST;
10689        }
10690
10691        void cleanUpResourcesLI() {
10692            // Enumerate all code paths before deleting
10693            cleanUpResourcesLI(getAllCodePaths());
10694        }
10695
10696        private void cleanUpResourcesLI(List<String> allCodePaths) {
10697            cleanUp();
10698            removeDexFiles(allCodePaths, instructionSets);
10699        }
10700
10701        String getPackageName() {
10702            return getAsecPackageName(cid);
10703        }
10704
10705        boolean doPostDeleteLI(boolean delete) {
10706            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
10707            final List<String> allCodePaths = getAllCodePaths();
10708            boolean mounted = PackageHelper.isContainerMounted(cid);
10709            if (mounted) {
10710                // Unmount first
10711                if (PackageHelper.unMountSdDir(cid)) {
10712                    mounted = false;
10713                }
10714            }
10715            if (!mounted && delete) {
10716                cleanUpResourcesLI(allCodePaths);
10717            }
10718            return !mounted;
10719        }
10720
10721        @Override
10722        int doPreCopy() {
10723            if (isFwdLocked()) {
10724                if (!PackageHelper.fixSdPermissions(cid,
10725                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
10726                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10727                }
10728            }
10729
10730            return PackageManager.INSTALL_SUCCEEDED;
10731        }
10732
10733        @Override
10734        int doPostCopy(int uid) {
10735            if (isFwdLocked()) {
10736                if (uid < Process.FIRST_APPLICATION_UID
10737                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
10738                                RES_FILE_NAME)) {
10739                    Slog.e(TAG, "Failed to finalize " + cid);
10740                    PackageHelper.destroySdDir(cid);
10741                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10742                }
10743            }
10744
10745            return PackageManager.INSTALL_SUCCEEDED;
10746        }
10747    }
10748
10749    /**
10750     * Logic to handle movement of existing installed applications.
10751     */
10752    class MoveInstallArgs extends InstallArgs {
10753        private File codeFile;
10754        private File resourceFile;
10755
10756        /** New install */
10757        MoveInstallArgs(InstallParams params) {
10758            super(params.origin, params.move, params.observer, params.installFlags,
10759                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10760                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10761        }
10762
10763        int copyApk(IMediaContainerService imcs, boolean temp) {
10764            Slog.d(TAG, "Moving " + move.packageName + " from " + move.fromUuid + " to "
10765                    + move.toUuid);
10766            synchronized (mInstaller) {
10767                if (mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
10768                        move.dataAppName, move.appId, move.seinfo) != 0) {
10769                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10770                }
10771            }
10772
10773            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
10774            resourceFile = codeFile;
10775            Slog.d(TAG, "codeFile after move is " + codeFile);
10776
10777            return PackageManager.INSTALL_SUCCEEDED;
10778        }
10779
10780        int doPreInstall(int status) {
10781            if (status != PackageManager.INSTALL_SUCCEEDED) {
10782                cleanUp();
10783            }
10784            return status;
10785        }
10786
10787        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10788            if (status != PackageManager.INSTALL_SUCCEEDED) {
10789                cleanUp();
10790                return false;
10791            }
10792
10793            // Reflect the move in app info
10794            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10795            pkg.applicationInfo.setCodePath(pkg.codePath);
10796            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10797            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10798            pkg.applicationInfo.setResourcePath(pkg.codePath);
10799            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10800            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10801
10802            return true;
10803        }
10804
10805        int doPostInstall(int status, int uid) {
10806            if (status != PackageManager.INSTALL_SUCCEEDED) {
10807                cleanUp();
10808            }
10809            return status;
10810        }
10811
10812        @Override
10813        String getCodePath() {
10814            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
10815        }
10816
10817        @Override
10818        String getResourcePath() {
10819            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
10820        }
10821
10822        private boolean cleanUp() {
10823            if (codeFile == null || !codeFile.exists()) {
10824                return false;
10825            }
10826
10827            if (codeFile.isDirectory()) {
10828                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
10829            } else {
10830                codeFile.delete();
10831            }
10832
10833            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
10834                resourceFile.delete();
10835            }
10836
10837            return true;
10838        }
10839
10840        void cleanUpResourcesLI() {
10841            cleanUp();
10842        }
10843
10844        boolean doPostDeleteLI(boolean delete) {
10845            // XXX err, shouldn't we respect the delete flag?
10846            cleanUpResourcesLI();
10847            return true;
10848        }
10849    }
10850
10851    static String getAsecPackageName(String packageCid) {
10852        int idx = packageCid.lastIndexOf("-");
10853        if (idx == -1) {
10854            return packageCid;
10855        }
10856        return packageCid.substring(0, idx);
10857    }
10858
10859    // Utility method used to create code paths based on package name and available index.
10860    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
10861        String idxStr = "";
10862        int idx = 1;
10863        // Fall back to default value of idx=1 if prefix is not
10864        // part of oldCodePath
10865        if (oldCodePath != null) {
10866            String subStr = oldCodePath;
10867            // Drop the suffix right away
10868            if (suffix != null && subStr.endsWith(suffix)) {
10869                subStr = subStr.substring(0, subStr.length() - suffix.length());
10870            }
10871            // If oldCodePath already contains prefix find out the
10872            // ending index to either increment or decrement.
10873            int sidx = subStr.lastIndexOf(prefix);
10874            if (sidx != -1) {
10875                subStr = subStr.substring(sidx + prefix.length());
10876                if (subStr != null) {
10877                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
10878                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
10879                    }
10880                    try {
10881                        idx = Integer.parseInt(subStr);
10882                        if (idx <= 1) {
10883                            idx++;
10884                        } else {
10885                            idx--;
10886                        }
10887                    } catch(NumberFormatException e) {
10888                    }
10889                }
10890            }
10891        }
10892        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
10893        return prefix + idxStr;
10894    }
10895
10896    private File getNextCodePath(File targetDir, String packageName) {
10897        int suffix = 1;
10898        File result;
10899        do {
10900            result = new File(targetDir, packageName + "-" + suffix);
10901            suffix++;
10902        } while (result.exists());
10903        return result;
10904    }
10905
10906    // Utility method that returns the relative package path with respect
10907    // to the installation directory. Like say for /data/data/com.test-1.apk
10908    // string com.test-1 is returned.
10909    static String deriveCodePathName(String codePath) {
10910        if (codePath == null) {
10911            return null;
10912        }
10913        final File codeFile = new File(codePath);
10914        final String name = codeFile.getName();
10915        if (codeFile.isDirectory()) {
10916            return name;
10917        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
10918            final int lastDot = name.lastIndexOf('.');
10919            return name.substring(0, lastDot);
10920        } else {
10921            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
10922            return null;
10923        }
10924    }
10925
10926    class PackageInstalledInfo {
10927        String name;
10928        int uid;
10929        // The set of users that originally had this package installed.
10930        int[] origUsers;
10931        // The set of users that now have this package installed.
10932        int[] newUsers;
10933        PackageParser.Package pkg;
10934        int returnCode;
10935        String returnMsg;
10936        PackageRemovedInfo removedInfo;
10937
10938        public void setError(int code, String msg) {
10939            returnCode = code;
10940            returnMsg = msg;
10941            Slog.w(TAG, msg);
10942        }
10943
10944        public void setError(String msg, PackageParserException e) {
10945            returnCode = e.error;
10946            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
10947            Slog.w(TAG, msg, e);
10948        }
10949
10950        public void setError(String msg, PackageManagerException e) {
10951            returnCode = e.error;
10952            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
10953            Slog.w(TAG, msg, e);
10954        }
10955
10956        // In some error cases we want to convey more info back to the observer
10957        String origPackage;
10958        String origPermission;
10959    }
10960
10961    /*
10962     * Install a non-existing package.
10963     */
10964    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
10965            UserHandle user, String installerPackageName, String volumeUuid,
10966            PackageInstalledInfo res) {
10967        // Remember this for later, in case we need to rollback this install
10968        String pkgName = pkg.packageName;
10969
10970        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
10971        final boolean dataDirExists = PackageManager.getDataDirForUser(volumeUuid, pkgName,
10972                UserHandle.USER_OWNER).exists();
10973        synchronized(mPackages) {
10974            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
10975                // A package with the same name is already installed, though
10976                // it has been renamed to an older name.  The package we
10977                // are trying to install should be installed as an update to
10978                // the existing one, but that has not been requested, so bail.
10979                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
10980                        + " without first uninstalling package running as "
10981                        + mSettings.mRenamedPackages.get(pkgName));
10982                return;
10983            }
10984            if (mPackages.containsKey(pkgName)) {
10985                // Don't allow installation over an existing package with the same name.
10986                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
10987                        + " without first uninstalling.");
10988                return;
10989            }
10990        }
10991
10992        try {
10993            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
10994                    System.currentTimeMillis(), user);
10995
10996            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
10997            // delete the partially installed application. the data directory will have to be
10998            // restored if it was already existing
10999            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11000                // remove package from internal structures.  Note that we want deletePackageX to
11001                // delete the package data and cache directories that it created in
11002                // scanPackageLocked, unless those directories existed before we even tried to
11003                // install.
11004                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
11005                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
11006                                res.removedInfo, true);
11007            }
11008
11009        } catch (PackageManagerException e) {
11010            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11011        }
11012    }
11013
11014    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
11015        // Upgrade keysets are being used.  Determine if new package has a superset of the
11016        // required keys.
11017        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
11018        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11019        for (int i = 0; i < upgradeKeySets.length; i++) {
11020            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
11021            if (newPkg.mSigningKeys.containsAll(upgradeSet)) {
11022                return true;
11023            }
11024        }
11025        return false;
11026    }
11027
11028    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11029            UserHandle user, String installerPackageName, String volumeUuid,
11030            PackageInstalledInfo res) {
11031        final PackageParser.Package oldPackage;
11032        final String pkgName = pkg.packageName;
11033        final int[] allUsers;
11034        final boolean[] perUserInstalled;
11035        final boolean weFroze;
11036
11037        // First find the old package info and check signatures
11038        synchronized(mPackages) {
11039            oldPackage = mPackages.get(pkgName);
11040            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
11041            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11042            if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
11043                // default to original signature matching
11044                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
11045                    != PackageManager.SIGNATURE_MATCH) {
11046                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11047                            "New package has a different signature: " + pkgName);
11048                    return;
11049                }
11050            } else {
11051                if(!checkUpgradeKeySetLP(ps, pkg)) {
11052                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11053                            "New package not signed by keys specified by upgrade-keysets: "
11054                            + pkgName);
11055                    return;
11056                }
11057            }
11058
11059            // In case of rollback, remember per-user/profile install state
11060            allUsers = sUserManager.getUserIds();
11061            perUserInstalled = new boolean[allUsers.length];
11062            for (int i = 0; i < allUsers.length; i++) {
11063                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11064            }
11065
11066            // Mark the app as frozen to prevent launching during the upgrade
11067            // process, and then kill all running instances
11068            if (!ps.frozen) {
11069                ps.frozen = true;
11070                weFroze = true;
11071            } else {
11072                weFroze = false;
11073            }
11074        }
11075
11076        // Now that we're guarded by frozen state, kill app during upgrade
11077        killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg");
11078
11079        try {
11080            boolean sysPkg = (isSystemApp(oldPackage));
11081            if (sysPkg) {
11082                replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11083                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11084            } else {
11085                replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11086                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11087            }
11088        } finally {
11089            // Regardless of success or failure of upgrade steps above, always
11090            // unfreeze the package if we froze it
11091            if (weFroze) {
11092                unfreezePackage(pkgName);
11093            }
11094        }
11095    }
11096
11097    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
11098            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11099            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11100            String volumeUuid, PackageInstalledInfo res) {
11101        String pkgName = deletedPackage.packageName;
11102        boolean deletedPkg = true;
11103        boolean updatedSettings = false;
11104
11105        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
11106                + deletedPackage);
11107        long origUpdateTime;
11108        if (pkg.mExtras != null) {
11109            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
11110        } else {
11111            origUpdateTime = 0;
11112        }
11113
11114        // First delete the existing package while retaining the data directory
11115        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
11116                res.removedInfo, true)) {
11117            // If the existing package wasn't successfully deleted
11118            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
11119            deletedPkg = false;
11120        } else {
11121            // Successfully deleted the old package; proceed with replace.
11122
11123            // If deleted package lived in a container, give users a chance to
11124            // relinquish resources before killing.
11125            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
11126                if (DEBUG_INSTALL) {
11127                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
11128                }
11129                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
11130                final ArrayList<String> pkgList = new ArrayList<String>(1);
11131                pkgList.add(deletedPackage.applicationInfo.packageName);
11132                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
11133            }
11134
11135            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
11136            try {
11137                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
11138                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
11139                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11140                        perUserInstalled, res, user);
11141                updatedSettings = true;
11142            } catch (PackageManagerException e) {
11143                res.setError("Package couldn't be installed in " + pkg.codePath, e);
11144            }
11145        }
11146
11147        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11148            // remove package from internal structures.  Note that we want deletePackageX to
11149            // delete the package data and cache directories that it created in
11150            // scanPackageLocked, unless those directories existed before we even tried to
11151            // install.
11152            if(updatedSettings) {
11153                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
11154                deletePackageLI(
11155                        pkgName, null, true, allUsers, perUserInstalled,
11156                        PackageManager.DELETE_KEEP_DATA,
11157                                res.removedInfo, true);
11158            }
11159            // Since we failed to install the new package we need to restore the old
11160            // package that we deleted.
11161            if (deletedPkg) {
11162                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
11163                File restoreFile = new File(deletedPackage.codePath);
11164                // Parse old package
11165                boolean oldExternal = isExternal(deletedPackage);
11166                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
11167                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
11168                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11169                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
11170                try {
11171                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
11172                } catch (PackageManagerException e) {
11173                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
11174                            + e.getMessage());
11175                    return;
11176                }
11177                // Restore of old package succeeded. Update permissions.
11178                // writer
11179                synchronized (mPackages) {
11180                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
11181                            UPDATE_PERMISSIONS_ALL);
11182                    // can downgrade to reader
11183                    mSettings.writeLPr();
11184                }
11185                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
11186            }
11187        }
11188    }
11189
11190    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
11191            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11192            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11193            String volumeUuid, PackageInstalledInfo res) {
11194        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
11195                + ", old=" + deletedPackage);
11196        boolean disabledSystem = false;
11197        boolean updatedSettings = false;
11198        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
11199        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
11200                != 0) {
11201            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11202        }
11203        String packageName = deletedPackage.packageName;
11204        if (packageName == null) {
11205            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11206                    "Attempt to delete null packageName.");
11207            return;
11208        }
11209        PackageParser.Package oldPkg;
11210        PackageSetting oldPkgSetting;
11211        // reader
11212        synchronized (mPackages) {
11213            oldPkg = mPackages.get(packageName);
11214            oldPkgSetting = mSettings.mPackages.get(packageName);
11215            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
11216                    (oldPkgSetting == null)) {
11217                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11218                        "Couldn't find package:" + packageName + " information");
11219                return;
11220            }
11221        }
11222
11223        res.removedInfo.uid = oldPkg.applicationInfo.uid;
11224        res.removedInfo.removedPackage = packageName;
11225        // Remove existing system package
11226        removePackageLI(oldPkgSetting, true);
11227        // writer
11228        synchronized (mPackages) {
11229            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
11230            if (!disabledSystem && deletedPackage != null) {
11231                // We didn't need to disable the .apk as a current system package,
11232                // which means we are replacing another update that is already
11233                // installed.  We need to make sure to delete the older one's .apk.
11234                res.removedInfo.args = createInstallArgsForExisting(0,
11235                        deletedPackage.applicationInfo.getCodePath(),
11236                        deletedPackage.applicationInfo.getResourcePath(),
11237                        getAppDexInstructionSets(deletedPackage.applicationInfo));
11238            } else {
11239                res.removedInfo.args = null;
11240            }
11241        }
11242
11243        // Successfully disabled the old package. Now proceed with re-installation
11244        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
11245
11246        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11247        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
11248
11249        PackageParser.Package newPackage = null;
11250        try {
11251            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
11252            if (newPackage.mExtras != null) {
11253                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
11254                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
11255                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
11256
11257                // is the update attempting to change shared user? that isn't going to work...
11258                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
11259                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
11260                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
11261                            + " to " + newPkgSetting.sharedUser);
11262                    updatedSettings = true;
11263                }
11264            }
11265
11266            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11267                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11268                        perUserInstalled, res, user);
11269                updatedSettings = true;
11270            }
11271
11272        } catch (PackageManagerException e) {
11273            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11274        }
11275
11276        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11277            // Re installation failed. Restore old information
11278            // Remove new pkg information
11279            if (newPackage != null) {
11280                removeInstalledPackageLI(newPackage, true);
11281            }
11282            // Add back the old system package
11283            try {
11284                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
11285            } catch (PackageManagerException e) {
11286                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
11287            }
11288            // Restore the old system information in Settings
11289            synchronized (mPackages) {
11290                if (disabledSystem) {
11291                    mSettings.enableSystemPackageLPw(packageName);
11292                }
11293                if (updatedSettings) {
11294                    mSettings.setInstallerPackageName(packageName,
11295                            oldPkgSetting.installerPackageName);
11296                }
11297                mSettings.writeLPr();
11298            }
11299        }
11300    }
11301
11302    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
11303            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
11304            UserHandle user) {
11305        String pkgName = newPackage.packageName;
11306        synchronized (mPackages) {
11307            //write settings. the installStatus will be incomplete at this stage.
11308            //note that the new package setting would have already been
11309            //added to mPackages. It hasn't been persisted yet.
11310            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
11311            mSettings.writeLPr();
11312        }
11313
11314        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
11315
11316        synchronized (mPackages) {
11317            updatePermissionsLPw(newPackage.packageName, newPackage,
11318                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
11319                            ? UPDATE_PERMISSIONS_ALL : 0));
11320            // For system-bundled packages, we assume that installing an upgraded version
11321            // of the package implies that the user actually wants to run that new code,
11322            // so we enable the package.
11323            PackageSetting ps = mSettings.mPackages.get(pkgName);
11324            if (ps != null) {
11325                if (isSystemApp(newPackage)) {
11326                    // NB: implicit assumption that system package upgrades apply to all users
11327                    if (DEBUG_INSTALL) {
11328                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
11329                    }
11330                    if (res.origUsers != null) {
11331                        for (int userHandle : res.origUsers) {
11332                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
11333                                    userHandle, installerPackageName);
11334                        }
11335                    }
11336                    // Also convey the prior install/uninstall state
11337                    if (allUsers != null && perUserInstalled != null) {
11338                        for (int i = 0; i < allUsers.length; i++) {
11339                            if (DEBUG_INSTALL) {
11340                                Slog.d(TAG, "    user " + allUsers[i]
11341                                        + " => " + perUserInstalled[i]);
11342                            }
11343                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
11344                        }
11345                        // these install state changes will be persisted in the
11346                        // upcoming call to mSettings.writeLPr().
11347                    }
11348                }
11349                // It's implied that when a user requests installation, they want the app to be
11350                // installed and enabled.
11351                int userId = user.getIdentifier();
11352                if (userId != UserHandle.USER_ALL) {
11353                    ps.setInstalled(true, userId);
11354                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
11355                }
11356            }
11357            res.name = pkgName;
11358            res.uid = newPackage.applicationInfo.uid;
11359            res.pkg = newPackage;
11360            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
11361            mSettings.setInstallerPackageName(pkgName, installerPackageName);
11362            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11363            //to update install status
11364            mSettings.writeLPr();
11365        }
11366    }
11367
11368    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
11369        final int installFlags = args.installFlags;
11370        final String installerPackageName = args.installerPackageName;
11371        final String volumeUuid = args.volumeUuid;
11372        final File tmpPackageFile = new File(args.getCodePath());
11373        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
11374        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
11375                || (args.volumeUuid != null));
11376        boolean replace = false;
11377        int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE;
11378        // Result object to be returned
11379        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11380
11381        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
11382        // Retrieve PackageSettings and parse package
11383        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
11384                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
11385                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11386        PackageParser pp = new PackageParser();
11387        pp.setSeparateProcesses(mSeparateProcesses);
11388        pp.setDisplayMetrics(mMetrics);
11389
11390        final PackageParser.Package pkg;
11391        try {
11392            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
11393        } catch (PackageParserException e) {
11394            res.setError("Failed parse during installPackageLI", e);
11395            return;
11396        }
11397
11398        // Mark that we have an install time CPU ABI override.
11399        pkg.cpuAbiOverride = args.abiOverride;
11400
11401        String pkgName = res.name = pkg.packageName;
11402        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
11403            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
11404                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
11405                return;
11406            }
11407        }
11408
11409        try {
11410            pp.collectCertificates(pkg, parseFlags);
11411            pp.collectManifestDigest(pkg);
11412        } catch (PackageParserException e) {
11413            res.setError("Failed collect during installPackageLI", e);
11414            return;
11415        }
11416
11417        /* If the installer passed in a manifest digest, compare it now. */
11418        if (args.manifestDigest != null) {
11419            if (DEBUG_INSTALL) {
11420                final String parsedManifest = pkg.manifestDigest == null ? "null"
11421                        : pkg.manifestDigest.toString();
11422                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
11423                        + parsedManifest);
11424            }
11425
11426            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
11427                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
11428                return;
11429            }
11430        } else if (DEBUG_INSTALL) {
11431            final String parsedManifest = pkg.manifestDigest == null
11432                    ? "null" : pkg.manifestDigest.toString();
11433            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
11434        }
11435
11436        // Get rid of all references to package scan path via parser.
11437        pp = null;
11438        String oldCodePath = null;
11439        boolean systemApp = false;
11440        synchronized (mPackages) {
11441            // Check if installing already existing package
11442            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
11443                String oldName = mSettings.mRenamedPackages.get(pkgName);
11444                if (pkg.mOriginalPackages != null
11445                        && pkg.mOriginalPackages.contains(oldName)
11446                        && mPackages.containsKey(oldName)) {
11447                    // This package is derived from an original package,
11448                    // and this device has been updating from that original
11449                    // name.  We must continue using the original name, so
11450                    // rename the new package here.
11451                    pkg.setPackageName(oldName);
11452                    pkgName = pkg.packageName;
11453                    replace = true;
11454                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
11455                            + oldName + " pkgName=" + pkgName);
11456                } else if (mPackages.containsKey(pkgName)) {
11457                    // This package, under its official name, already exists
11458                    // on the device; we should replace it.
11459                    replace = true;
11460                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
11461                }
11462            }
11463
11464            PackageSetting ps = mSettings.mPackages.get(pkgName);
11465            if (ps != null) {
11466                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
11467
11468                // Quick sanity check that we're signed correctly if updating;
11469                // we'll check this again later when scanning, but we want to
11470                // bail early here before tripping over redefined permissions.
11471                if (!ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
11472                    try {
11473                        verifySignaturesLP(ps, pkg);
11474                    } catch (PackageManagerException e) {
11475                        res.setError(e.error, e.getMessage());
11476                        return;
11477                    }
11478                } else {
11479                    if (!checkUpgradeKeySetLP(ps, pkg)) {
11480                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
11481                                + pkg.packageName + " upgrade keys do not match the "
11482                                + "previously installed version");
11483                        return;
11484                    }
11485                }
11486
11487                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
11488                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
11489                    systemApp = (ps.pkg.applicationInfo.flags &
11490                            ApplicationInfo.FLAG_SYSTEM) != 0;
11491                }
11492                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
11493            }
11494
11495            // Check whether the newly-scanned package wants to define an already-defined perm
11496            int N = pkg.permissions.size();
11497            for (int i = N-1; i >= 0; i--) {
11498                PackageParser.Permission perm = pkg.permissions.get(i);
11499                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
11500                if (bp != null) {
11501                    // If the defining package is signed with our cert, it's okay.  This
11502                    // also includes the "updating the same package" case, of course.
11503                    // "updating same package" could also involve key-rotation.
11504                    final boolean sigsOk;
11505                    if (!bp.sourcePackage.equals(pkg.packageName)
11506                            || !(bp.packageSetting instanceof PackageSetting)
11507                            || !bp.packageSetting.keySetData.isUsingUpgradeKeySets()
11508                            || ((PackageSetting) bp.packageSetting).sharedUser != null) {
11509                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
11510                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
11511                    } else {
11512                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
11513                    }
11514                    if (!sigsOk) {
11515                        // If the owning package is the system itself, we log but allow
11516                        // install to proceed; we fail the install on all other permission
11517                        // redefinitions.
11518                        if (!bp.sourcePackage.equals("android")) {
11519                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
11520                                    + pkg.packageName + " attempting to redeclare permission "
11521                                    + perm.info.name + " already owned by " + bp.sourcePackage);
11522                            res.origPermission = perm.info.name;
11523                            res.origPackage = bp.sourcePackage;
11524                            return;
11525                        } else {
11526                            Slog.w(TAG, "Package " + pkg.packageName
11527                                    + " attempting to redeclare system permission "
11528                                    + perm.info.name + "; ignoring new declaration");
11529                            pkg.permissions.remove(i);
11530                        }
11531                    }
11532                }
11533            }
11534
11535        }
11536
11537        if (systemApp && onExternal) {
11538            // Disable updates to system apps on sdcard
11539            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
11540                    "Cannot install updates to system apps on sdcard");
11541            return;
11542        }
11543
11544        if (args.move != null) {
11545            // We did an in-place move, so dex is ready to roll
11546            scanFlags |= SCAN_NO_DEX;
11547        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
11548            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
11549            scanFlags |= SCAN_NO_DEX;
11550            // Run dexopt before old package gets removed, to minimize time when app is unavailable
11551            int result = mPackageDexOptimizer
11552                    .performDexOpt(pkg, null /* instruction sets */, true /* forceDex */,
11553                            false /* defer */, false /* inclDependencies */);
11554            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
11555                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
11556                return;
11557            }
11558        }
11559
11560        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
11561            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
11562            return;
11563        }
11564
11565        startIntentFilterVerifications(args.user.getIdentifier(), pkg);
11566
11567        if (replace) {
11568            replacePackageLI(pkg, parseFlags, scanFlags, args.user,
11569                    installerPackageName, volumeUuid, res);
11570        } else {
11571            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
11572                    args.user, installerPackageName, volumeUuid, res);
11573        }
11574        synchronized (mPackages) {
11575            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11576            if (ps != null) {
11577                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
11578            }
11579        }
11580    }
11581
11582    private void startIntentFilterVerifications(int userId, PackageParser.Package pkg) {
11583        if (mIntentFilterVerifierComponent == null) {
11584            Slog.d(TAG, "No IntentFilter verification will not be done as "
11585                    + "there is no IntentFilterVerifier available!");
11586            return;
11587        }
11588
11589        final int verifierUid = getPackageUid(
11590                mIntentFilterVerifierComponent.getPackageName(),
11591                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
11592
11593        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
11594        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
11595        msg.obj = pkg;
11596        msg.arg1 = userId;
11597        msg.arg2 = verifierUid;
11598
11599        mHandler.sendMessage(msg);
11600    }
11601
11602    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid,
11603            PackageParser.Package pkg) {
11604        int size = pkg.activities.size();
11605        if (size == 0) {
11606            Slog.d(TAG, "No activity, so no need to verify any IntentFilter!");
11607            return;
11608        }
11609
11610        final boolean hasDomainURLs = hasDomainURLs(pkg);
11611        if (!hasDomainURLs) {
11612            Slog.d(TAG, "No domain URLs, so no need to verify any IntentFilter!");
11613            return;
11614        }
11615
11616        Slog.d(TAG, "Checking for userId:" + userId + " if any IntentFilter from the " + size
11617                + " Activities needs verification ...");
11618
11619        final int verificationId = mIntentFilterVerificationToken++;
11620        int count = 0;
11621        final String packageName = pkg.packageName;
11622        ArrayList<String> allHosts = new ArrayList<>();
11623
11624        synchronized (mPackages) {
11625            for (PackageParser.Activity a : pkg.activities) {
11626                for (ActivityIntentInfo filter : a.intents) {
11627                    boolean needsFilterVerification = filter.needsVerification();
11628                    if (needsFilterVerification && needsNetworkVerificationLPr(filter)) {
11629                        Slog.d(TAG, "Verification needed for IntentFilter:" + filter.toString());
11630                        mIntentFilterVerifier.addOneIntentFilterVerification(
11631                                verifierUid, userId, verificationId, filter, packageName);
11632                        count++;
11633                    } else if (!needsFilterVerification) {
11634                        Slog.d(TAG, "No verification needed for IntentFilter:" + filter.toString());
11635                        if (hasValidDomains(filter)) {
11636                            ArrayList<String> hosts = filter.getHostsList();
11637                            if (hosts.size() > 0) {
11638                                allHosts.addAll(hosts);
11639                            } else {
11640                                if (allHosts.isEmpty()) {
11641                                    allHosts.add("*");
11642                                }
11643                            }
11644                        }
11645                    } else {
11646                        Slog.d(TAG, "Verification already done for IntentFilter:"
11647                                + filter.toString());
11648                    }
11649                }
11650            }
11651        }
11652
11653        if (count > 0) {
11654            mIntentFilterVerifier.startVerifications(userId);
11655            Slog.d(TAG, "Started " + count + " IntentFilter verification"
11656                    + (count > 1 ? "s" : "") +  " for userId:" + userId + "!");
11657        } else {
11658            Slog.d(TAG, "No need to start any IntentFilter verification!");
11659            if (allHosts.size() > 0 && mSettings.createIntentFilterVerificationIfNeededLPw(
11660                    packageName, allHosts) != null) {
11661                scheduleWriteSettingsLocked();
11662            }
11663        }
11664    }
11665
11666    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
11667        final ComponentName cn  = filter.activity.getComponentName();
11668        final String packageName = cn.getPackageName();
11669
11670        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
11671                packageName);
11672        if (ivi == null) {
11673            return true;
11674        }
11675        int status = ivi.getStatus();
11676        switch (status) {
11677            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
11678            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
11679                return true;
11680
11681            default:
11682                // Nothing to do
11683                return false;
11684        }
11685    }
11686
11687    private boolean isSystemComponentOrPersistentPrivApp(PackageParser.Package pkg) {
11688        return UserHandle.getAppId(pkg.applicationInfo.uid) < FIRST_APPLICATION_UID
11689                || ((pkg.applicationInfo.privateFlags
11690                        & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0
11691                && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0);
11692    }
11693
11694    private static boolean isMultiArch(PackageSetting ps) {
11695        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
11696    }
11697
11698    private static boolean isMultiArch(ApplicationInfo info) {
11699        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
11700    }
11701
11702    private static boolean isExternal(PackageParser.Package pkg) {
11703        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
11704    }
11705
11706    private static boolean isExternal(PackageSetting ps) {
11707        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
11708    }
11709
11710    private static boolean isExternal(ApplicationInfo info) {
11711        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
11712    }
11713
11714    private static boolean isSystemApp(PackageParser.Package pkg) {
11715        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
11716    }
11717
11718    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
11719        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
11720    }
11721
11722    private static boolean hasDomainURLs(PackageParser.Package pkg) {
11723        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
11724    }
11725
11726    private static boolean isSystemApp(PackageSetting ps) {
11727        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
11728    }
11729
11730    private static boolean isUpdatedSystemApp(PackageSetting ps) {
11731        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
11732    }
11733
11734    private int packageFlagsToInstallFlags(PackageSetting ps) {
11735        int installFlags = 0;
11736        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
11737            // This existing package was an external ASEC install when we have
11738            // the external flag without a UUID
11739            installFlags |= PackageManager.INSTALL_EXTERNAL;
11740        }
11741        if (ps.isForwardLocked()) {
11742            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
11743        }
11744        return installFlags;
11745    }
11746
11747    private void deleteTempPackageFiles() {
11748        final FilenameFilter filter = new FilenameFilter() {
11749            public boolean accept(File dir, String name) {
11750                return name.startsWith("vmdl") && name.endsWith(".tmp");
11751            }
11752        };
11753        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
11754            file.delete();
11755        }
11756    }
11757
11758    @Override
11759    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
11760            int flags) {
11761        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
11762                flags);
11763    }
11764
11765    @Override
11766    public void deletePackage(final String packageName,
11767            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
11768        mContext.enforceCallingOrSelfPermission(
11769                android.Manifest.permission.DELETE_PACKAGES, null);
11770        final int uid = Binder.getCallingUid();
11771        if (UserHandle.getUserId(uid) != userId) {
11772            mContext.enforceCallingPermission(
11773                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
11774                    "deletePackage for user " + userId);
11775        }
11776        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
11777            try {
11778                observer.onPackageDeleted(packageName,
11779                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
11780            } catch (RemoteException re) {
11781            }
11782            return;
11783        }
11784
11785        boolean uninstallBlocked = false;
11786        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
11787            int[] users = sUserManager.getUserIds();
11788            for (int i = 0; i < users.length; ++i) {
11789                if (getBlockUninstallForUser(packageName, users[i])) {
11790                    uninstallBlocked = true;
11791                    break;
11792                }
11793            }
11794        } else {
11795            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
11796        }
11797        if (uninstallBlocked) {
11798            try {
11799                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
11800                        null);
11801            } catch (RemoteException re) {
11802            }
11803            return;
11804        }
11805
11806        if (DEBUG_REMOVE) {
11807            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
11808        }
11809        // Queue up an async operation since the package deletion may take a little while.
11810        mHandler.post(new Runnable() {
11811            public void run() {
11812                mHandler.removeCallbacks(this);
11813                final int returnCode = deletePackageX(packageName, userId, flags);
11814                if (observer != null) {
11815                    try {
11816                        observer.onPackageDeleted(packageName, returnCode, null);
11817                    } catch (RemoteException e) {
11818                        Log.i(TAG, "Observer no longer exists.");
11819                    } //end catch
11820                } //end if
11821            } //end run
11822        });
11823    }
11824
11825    private boolean isPackageDeviceAdmin(String packageName, int userId) {
11826        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
11827                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
11828        try {
11829            if (dpm != null) {
11830                if (dpm.isDeviceOwner(packageName)) {
11831                    return true;
11832                }
11833                int[] users;
11834                if (userId == UserHandle.USER_ALL) {
11835                    users = sUserManager.getUserIds();
11836                } else {
11837                    users = new int[]{userId};
11838                }
11839                for (int i = 0; i < users.length; ++i) {
11840                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
11841                        return true;
11842                    }
11843                }
11844            }
11845        } catch (RemoteException e) {
11846        }
11847        return false;
11848    }
11849
11850    /**
11851     *  This method is an internal method that could be get invoked either
11852     *  to delete an installed package or to clean up a failed installation.
11853     *  After deleting an installed package, a broadcast is sent to notify any
11854     *  listeners that the package has been installed. For cleaning up a failed
11855     *  installation, the broadcast is not necessary since the package's
11856     *  installation wouldn't have sent the initial broadcast either
11857     *  The key steps in deleting a package are
11858     *  deleting the package information in internal structures like mPackages,
11859     *  deleting the packages base directories through installd
11860     *  updating mSettings to reflect current status
11861     *  persisting settings for later use
11862     *  sending a broadcast if necessary
11863     */
11864    private int deletePackageX(String packageName, int userId, int flags) {
11865        final PackageRemovedInfo info = new PackageRemovedInfo();
11866        final boolean res;
11867
11868        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
11869                ? UserHandle.ALL : new UserHandle(userId);
11870
11871        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
11872            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
11873            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
11874        }
11875
11876        boolean removedForAllUsers = false;
11877        boolean systemUpdate = false;
11878
11879        // for the uninstall-updates case and restricted profiles, remember the per-
11880        // userhandle installed state
11881        int[] allUsers;
11882        boolean[] perUserInstalled;
11883        synchronized (mPackages) {
11884            PackageSetting ps = mSettings.mPackages.get(packageName);
11885            allUsers = sUserManager.getUserIds();
11886            perUserInstalled = new boolean[allUsers.length];
11887            for (int i = 0; i < allUsers.length; i++) {
11888                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11889            }
11890        }
11891
11892        synchronized (mInstallLock) {
11893            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
11894            res = deletePackageLI(packageName, removeForUser,
11895                    true, allUsers, perUserInstalled,
11896                    flags | REMOVE_CHATTY, info, true);
11897            systemUpdate = info.isRemovedPackageSystemUpdate;
11898            if (res && !systemUpdate && mPackages.get(packageName) == null) {
11899                removedForAllUsers = true;
11900            }
11901            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
11902                    + " removedForAllUsers=" + removedForAllUsers);
11903        }
11904
11905        if (res) {
11906            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
11907
11908            // If the removed package was a system update, the old system package
11909            // was re-enabled; we need to broadcast this information
11910            if (systemUpdate) {
11911                Bundle extras = new Bundle(1);
11912                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
11913                        ? info.removedAppId : info.uid);
11914                extras.putBoolean(Intent.EXTRA_REPLACING, true);
11915
11916                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
11917                        extras, null, null, null);
11918                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
11919                        extras, null, null, null);
11920                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
11921                        null, packageName, null, null);
11922            }
11923        }
11924        // Force a gc here.
11925        Runtime.getRuntime().gc();
11926        // Delete the resources here after sending the broadcast to let
11927        // other processes clean up before deleting resources.
11928        if (info.args != null) {
11929            synchronized (mInstallLock) {
11930                info.args.doPostDeleteLI(true);
11931            }
11932        }
11933
11934        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
11935    }
11936
11937    class PackageRemovedInfo {
11938        String removedPackage;
11939        int uid = -1;
11940        int removedAppId = -1;
11941        int[] removedUsers = null;
11942        boolean isRemovedPackageSystemUpdate = false;
11943        // Clean up resources deleted packages.
11944        InstallArgs args = null;
11945
11946        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
11947            Bundle extras = new Bundle(1);
11948            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
11949            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
11950            if (replacing) {
11951                extras.putBoolean(Intent.EXTRA_REPLACING, true);
11952            }
11953            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
11954            if (removedPackage != null) {
11955                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
11956                        extras, null, null, removedUsers);
11957                if (fullRemove && !replacing) {
11958                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
11959                            extras, null, null, removedUsers);
11960                }
11961            }
11962            if (removedAppId >= 0) {
11963                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
11964                        removedUsers);
11965            }
11966        }
11967    }
11968
11969    /*
11970     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
11971     * flag is not set, the data directory is removed as well.
11972     * make sure this flag is set for partially installed apps. If not its meaningless to
11973     * delete a partially installed application.
11974     */
11975    private void removePackageDataLI(PackageSetting ps,
11976            int[] allUserHandles, boolean[] perUserInstalled,
11977            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
11978        String packageName = ps.name;
11979        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
11980        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
11981        // Retrieve object to delete permissions for shared user later on
11982        final PackageSetting deletedPs;
11983        // reader
11984        synchronized (mPackages) {
11985            deletedPs = mSettings.mPackages.get(packageName);
11986            if (outInfo != null) {
11987                outInfo.removedPackage = packageName;
11988                outInfo.removedUsers = deletedPs != null
11989                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
11990                        : null;
11991            }
11992        }
11993        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
11994            removeDataDirsLI(ps.volumeUuid, packageName);
11995            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
11996        }
11997        // writer
11998        synchronized (mPackages) {
11999            if (deletedPs != null) {
12000                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12001                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
12002                    clearDefaultBrowserIfNeeded(packageName);
12003                    if (outInfo != null) {
12004                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
12005                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
12006                    }
12007                    updatePermissionsLPw(deletedPs.name, null, 0);
12008                    if (deletedPs.sharedUser != null) {
12009                        // Remove permissions associated with package. Since runtime
12010                        // permissions are per user we have to kill the removed package
12011                        // or packages running under the shared user of the removed
12012                        // package if revoking the permissions requested only by the removed
12013                        // package is successful and this causes a change in gids.
12014                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12015                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
12016                                    userId);
12017                            if (userIdToKill == UserHandle.USER_ALL
12018                                    || userIdToKill >= UserHandle.USER_OWNER) {
12019                                // If gids changed for this user, kill all affected packages.
12020                                mHandler.post(new Runnable() {
12021                                    @Override
12022                                    public void run() {
12023                                        // This has to happen with no lock held.
12024                                        killSettingPackagesForUser(deletedPs, userIdToKill,
12025                                                KILL_APP_REASON_GIDS_CHANGED);
12026                                    }
12027                                });
12028                            break;
12029                            }
12030                        }
12031                    }
12032                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
12033                }
12034                // make sure to preserve per-user disabled state if this removal was just
12035                // a downgrade of a system app to the factory package
12036                if (allUserHandles != null && perUserInstalled != null) {
12037                    if (DEBUG_REMOVE) {
12038                        Slog.d(TAG, "Propagating install state across downgrade");
12039                    }
12040                    for (int i = 0; i < allUserHandles.length; i++) {
12041                        if (DEBUG_REMOVE) {
12042                            Slog.d(TAG, "    user " + allUserHandles[i]
12043                                    + " => " + perUserInstalled[i]);
12044                        }
12045                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12046                    }
12047                }
12048            }
12049            // can downgrade to reader
12050            if (writeSettings) {
12051                // Save settings now
12052                mSettings.writeLPr();
12053            }
12054        }
12055        if (outInfo != null) {
12056            // A user ID was deleted here. Go through all users and remove it
12057            // from KeyStore.
12058            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
12059        }
12060    }
12061
12062    static boolean locationIsPrivileged(File path) {
12063        try {
12064            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
12065                    .getCanonicalPath();
12066            return path.getCanonicalPath().startsWith(privilegedAppDir);
12067        } catch (IOException e) {
12068            Slog.e(TAG, "Unable to access code path " + path);
12069        }
12070        return false;
12071    }
12072
12073    /*
12074     * Tries to delete system package.
12075     */
12076    private boolean deleteSystemPackageLI(PackageSetting newPs,
12077            int[] allUserHandles, boolean[] perUserInstalled,
12078            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
12079        final boolean applyUserRestrictions
12080                = (allUserHandles != null) && (perUserInstalled != null);
12081        PackageSetting disabledPs = null;
12082        // Confirm if the system package has been updated
12083        // An updated system app can be deleted. This will also have to restore
12084        // the system pkg from system partition
12085        // reader
12086        synchronized (mPackages) {
12087            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
12088        }
12089        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
12090                + " disabledPs=" + disabledPs);
12091        if (disabledPs == null) {
12092            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
12093            return false;
12094        } else if (DEBUG_REMOVE) {
12095            Slog.d(TAG, "Deleting system pkg from data partition");
12096        }
12097        if (DEBUG_REMOVE) {
12098            if (applyUserRestrictions) {
12099                Slog.d(TAG, "Remembering install states:");
12100                for (int i = 0; i < allUserHandles.length; i++) {
12101                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
12102                }
12103            }
12104        }
12105        // Delete the updated package
12106        outInfo.isRemovedPackageSystemUpdate = true;
12107        if (disabledPs.versionCode < newPs.versionCode) {
12108            // Delete data for downgrades
12109            flags &= ~PackageManager.DELETE_KEEP_DATA;
12110        } else {
12111            // Preserve data by setting flag
12112            flags |= PackageManager.DELETE_KEEP_DATA;
12113        }
12114        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
12115                allUserHandles, perUserInstalled, outInfo, writeSettings);
12116        if (!ret) {
12117            return false;
12118        }
12119        // writer
12120        synchronized (mPackages) {
12121            // Reinstate the old system package
12122            mSettings.enableSystemPackageLPw(newPs.name);
12123            // Remove any native libraries from the upgraded package.
12124            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
12125        }
12126        // Install the system package
12127        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
12128        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
12129        if (locationIsPrivileged(disabledPs.codePath)) {
12130            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12131        }
12132
12133        final PackageParser.Package newPkg;
12134        try {
12135            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
12136        } catch (PackageManagerException e) {
12137            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
12138            return false;
12139        }
12140
12141        // writer
12142        synchronized (mPackages) {
12143            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
12144            updatePermissionsLPw(newPkg.packageName, newPkg,
12145                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
12146            if (applyUserRestrictions) {
12147                if (DEBUG_REMOVE) {
12148                    Slog.d(TAG, "Propagating install state across reinstall");
12149                }
12150                for (int i = 0; i < allUserHandles.length; i++) {
12151                    if (DEBUG_REMOVE) {
12152                        Slog.d(TAG, "    user " + allUserHandles[i]
12153                                + " => " + perUserInstalled[i]);
12154                    }
12155                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12156                }
12157                // Regardless of writeSettings we need to ensure that this restriction
12158                // state propagation is persisted
12159                mSettings.writeAllUsersPackageRestrictionsLPr();
12160            }
12161            // can downgrade to reader here
12162            if (writeSettings) {
12163                mSettings.writeLPr();
12164            }
12165        }
12166        return true;
12167    }
12168
12169    private boolean deleteInstalledPackageLI(PackageSetting ps,
12170            boolean deleteCodeAndResources, int flags,
12171            int[] allUserHandles, boolean[] perUserInstalled,
12172            PackageRemovedInfo outInfo, boolean writeSettings) {
12173        if (outInfo != null) {
12174            outInfo.uid = ps.appId;
12175        }
12176
12177        // Delete package data from internal structures and also remove data if flag is set
12178        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
12179
12180        // Delete application code and resources
12181        if (deleteCodeAndResources && (outInfo != null)) {
12182            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
12183                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
12184            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
12185        }
12186        return true;
12187    }
12188
12189    @Override
12190    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
12191            int userId) {
12192        mContext.enforceCallingOrSelfPermission(
12193                android.Manifest.permission.DELETE_PACKAGES, null);
12194        synchronized (mPackages) {
12195            PackageSetting ps = mSettings.mPackages.get(packageName);
12196            if (ps == null) {
12197                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
12198                return false;
12199            }
12200            if (!ps.getInstalled(userId)) {
12201                // Can't block uninstall for an app that is not installed or enabled.
12202                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
12203                return false;
12204            }
12205            ps.setBlockUninstall(blockUninstall, userId);
12206            mSettings.writePackageRestrictionsLPr(userId);
12207        }
12208        return true;
12209    }
12210
12211    @Override
12212    public boolean getBlockUninstallForUser(String packageName, int userId) {
12213        synchronized (mPackages) {
12214            PackageSetting ps = mSettings.mPackages.get(packageName);
12215            if (ps == null) {
12216                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
12217                return false;
12218            }
12219            return ps.getBlockUninstall(userId);
12220        }
12221    }
12222
12223    /*
12224     * This method handles package deletion in general
12225     */
12226    private boolean deletePackageLI(String packageName, UserHandle user,
12227            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
12228            int flags, PackageRemovedInfo outInfo,
12229            boolean writeSettings) {
12230        if (packageName == null) {
12231            Slog.w(TAG, "Attempt to delete null packageName.");
12232            return false;
12233        }
12234        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
12235        PackageSetting ps;
12236        boolean dataOnly = false;
12237        int removeUser = -1;
12238        int appId = -1;
12239        synchronized (mPackages) {
12240            ps = mSettings.mPackages.get(packageName);
12241            if (ps == null) {
12242                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12243                return false;
12244            }
12245            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
12246                    && user.getIdentifier() != UserHandle.USER_ALL) {
12247                // The caller is asking that the package only be deleted for a single
12248                // user.  To do this, we just mark its uninstalled state and delete
12249                // its data.  If this is a system app, we only allow this to happen if
12250                // they have set the special DELETE_SYSTEM_APP which requests different
12251                // semantics than normal for uninstalling system apps.
12252                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
12253                ps.setUserState(user.getIdentifier(),
12254                        COMPONENT_ENABLED_STATE_DEFAULT,
12255                        false, //installed
12256                        true,  //stopped
12257                        true,  //notLaunched
12258                        false, //hidden
12259                        null, null, null,
12260                        false, // blockUninstall
12261                        INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
12262                if (!isSystemApp(ps)) {
12263                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
12264                        // Other user still have this package installed, so all
12265                        // we need to do is clear this user's data and save that
12266                        // it is uninstalled.
12267                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
12268                        removeUser = user.getIdentifier();
12269                        appId = ps.appId;
12270                        scheduleWritePackageRestrictionsLocked(removeUser);
12271                    } else {
12272                        // We need to set it back to 'installed' so the uninstall
12273                        // broadcasts will be sent correctly.
12274                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
12275                        ps.setInstalled(true, user.getIdentifier());
12276                    }
12277                } else {
12278                    // This is a system app, so we assume that the
12279                    // other users still have this package installed, so all
12280                    // we need to do is clear this user's data and save that
12281                    // it is uninstalled.
12282                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
12283                    removeUser = user.getIdentifier();
12284                    appId = ps.appId;
12285                    scheduleWritePackageRestrictionsLocked(removeUser);
12286                }
12287            }
12288        }
12289
12290        if (removeUser >= 0) {
12291            // From above, we determined that we are deleting this only
12292            // for a single user.  Continue the work here.
12293            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
12294            if (outInfo != null) {
12295                outInfo.removedPackage = packageName;
12296                outInfo.removedAppId = appId;
12297                outInfo.removedUsers = new int[] {removeUser};
12298            }
12299            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
12300            removeKeystoreDataIfNeeded(removeUser, appId);
12301            schedulePackageCleaning(packageName, removeUser, false);
12302            synchronized (mPackages) {
12303                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
12304                    scheduleWritePackageRestrictionsLocked(removeUser);
12305                }
12306            }
12307            return true;
12308        }
12309
12310        if (dataOnly) {
12311            // Delete application data first
12312            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
12313            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
12314            return true;
12315        }
12316
12317        boolean ret = false;
12318        if (isSystemApp(ps)) {
12319            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
12320            // When an updated system application is deleted we delete the existing resources as well and
12321            // fall back to existing code in system partition
12322            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
12323                    flags, outInfo, writeSettings);
12324        } else {
12325            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
12326            // Kill application pre-emptively especially for apps on sd.
12327            killApplication(packageName, ps.appId, "uninstall pkg");
12328            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
12329                    allUserHandles, perUserInstalled,
12330                    outInfo, writeSettings);
12331        }
12332
12333        return ret;
12334    }
12335
12336    private final class ClearStorageConnection implements ServiceConnection {
12337        IMediaContainerService mContainerService;
12338
12339        @Override
12340        public void onServiceConnected(ComponentName name, IBinder service) {
12341            synchronized (this) {
12342                mContainerService = IMediaContainerService.Stub.asInterface(service);
12343                notifyAll();
12344            }
12345        }
12346
12347        @Override
12348        public void onServiceDisconnected(ComponentName name) {
12349        }
12350    }
12351
12352    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
12353        final boolean mounted;
12354        if (Environment.isExternalStorageEmulated()) {
12355            mounted = true;
12356        } else {
12357            final String status = Environment.getExternalStorageState();
12358
12359            mounted = status.equals(Environment.MEDIA_MOUNTED)
12360                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
12361        }
12362
12363        if (!mounted) {
12364            return;
12365        }
12366
12367        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
12368        int[] users;
12369        if (userId == UserHandle.USER_ALL) {
12370            users = sUserManager.getUserIds();
12371        } else {
12372            users = new int[] { userId };
12373        }
12374        final ClearStorageConnection conn = new ClearStorageConnection();
12375        if (mContext.bindServiceAsUser(
12376                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
12377            try {
12378                for (int curUser : users) {
12379                    long timeout = SystemClock.uptimeMillis() + 5000;
12380                    synchronized (conn) {
12381                        long now = SystemClock.uptimeMillis();
12382                        while (conn.mContainerService == null && now < timeout) {
12383                            try {
12384                                conn.wait(timeout - now);
12385                            } catch (InterruptedException e) {
12386                            }
12387                        }
12388                    }
12389                    if (conn.mContainerService == null) {
12390                        return;
12391                    }
12392
12393                    final UserEnvironment userEnv = new UserEnvironment(curUser);
12394                    clearDirectory(conn.mContainerService,
12395                            userEnv.buildExternalStorageAppCacheDirs(packageName));
12396                    if (allData) {
12397                        clearDirectory(conn.mContainerService,
12398                                userEnv.buildExternalStorageAppDataDirs(packageName));
12399                        clearDirectory(conn.mContainerService,
12400                                userEnv.buildExternalStorageAppMediaDirs(packageName));
12401                    }
12402                }
12403            } finally {
12404                mContext.unbindService(conn);
12405            }
12406        }
12407    }
12408
12409    @Override
12410    public void clearApplicationUserData(final String packageName,
12411            final IPackageDataObserver observer, final int userId) {
12412        mContext.enforceCallingOrSelfPermission(
12413                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
12414        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
12415        // Queue up an async operation since the package deletion may take a little while.
12416        mHandler.post(new Runnable() {
12417            public void run() {
12418                mHandler.removeCallbacks(this);
12419                final boolean succeeded;
12420                synchronized (mInstallLock) {
12421                    succeeded = clearApplicationUserDataLI(packageName, userId);
12422                }
12423                clearExternalStorageDataSync(packageName, userId, true);
12424                if (succeeded) {
12425                    // invoke DeviceStorageMonitor's update method to clear any notifications
12426                    DeviceStorageMonitorInternal
12427                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
12428                    if (dsm != null) {
12429                        dsm.checkMemory();
12430                    }
12431                }
12432                if(observer != null) {
12433                    try {
12434                        observer.onRemoveCompleted(packageName, succeeded);
12435                    } catch (RemoteException e) {
12436                        Log.i(TAG, "Observer no longer exists.");
12437                    }
12438                } //end if observer
12439            } //end run
12440        });
12441    }
12442
12443    private boolean clearApplicationUserDataLI(String packageName, int userId) {
12444        if (packageName == null) {
12445            Slog.w(TAG, "Attempt to delete null packageName.");
12446            return false;
12447        }
12448
12449        // Try finding details about the requested package
12450        PackageParser.Package pkg;
12451        synchronized (mPackages) {
12452            pkg = mPackages.get(packageName);
12453            if (pkg == null) {
12454                final PackageSetting ps = mSettings.mPackages.get(packageName);
12455                if (ps != null) {
12456                    pkg = ps.pkg;
12457                }
12458            }
12459        }
12460
12461        if (pkg == null) {
12462            Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12463        }
12464
12465        // Always delete data directories for package, even if we found no other
12466        // record of app. This helps users recover from UID mismatches without
12467        // resorting to a full data wipe.
12468        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
12469        if (retCode < 0) {
12470            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
12471            return false;
12472        }
12473
12474        if (pkg == null) {
12475            return false;
12476        }
12477
12478        if (pkg != null && pkg.applicationInfo != null) {
12479            final int appId = pkg.applicationInfo.uid;
12480            removeKeystoreDataIfNeeded(userId, appId);
12481        }
12482
12483        // Create a native library symlink only if we have native libraries
12484        // and if the native libraries are 32 bit libraries. We do not provide
12485        // this symlink for 64 bit libraries.
12486        if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null &&
12487                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
12488            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
12489            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
12490                    nativeLibPath, userId) < 0) {
12491                Slog.w(TAG, "Failed linking native library dir");
12492                return false;
12493            }
12494        }
12495
12496        return true;
12497    }
12498
12499    /**
12500     * Remove entries from the keystore daemon. Will only remove it if the
12501     * {@code appId} is valid.
12502     */
12503    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
12504        if (appId < 0) {
12505            return;
12506        }
12507
12508        final KeyStore keyStore = KeyStore.getInstance();
12509        if (keyStore != null) {
12510            if (userId == UserHandle.USER_ALL) {
12511                for (final int individual : sUserManager.getUserIds()) {
12512                    keyStore.clearUid(UserHandle.getUid(individual, appId));
12513                }
12514            } else {
12515                keyStore.clearUid(UserHandle.getUid(userId, appId));
12516            }
12517        } else {
12518            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
12519        }
12520    }
12521
12522    @Override
12523    public void deleteApplicationCacheFiles(final String packageName,
12524            final IPackageDataObserver observer) {
12525        mContext.enforceCallingOrSelfPermission(
12526                android.Manifest.permission.DELETE_CACHE_FILES, null);
12527        // Queue up an async operation since the package deletion may take a little while.
12528        final int userId = UserHandle.getCallingUserId();
12529        mHandler.post(new Runnable() {
12530            public void run() {
12531                mHandler.removeCallbacks(this);
12532                final boolean succeded;
12533                synchronized (mInstallLock) {
12534                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
12535                }
12536                clearExternalStorageDataSync(packageName, userId, false);
12537                if (observer != null) {
12538                    try {
12539                        observer.onRemoveCompleted(packageName, succeded);
12540                    } catch (RemoteException e) {
12541                        Log.i(TAG, "Observer no longer exists.");
12542                    }
12543                } //end if observer
12544            } //end run
12545        });
12546    }
12547
12548    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
12549        if (packageName == null) {
12550            Slog.w(TAG, "Attempt to delete null packageName.");
12551            return false;
12552        }
12553        PackageParser.Package p;
12554        synchronized (mPackages) {
12555            p = mPackages.get(packageName);
12556        }
12557        if (p == null) {
12558            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
12559            return false;
12560        }
12561        final ApplicationInfo applicationInfo = p.applicationInfo;
12562        if (applicationInfo == null) {
12563            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
12564            return false;
12565        }
12566        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
12567        if (retCode < 0) {
12568            Slog.w(TAG, "Couldn't remove cache files for package: "
12569                       + packageName + " u" + userId);
12570            return false;
12571        }
12572        return true;
12573    }
12574
12575    @Override
12576    public void getPackageSizeInfo(final String packageName, int userHandle,
12577            final IPackageStatsObserver observer) {
12578        mContext.enforceCallingOrSelfPermission(
12579                android.Manifest.permission.GET_PACKAGE_SIZE, null);
12580        if (packageName == null) {
12581            throw new IllegalArgumentException("Attempt to get size of null packageName");
12582        }
12583
12584        PackageStats stats = new PackageStats(packageName, userHandle);
12585
12586        /*
12587         * Queue up an async operation since the package measurement may take a
12588         * little while.
12589         */
12590        Message msg = mHandler.obtainMessage(INIT_COPY);
12591        msg.obj = new MeasureParams(stats, observer);
12592        mHandler.sendMessage(msg);
12593    }
12594
12595    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
12596            PackageStats pStats) {
12597        if (packageName == null) {
12598            Slog.w(TAG, "Attempt to get size of null packageName.");
12599            return false;
12600        }
12601        PackageParser.Package p;
12602        boolean dataOnly = false;
12603        String libDirRoot = null;
12604        String asecPath = null;
12605        PackageSetting ps = null;
12606        synchronized (mPackages) {
12607            p = mPackages.get(packageName);
12608            ps = mSettings.mPackages.get(packageName);
12609            if(p == null) {
12610                dataOnly = true;
12611                if((ps == null) || (ps.pkg == null)) {
12612                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
12613                    return false;
12614                }
12615                p = ps.pkg;
12616            }
12617            if (ps != null) {
12618                libDirRoot = ps.legacyNativeLibraryPathString;
12619            }
12620            if (p != null && (isExternal(p) || p.isForwardLocked())) {
12621                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
12622                if (secureContainerId != null) {
12623                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
12624                }
12625            }
12626        }
12627        String publicSrcDir = null;
12628        if(!dataOnly) {
12629            final ApplicationInfo applicationInfo = p.applicationInfo;
12630            if (applicationInfo == null) {
12631                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
12632                return false;
12633            }
12634            if (p.isForwardLocked()) {
12635                publicSrcDir = applicationInfo.getBaseResourcePath();
12636            }
12637        }
12638        // TODO: extend to measure size of split APKs
12639        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
12640        // not just the first level.
12641        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
12642        // just the primary.
12643        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
12644        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath,
12645                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
12646        if (res < 0) {
12647            return false;
12648        }
12649
12650        // Fix-up for forward-locked applications in ASEC containers.
12651        if (!isExternal(p)) {
12652            pStats.codeSize += pStats.externalCodeSize;
12653            pStats.externalCodeSize = 0L;
12654        }
12655
12656        return true;
12657    }
12658
12659
12660    @Override
12661    public void addPackageToPreferred(String packageName) {
12662        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
12663    }
12664
12665    @Override
12666    public void removePackageFromPreferred(String packageName) {
12667        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
12668    }
12669
12670    @Override
12671    public List<PackageInfo> getPreferredPackages(int flags) {
12672        return new ArrayList<PackageInfo>();
12673    }
12674
12675    private int getUidTargetSdkVersionLockedLPr(int uid) {
12676        Object obj = mSettings.getUserIdLPr(uid);
12677        if (obj instanceof SharedUserSetting) {
12678            final SharedUserSetting sus = (SharedUserSetting) obj;
12679            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
12680            final Iterator<PackageSetting> it = sus.packages.iterator();
12681            while (it.hasNext()) {
12682                final PackageSetting ps = it.next();
12683                if (ps.pkg != null) {
12684                    int v = ps.pkg.applicationInfo.targetSdkVersion;
12685                    if (v < vers) vers = v;
12686                }
12687            }
12688            return vers;
12689        } else if (obj instanceof PackageSetting) {
12690            final PackageSetting ps = (PackageSetting) obj;
12691            if (ps.pkg != null) {
12692                return ps.pkg.applicationInfo.targetSdkVersion;
12693            }
12694        }
12695        return Build.VERSION_CODES.CUR_DEVELOPMENT;
12696    }
12697
12698    @Override
12699    public void addPreferredActivity(IntentFilter filter, int match,
12700            ComponentName[] set, ComponentName activity, int userId) {
12701        addPreferredActivityInternal(filter, match, set, activity, true, userId,
12702                "Adding preferred");
12703    }
12704
12705    private void addPreferredActivityInternal(IntentFilter filter, int match,
12706            ComponentName[] set, ComponentName activity, boolean always, int userId,
12707            String opname) {
12708        // writer
12709        int callingUid = Binder.getCallingUid();
12710        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
12711        if (filter.countActions() == 0) {
12712            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
12713            return;
12714        }
12715        synchronized (mPackages) {
12716            if (mContext.checkCallingOrSelfPermission(
12717                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
12718                    != PackageManager.PERMISSION_GRANTED) {
12719                if (getUidTargetSdkVersionLockedLPr(callingUid)
12720                        < Build.VERSION_CODES.FROYO) {
12721                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
12722                            + callingUid);
12723                    return;
12724                }
12725                mContext.enforceCallingOrSelfPermission(
12726                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12727            }
12728
12729            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
12730            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
12731                    + userId + ":");
12732            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12733            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
12734            scheduleWritePackageRestrictionsLocked(userId);
12735        }
12736    }
12737
12738    @Override
12739    public void replacePreferredActivity(IntentFilter filter, int match,
12740            ComponentName[] set, ComponentName activity, int userId) {
12741        if (filter.countActions() != 1) {
12742            throw new IllegalArgumentException(
12743                    "replacePreferredActivity expects filter to have only 1 action.");
12744        }
12745        if (filter.countDataAuthorities() != 0
12746                || filter.countDataPaths() != 0
12747                || filter.countDataSchemes() > 1
12748                || filter.countDataTypes() != 0) {
12749            throw new IllegalArgumentException(
12750                    "replacePreferredActivity expects filter to have no data authorities, " +
12751                    "paths, or types; and at most one scheme.");
12752        }
12753
12754        final int callingUid = Binder.getCallingUid();
12755        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
12756        synchronized (mPackages) {
12757            if (mContext.checkCallingOrSelfPermission(
12758                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
12759                    != PackageManager.PERMISSION_GRANTED) {
12760                if (getUidTargetSdkVersionLockedLPr(callingUid)
12761                        < Build.VERSION_CODES.FROYO) {
12762                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
12763                            + Binder.getCallingUid());
12764                    return;
12765                }
12766                mContext.enforceCallingOrSelfPermission(
12767                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12768            }
12769
12770            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
12771            if (pir != null) {
12772                // Get all of the existing entries that exactly match this filter.
12773                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
12774                if (existing != null && existing.size() == 1) {
12775                    PreferredActivity cur = existing.get(0);
12776                    if (DEBUG_PREFERRED) {
12777                        Slog.i(TAG, "Checking replace of preferred:");
12778                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12779                        if (!cur.mPref.mAlways) {
12780                            Slog.i(TAG, "  -- CUR; not mAlways!");
12781                        } else {
12782                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
12783                            Slog.i(TAG, "  -- CUR: mSet="
12784                                    + Arrays.toString(cur.mPref.mSetComponents));
12785                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
12786                            Slog.i(TAG, "  -- NEW: mMatch="
12787                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
12788                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
12789                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
12790                        }
12791                    }
12792                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
12793                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
12794                            && cur.mPref.sameSet(set)) {
12795                        // Setting the preferred activity to what it happens to be already
12796                        if (DEBUG_PREFERRED) {
12797                            Slog.i(TAG, "Replacing with same preferred activity "
12798                                    + cur.mPref.mShortComponent + " for user "
12799                                    + userId + ":");
12800                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12801                        }
12802                        return;
12803                    }
12804                }
12805
12806                if (existing != null) {
12807                    if (DEBUG_PREFERRED) {
12808                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
12809                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12810                    }
12811                    for (int i = 0; i < existing.size(); i++) {
12812                        PreferredActivity pa = existing.get(i);
12813                        if (DEBUG_PREFERRED) {
12814                            Slog.i(TAG, "Removing existing preferred activity "
12815                                    + pa.mPref.mComponent + ":");
12816                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
12817                        }
12818                        pir.removeFilter(pa);
12819                    }
12820                }
12821            }
12822            addPreferredActivityInternal(filter, match, set, activity, true, userId,
12823                    "Replacing preferred");
12824        }
12825    }
12826
12827    @Override
12828    public void clearPackagePreferredActivities(String packageName) {
12829        final int uid = Binder.getCallingUid();
12830        // writer
12831        synchronized (mPackages) {
12832            PackageParser.Package pkg = mPackages.get(packageName);
12833            if (pkg == null || pkg.applicationInfo.uid != uid) {
12834                if (mContext.checkCallingOrSelfPermission(
12835                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
12836                        != PackageManager.PERMISSION_GRANTED) {
12837                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
12838                            < Build.VERSION_CODES.FROYO) {
12839                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
12840                                + Binder.getCallingUid());
12841                        return;
12842                    }
12843                    mContext.enforceCallingOrSelfPermission(
12844                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12845                }
12846            }
12847
12848            int user = UserHandle.getCallingUserId();
12849            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
12850                scheduleWritePackageRestrictionsLocked(user);
12851            }
12852        }
12853    }
12854
12855    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
12856    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
12857        ArrayList<PreferredActivity> removed = null;
12858        boolean changed = false;
12859        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12860            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
12861            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12862            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
12863                continue;
12864            }
12865            Iterator<PreferredActivity> it = pir.filterIterator();
12866            while (it.hasNext()) {
12867                PreferredActivity pa = it.next();
12868                // Mark entry for removal only if it matches the package name
12869                // and the entry is of type "always".
12870                if (packageName == null ||
12871                        (pa.mPref.mComponent.getPackageName().equals(packageName)
12872                                && pa.mPref.mAlways)) {
12873                    if (removed == null) {
12874                        removed = new ArrayList<PreferredActivity>();
12875                    }
12876                    removed.add(pa);
12877                }
12878            }
12879            if (removed != null) {
12880                for (int j=0; j<removed.size(); j++) {
12881                    PreferredActivity pa = removed.get(j);
12882                    pir.removeFilter(pa);
12883                }
12884                changed = true;
12885            }
12886        }
12887        return changed;
12888    }
12889
12890    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
12891    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
12892        if (userId == UserHandle.USER_ALL) {
12893            if (mSettings.removeIntentFilterVerificationLPw(packageName,
12894                    sUserManager.getUserIds())) {
12895                for (int oneUserId : sUserManager.getUserIds()) {
12896                    scheduleWritePackageRestrictionsLocked(oneUserId);
12897                }
12898            }
12899        } else {
12900            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
12901                scheduleWritePackageRestrictionsLocked(userId);
12902            }
12903        }
12904    }
12905
12906
12907    void clearDefaultBrowserIfNeeded(String packageName) {
12908        for (int oneUserId : sUserManager.getUserIds()) {
12909            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
12910            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
12911            if (packageName.equals(defaultBrowserPackageName)) {
12912                setDefaultBrowserPackageName(null, oneUserId);
12913            }
12914        }
12915    }
12916
12917    @Override
12918    public void resetPreferredActivities(int userId) {
12919        /* TODO: Actually use userId. Why is it being passed in? */
12920        mContext.enforceCallingOrSelfPermission(
12921                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12922        // writer
12923        synchronized (mPackages) {
12924            int user = UserHandle.getCallingUserId();
12925            clearPackagePreferredActivitiesLPw(null, user);
12926            mSettings.readDefaultPreferredAppsLPw(this, user);
12927            scheduleWritePackageRestrictionsLocked(user);
12928        }
12929    }
12930
12931    @Override
12932    public int getPreferredActivities(List<IntentFilter> outFilters,
12933            List<ComponentName> outActivities, String packageName) {
12934
12935        int num = 0;
12936        final int userId = UserHandle.getCallingUserId();
12937        // reader
12938        synchronized (mPackages) {
12939            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
12940            if (pir != null) {
12941                final Iterator<PreferredActivity> it = pir.filterIterator();
12942                while (it.hasNext()) {
12943                    final PreferredActivity pa = it.next();
12944                    if (packageName == null
12945                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
12946                                    && pa.mPref.mAlways)) {
12947                        if (outFilters != null) {
12948                            outFilters.add(new IntentFilter(pa));
12949                        }
12950                        if (outActivities != null) {
12951                            outActivities.add(pa.mPref.mComponent);
12952                        }
12953                    }
12954                }
12955            }
12956        }
12957
12958        return num;
12959    }
12960
12961    @Override
12962    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
12963            int userId) {
12964        int callingUid = Binder.getCallingUid();
12965        if (callingUid != Process.SYSTEM_UID) {
12966            throw new SecurityException(
12967                    "addPersistentPreferredActivity can only be run by the system");
12968        }
12969        if (filter.countActions() == 0) {
12970            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
12971            return;
12972        }
12973        synchronized (mPackages) {
12974            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
12975                    " :");
12976            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12977            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
12978                    new PersistentPreferredActivity(filter, activity));
12979            scheduleWritePackageRestrictionsLocked(userId);
12980        }
12981    }
12982
12983    @Override
12984    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
12985        int callingUid = Binder.getCallingUid();
12986        if (callingUid != Process.SYSTEM_UID) {
12987            throw new SecurityException(
12988                    "clearPackagePersistentPreferredActivities can only be run by the system");
12989        }
12990        ArrayList<PersistentPreferredActivity> removed = null;
12991        boolean changed = false;
12992        synchronized (mPackages) {
12993            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
12994                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
12995                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
12996                        .valueAt(i);
12997                if (userId != thisUserId) {
12998                    continue;
12999                }
13000                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
13001                while (it.hasNext()) {
13002                    PersistentPreferredActivity ppa = it.next();
13003                    // Mark entry for removal only if it matches the package name.
13004                    if (ppa.mComponent.getPackageName().equals(packageName)) {
13005                        if (removed == null) {
13006                            removed = new ArrayList<PersistentPreferredActivity>();
13007                        }
13008                        removed.add(ppa);
13009                    }
13010                }
13011                if (removed != null) {
13012                    for (int j=0; j<removed.size(); j++) {
13013                        PersistentPreferredActivity ppa = removed.get(j);
13014                        ppir.removeFilter(ppa);
13015                    }
13016                    changed = true;
13017                }
13018            }
13019
13020            if (changed) {
13021                scheduleWritePackageRestrictionsLocked(userId);
13022            }
13023        }
13024    }
13025
13026    /**
13027     * Non-Binder method, support for the backup/restore mechanism: write the
13028     * full set of preferred activities in its canonical XML format.  Returns true
13029     * on success; false otherwise.
13030     */
13031    @Override
13032    public byte[] getPreferredActivityBackup(int userId) {
13033        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13034            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
13035        }
13036
13037        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13038        try {
13039            final XmlSerializer serializer = new FastXmlSerializer();
13040            serializer.setOutput(dataStream, "utf-8");
13041            serializer.startDocument(null, true);
13042            serializer.startTag(null, TAG_PREFERRED_BACKUP);
13043
13044            synchronized (mPackages) {
13045                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
13046            }
13047
13048            serializer.endTag(null, TAG_PREFERRED_BACKUP);
13049            serializer.endDocument();
13050            serializer.flush();
13051        } catch (Exception e) {
13052            if (DEBUG_BACKUP) {
13053                Slog.e(TAG, "Unable to write preferred activities for backup", e);
13054            }
13055            return null;
13056        }
13057
13058        return dataStream.toByteArray();
13059    }
13060
13061    @Override
13062    public void restorePreferredActivities(byte[] backup, int userId) {
13063        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13064            throw new SecurityException("Only the system may call restorePreferredActivities()");
13065        }
13066
13067        try {
13068            final XmlPullParser parser = Xml.newPullParser();
13069            parser.setInput(new ByteArrayInputStream(backup), null);
13070
13071            int type;
13072            while ((type = parser.next()) != XmlPullParser.START_TAG
13073                    && type != XmlPullParser.END_DOCUMENT) {
13074            }
13075            if (type != XmlPullParser.START_TAG) {
13076                // oops didn't find a start tag?!
13077                if (DEBUG_BACKUP) {
13078                    Slog.e(TAG, "Didn't find start tag during restore");
13079                }
13080                return;
13081            }
13082
13083            // this is supposed to be TAG_PREFERRED_BACKUP
13084            if (!TAG_PREFERRED_BACKUP.equals(parser.getName())) {
13085                if (DEBUG_BACKUP) {
13086                    Slog.e(TAG, "Found unexpected tag " + parser.getName());
13087                }
13088                return;
13089            }
13090
13091            // skip interfering stuff, then we're aligned with the backing implementation
13092            while ((type = parser.next()) == XmlPullParser.TEXT) { }
13093            synchronized (mPackages) {
13094                mSettings.readPreferredActivitiesLPw(parser, userId);
13095            }
13096        } catch (Exception e) {
13097            if (DEBUG_BACKUP) {
13098                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
13099            }
13100        }
13101    }
13102
13103    @Override
13104    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
13105            int sourceUserId, int targetUserId, int flags) {
13106        mContext.enforceCallingOrSelfPermission(
13107                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
13108        int callingUid = Binder.getCallingUid();
13109        enforceOwnerRights(ownerPackage, callingUid);
13110        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
13111        if (intentFilter.countActions() == 0) {
13112            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
13113            return;
13114        }
13115        synchronized (mPackages) {
13116            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
13117                    ownerPackage, targetUserId, flags);
13118            CrossProfileIntentResolver resolver =
13119                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
13120            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
13121            // We have all those whose filter is equal. Now checking if the rest is equal as well.
13122            if (existing != null) {
13123                int size = existing.size();
13124                for (int i = 0; i < size; i++) {
13125                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
13126                        return;
13127                    }
13128                }
13129            }
13130            resolver.addFilter(newFilter);
13131            scheduleWritePackageRestrictionsLocked(sourceUserId);
13132        }
13133    }
13134
13135    @Override
13136    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
13137        mContext.enforceCallingOrSelfPermission(
13138                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
13139        int callingUid = Binder.getCallingUid();
13140        enforceOwnerRights(ownerPackage, callingUid);
13141        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
13142        synchronized (mPackages) {
13143            CrossProfileIntentResolver resolver =
13144                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
13145            ArraySet<CrossProfileIntentFilter> set =
13146                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
13147            for (CrossProfileIntentFilter filter : set) {
13148                if (filter.getOwnerPackage().equals(ownerPackage)) {
13149                    resolver.removeFilter(filter);
13150                }
13151            }
13152            scheduleWritePackageRestrictionsLocked(sourceUserId);
13153        }
13154    }
13155
13156    // Enforcing that callingUid is owning pkg on userId
13157    private void enforceOwnerRights(String pkg, int callingUid) {
13158        // The system owns everything.
13159        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
13160            return;
13161        }
13162        int callingUserId = UserHandle.getUserId(callingUid);
13163        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
13164        if (pi == null) {
13165            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
13166                    + callingUserId);
13167        }
13168        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
13169            throw new SecurityException("Calling uid " + callingUid
13170                    + " does not own package " + pkg);
13171        }
13172    }
13173
13174    @Override
13175    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
13176        Intent intent = new Intent(Intent.ACTION_MAIN);
13177        intent.addCategory(Intent.CATEGORY_HOME);
13178
13179        final int callingUserId = UserHandle.getCallingUserId();
13180        List<ResolveInfo> list = queryIntentActivities(intent, null,
13181                PackageManager.GET_META_DATA, callingUserId);
13182        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
13183                true, false, false, callingUserId);
13184
13185        allHomeCandidates.clear();
13186        if (list != null) {
13187            for (ResolveInfo ri : list) {
13188                allHomeCandidates.add(ri);
13189            }
13190        }
13191        return (preferred == null || preferred.activityInfo == null)
13192                ? null
13193                : new ComponentName(preferred.activityInfo.packageName,
13194                        preferred.activityInfo.name);
13195    }
13196
13197    @Override
13198    public void setApplicationEnabledSetting(String appPackageName,
13199            int newState, int flags, int userId, String callingPackage) {
13200        if (!sUserManager.exists(userId)) return;
13201        if (callingPackage == null) {
13202            callingPackage = Integer.toString(Binder.getCallingUid());
13203        }
13204        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
13205    }
13206
13207    @Override
13208    public void setComponentEnabledSetting(ComponentName componentName,
13209            int newState, int flags, int userId) {
13210        if (!sUserManager.exists(userId)) return;
13211        setEnabledSetting(componentName.getPackageName(),
13212                componentName.getClassName(), newState, flags, userId, null);
13213    }
13214
13215    private void setEnabledSetting(final String packageName, String className, int newState,
13216            final int flags, int userId, String callingPackage) {
13217        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
13218              || newState == COMPONENT_ENABLED_STATE_ENABLED
13219              || newState == COMPONENT_ENABLED_STATE_DISABLED
13220              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
13221              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
13222            throw new IllegalArgumentException("Invalid new component state: "
13223                    + newState);
13224        }
13225        PackageSetting pkgSetting;
13226        final int uid = Binder.getCallingUid();
13227        final int permission = mContext.checkCallingOrSelfPermission(
13228                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
13229        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
13230        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
13231        boolean sendNow = false;
13232        boolean isApp = (className == null);
13233        String componentName = isApp ? packageName : className;
13234        int packageUid = -1;
13235        ArrayList<String> components;
13236
13237        // writer
13238        synchronized (mPackages) {
13239            pkgSetting = mSettings.mPackages.get(packageName);
13240            if (pkgSetting == null) {
13241                if (className == null) {
13242                    throw new IllegalArgumentException(
13243                            "Unknown package: " + packageName);
13244                }
13245                throw new IllegalArgumentException(
13246                        "Unknown component: " + packageName
13247                        + "/" + className);
13248            }
13249            // Allow root and verify that userId is not being specified by a different user
13250            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
13251                throw new SecurityException(
13252                        "Permission Denial: attempt to change component state from pid="
13253                        + Binder.getCallingPid()
13254                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
13255            }
13256            if (className == null) {
13257                // We're dealing with an application/package level state change
13258                if (pkgSetting.getEnabled(userId) == newState) {
13259                    // Nothing to do
13260                    return;
13261                }
13262                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
13263                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
13264                    // Don't care about who enables an app.
13265                    callingPackage = null;
13266                }
13267                pkgSetting.setEnabled(newState, userId, callingPackage);
13268                // pkgSetting.pkg.mSetEnabled = newState;
13269            } else {
13270                // We're dealing with a component level state change
13271                // First, verify that this is a valid class name.
13272                PackageParser.Package pkg = pkgSetting.pkg;
13273                if (pkg == null || !pkg.hasComponentClassName(className)) {
13274                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
13275                        throw new IllegalArgumentException("Component class " + className
13276                                + " does not exist in " + packageName);
13277                    } else {
13278                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
13279                                + className + " does not exist in " + packageName);
13280                    }
13281                }
13282                switch (newState) {
13283                case COMPONENT_ENABLED_STATE_ENABLED:
13284                    if (!pkgSetting.enableComponentLPw(className, userId)) {
13285                        return;
13286                    }
13287                    break;
13288                case COMPONENT_ENABLED_STATE_DISABLED:
13289                    if (!pkgSetting.disableComponentLPw(className, userId)) {
13290                        return;
13291                    }
13292                    break;
13293                case COMPONENT_ENABLED_STATE_DEFAULT:
13294                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
13295                        return;
13296                    }
13297                    break;
13298                default:
13299                    Slog.e(TAG, "Invalid new component state: " + newState);
13300                    return;
13301                }
13302            }
13303            scheduleWritePackageRestrictionsLocked(userId);
13304            components = mPendingBroadcasts.get(userId, packageName);
13305            final boolean newPackage = components == null;
13306            if (newPackage) {
13307                components = new ArrayList<String>();
13308            }
13309            if (!components.contains(componentName)) {
13310                components.add(componentName);
13311            }
13312            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
13313                sendNow = true;
13314                // Purge entry from pending broadcast list if another one exists already
13315                // since we are sending one right away.
13316                mPendingBroadcasts.remove(userId, packageName);
13317            } else {
13318                if (newPackage) {
13319                    mPendingBroadcasts.put(userId, packageName, components);
13320                }
13321                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
13322                    // Schedule a message
13323                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
13324                }
13325            }
13326        }
13327
13328        long callingId = Binder.clearCallingIdentity();
13329        try {
13330            if (sendNow) {
13331                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
13332                sendPackageChangedBroadcast(packageName,
13333                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
13334            }
13335        } finally {
13336            Binder.restoreCallingIdentity(callingId);
13337        }
13338    }
13339
13340    private void sendPackageChangedBroadcast(String packageName,
13341            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
13342        if (DEBUG_INSTALL)
13343            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
13344                    + componentNames);
13345        Bundle extras = new Bundle(4);
13346        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
13347        String nameList[] = new String[componentNames.size()];
13348        componentNames.toArray(nameList);
13349        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
13350        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
13351        extras.putInt(Intent.EXTRA_UID, packageUid);
13352        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
13353                new int[] {UserHandle.getUserId(packageUid)});
13354    }
13355
13356    @Override
13357    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
13358        if (!sUserManager.exists(userId)) return;
13359        final int uid = Binder.getCallingUid();
13360        final int permission = mContext.checkCallingOrSelfPermission(
13361                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
13362        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
13363        enforceCrossUserPermission(uid, userId, true, true, "stop package");
13364        // writer
13365        synchronized (mPackages) {
13366            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
13367                    allowedByPermission, uid, userId)) {
13368                scheduleWritePackageRestrictionsLocked(userId);
13369            }
13370        }
13371    }
13372
13373    @Override
13374    public String getInstallerPackageName(String packageName) {
13375        // reader
13376        synchronized (mPackages) {
13377            return mSettings.getInstallerPackageNameLPr(packageName);
13378        }
13379    }
13380
13381    @Override
13382    public int getApplicationEnabledSetting(String packageName, int userId) {
13383        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
13384        int uid = Binder.getCallingUid();
13385        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
13386        // reader
13387        synchronized (mPackages) {
13388            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
13389        }
13390    }
13391
13392    @Override
13393    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
13394        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
13395        int uid = Binder.getCallingUid();
13396        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
13397        // reader
13398        synchronized (mPackages) {
13399            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
13400        }
13401    }
13402
13403    @Override
13404    public void enterSafeMode() {
13405        enforceSystemOrRoot("Only the system can request entering safe mode");
13406
13407        if (!mSystemReady) {
13408            mSafeMode = true;
13409        }
13410    }
13411
13412    @Override
13413    public void systemReady() {
13414        mSystemReady = true;
13415
13416        // Read the compatibilty setting when the system is ready.
13417        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
13418                mContext.getContentResolver(),
13419                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
13420        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
13421        if (DEBUG_SETTINGS) {
13422            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
13423        }
13424
13425        synchronized (mPackages) {
13426            // Verify that all of the preferred activity components actually
13427            // exist.  It is possible for applications to be updated and at
13428            // that point remove a previously declared activity component that
13429            // had been set as a preferred activity.  We try to clean this up
13430            // the next time we encounter that preferred activity, but it is
13431            // possible for the user flow to never be able to return to that
13432            // situation so here we do a sanity check to make sure we haven't
13433            // left any junk around.
13434            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
13435            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13436                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13437                removed.clear();
13438                for (PreferredActivity pa : pir.filterSet()) {
13439                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
13440                        removed.add(pa);
13441                    }
13442                }
13443                if (removed.size() > 0) {
13444                    for (int r=0; r<removed.size(); r++) {
13445                        PreferredActivity pa = removed.get(r);
13446                        Slog.w(TAG, "Removing dangling preferred activity: "
13447                                + pa.mPref.mComponent);
13448                        pir.removeFilter(pa);
13449                    }
13450                    mSettings.writePackageRestrictionsLPr(
13451                            mSettings.mPreferredActivities.keyAt(i));
13452                }
13453            }
13454        }
13455        sUserManager.systemReady();
13456
13457        // Kick off any messages waiting for system ready
13458        if (mPostSystemReadyMessages != null) {
13459            for (Message msg : mPostSystemReadyMessages) {
13460                msg.sendToTarget();
13461            }
13462            mPostSystemReadyMessages = null;
13463        }
13464
13465        // Watch for external volumes that come and go over time
13466        final StorageManager storage = mContext.getSystemService(StorageManager.class);
13467        storage.registerListener(mStorageListener);
13468
13469        mInstallerService.systemReady();
13470    }
13471
13472    @Override
13473    public boolean isSafeMode() {
13474        return mSafeMode;
13475    }
13476
13477    @Override
13478    public boolean hasSystemUidErrors() {
13479        return mHasSystemUidErrors;
13480    }
13481
13482    static String arrayToString(int[] array) {
13483        StringBuffer buf = new StringBuffer(128);
13484        buf.append('[');
13485        if (array != null) {
13486            for (int i=0; i<array.length; i++) {
13487                if (i > 0) buf.append(", ");
13488                buf.append(array[i]);
13489            }
13490        }
13491        buf.append(']');
13492        return buf.toString();
13493    }
13494
13495    static class DumpState {
13496        public static final int DUMP_LIBS = 1 << 0;
13497        public static final int DUMP_FEATURES = 1 << 1;
13498        public static final int DUMP_RESOLVERS = 1 << 2;
13499        public static final int DUMP_PERMISSIONS = 1 << 3;
13500        public static final int DUMP_PACKAGES = 1 << 4;
13501        public static final int DUMP_SHARED_USERS = 1 << 5;
13502        public static final int DUMP_MESSAGES = 1 << 6;
13503        public static final int DUMP_PROVIDERS = 1 << 7;
13504        public static final int DUMP_VERIFIERS = 1 << 8;
13505        public static final int DUMP_PREFERRED = 1 << 9;
13506        public static final int DUMP_PREFERRED_XML = 1 << 10;
13507        public static final int DUMP_KEYSETS = 1 << 11;
13508        public static final int DUMP_VERSION = 1 << 12;
13509        public static final int DUMP_INSTALLS = 1 << 13;
13510        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
13511        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
13512
13513        public static final int OPTION_SHOW_FILTERS = 1 << 0;
13514
13515        private int mTypes;
13516
13517        private int mOptions;
13518
13519        private boolean mTitlePrinted;
13520
13521        private SharedUserSetting mSharedUser;
13522
13523        public boolean isDumping(int type) {
13524            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
13525                return true;
13526            }
13527
13528            return (mTypes & type) != 0;
13529        }
13530
13531        public void setDump(int type) {
13532            mTypes |= type;
13533        }
13534
13535        public boolean isOptionEnabled(int option) {
13536            return (mOptions & option) != 0;
13537        }
13538
13539        public void setOptionEnabled(int option) {
13540            mOptions |= option;
13541        }
13542
13543        public boolean onTitlePrinted() {
13544            final boolean printed = mTitlePrinted;
13545            mTitlePrinted = true;
13546            return printed;
13547        }
13548
13549        public boolean getTitlePrinted() {
13550            return mTitlePrinted;
13551        }
13552
13553        public void setTitlePrinted(boolean enabled) {
13554            mTitlePrinted = enabled;
13555        }
13556
13557        public SharedUserSetting getSharedUser() {
13558            return mSharedUser;
13559        }
13560
13561        public void setSharedUser(SharedUserSetting user) {
13562            mSharedUser = user;
13563        }
13564    }
13565
13566    @Override
13567    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
13568        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
13569                != PackageManager.PERMISSION_GRANTED) {
13570            pw.println("Permission Denial: can't dump ActivityManager from from pid="
13571                    + Binder.getCallingPid()
13572                    + ", uid=" + Binder.getCallingUid()
13573                    + " without permission "
13574                    + android.Manifest.permission.DUMP);
13575            return;
13576        }
13577
13578        DumpState dumpState = new DumpState();
13579        boolean fullPreferred = false;
13580        boolean checkin = false;
13581
13582        String packageName = null;
13583
13584        int opti = 0;
13585        while (opti < args.length) {
13586            String opt = args[opti];
13587            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
13588                break;
13589            }
13590            opti++;
13591
13592            if ("-a".equals(opt)) {
13593                // Right now we only know how to print all.
13594            } else if ("-h".equals(opt)) {
13595                pw.println("Package manager dump options:");
13596                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
13597                pw.println("    --checkin: dump for a checkin");
13598                pw.println("    -f: print details of intent filters");
13599                pw.println("    -h: print this help");
13600                pw.println("  cmd may be one of:");
13601                pw.println("    l[ibraries]: list known shared libraries");
13602                pw.println("    f[ibraries]: list device features");
13603                pw.println("    k[eysets]: print known keysets");
13604                pw.println("    r[esolvers]: dump intent resolvers");
13605                pw.println("    perm[issions]: dump permissions");
13606                pw.println("    pref[erred]: print preferred package settings");
13607                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
13608                pw.println("    prov[iders]: dump content providers");
13609                pw.println("    p[ackages]: dump installed packages");
13610                pw.println("    s[hared-users]: dump shared user IDs");
13611                pw.println("    m[essages]: print collected runtime messages");
13612                pw.println("    v[erifiers]: print package verifier info");
13613                pw.println("    version: print database version info");
13614                pw.println("    write: write current settings now");
13615                pw.println("    <package.name>: info about given package");
13616                pw.println("    installs: details about install sessions");
13617                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
13618                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
13619                return;
13620            } else if ("--checkin".equals(opt)) {
13621                checkin = true;
13622            } else if ("-f".equals(opt)) {
13623                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
13624            } else {
13625                pw.println("Unknown argument: " + opt + "; use -h for help");
13626            }
13627        }
13628
13629        // Is the caller requesting to dump a particular piece of data?
13630        if (opti < args.length) {
13631            String cmd = args[opti];
13632            opti++;
13633            // Is this a package name?
13634            if ("android".equals(cmd) || cmd.contains(".")) {
13635                packageName = cmd;
13636                // When dumping a single package, we always dump all of its
13637                // filter information since the amount of data will be reasonable.
13638                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
13639            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
13640                dumpState.setDump(DumpState.DUMP_LIBS);
13641            } else if ("f".equals(cmd) || "features".equals(cmd)) {
13642                dumpState.setDump(DumpState.DUMP_FEATURES);
13643            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
13644                dumpState.setDump(DumpState.DUMP_RESOLVERS);
13645            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
13646                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
13647            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
13648                dumpState.setDump(DumpState.DUMP_PREFERRED);
13649            } else if ("preferred-xml".equals(cmd)) {
13650                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
13651                if (opti < args.length && "--full".equals(args[opti])) {
13652                    fullPreferred = true;
13653                    opti++;
13654                }
13655            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
13656                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
13657            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
13658                dumpState.setDump(DumpState.DUMP_PACKAGES);
13659            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
13660                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
13661            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
13662                dumpState.setDump(DumpState.DUMP_PROVIDERS);
13663            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
13664                dumpState.setDump(DumpState.DUMP_MESSAGES);
13665            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
13666                dumpState.setDump(DumpState.DUMP_VERIFIERS);
13667            } else if ("i".equals(cmd) || "ifv".equals(cmd)
13668                    || "intent-filter-verifiers".equals(cmd)) {
13669                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
13670            } else if ("version".equals(cmd)) {
13671                dumpState.setDump(DumpState.DUMP_VERSION);
13672            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
13673                dumpState.setDump(DumpState.DUMP_KEYSETS);
13674            } else if ("installs".equals(cmd)) {
13675                dumpState.setDump(DumpState.DUMP_INSTALLS);
13676            } else if ("write".equals(cmd)) {
13677                synchronized (mPackages) {
13678                    mSettings.writeLPr();
13679                    pw.println("Settings written.");
13680                    return;
13681                }
13682            }
13683        }
13684
13685        if (checkin) {
13686            pw.println("vers,1");
13687        }
13688
13689        // reader
13690        synchronized (mPackages) {
13691            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
13692                if (!checkin) {
13693                    if (dumpState.onTitlePrinted())
13694                        pw.println();
13695                    pw.println("Database versions:");
13696                    pw.print("  SDK Version:");
13697                    pw.print(" internal=");
13698                    pw.print(mSettings.mInternalSdkPlatform);
13699                    pw.print(" external=");
13700                    pw.println(mSettings.mExternalSdkPlatform);
13701                    pw.print("  DB Version:");
13702                    pw.print(" internal=");
13703                    pw.print(mSettings.mInternalDatabaseVersion);
13704                    pw.print(" external=");
13705                    pw.println(mSettings.mExternalDatabaseVersion);
13706                }
13707            }
13708
13709            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
13710                if (!checkin) {
13711                    if (dumpState.onTitlePrinted())
13712                        pw.println();
13713                    pw.println("Verifiers:");
13714                    pw.print("  Required: ");
13715                    pw.print(mRequiredVerifierPackage);
13716                    pw.print(" (uid=");
13717                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
13718                    pw.println(")");
13719                } else if (mRequiredVerifierPackage != null) {
13720                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
13721                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
13722                }
13723            }
13724
13725            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
13726                    packageName == null) {
13727                if (mIntentFilterVerifierComponent != null) {
13728                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
13729                    if (!checkin) {
13730                        if (dumpState.onTitlePrinted())
13731                            pw.println();
13732                        pw.println("Intent Filter Verifier:");
13733                        pw.print("  Using: ");
13734                        pw.print(verifierPackageName);
13735                        pw.print(" (uid=");
13736                        pw.print(getPackageUid(verifierPackageName, 0));
13737                        pw.println(")");
13738                    } else if (verifierPackageName != null) {
13739                        pw.print("ifv,"); pw.print(verifierPackageName);
13740                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
13741                    }
13742                } else {
13743                    pw.println();
13744                    pw.println("No Intent Filter Verifier available!");
13745                }
13746            }
13747
13748            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
13749                boolean printedHeader = false;
13750                final Iterator<String> it = mSharedLibraries.keySet().iterator();
13751                while (it.hasNext()) {
13752                    String name = it.next();
13753                    SharedLibraryEntry ent = mSharedLibraries.get(name);
13754                    if (!checkin) {
13755                        if (!printedHeader) {
13756                            if (dumpState.onTitlePrinted())
13757                                pw.println();
13758                            pw.println("Libraries:");
13759                            printedHeader = true;
13760                        }
13761                        pw.print("  ");
13762                    } else {
13763                        pw.print("lib,");
13764                    }
13765                    pw.print(name);
13766                    if (!checkin) {
13767                        pw.print(" -> ");
13768                    }
13769                    if (ent.path != null) {
13770                        if (!checkin) {
13771                            pw.print("(jar) ");
13772                            pw.print(ent.path);
13773                        } else {
13774                            pw.print(",jar,");
13775                            pw.print(ent.path);
13776                        }
13777                    } else {
13778                        if (!checkin) {
13779                            pw.print("(apk) ");
13780                            pw.print(ent.apk);
13781                        } else {
13782                            pw.print(",apk,");
13783                            pw.print(ent.apk);
13784                        }
13785                    }
13786                    pw.println();
13787                }
13788            }
13789
13790            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
13791                if (dumpState.onTitlePrinted())
13792                    pw.println();
13793                if (!checkin) {
13794                    pw.println("Features:");
13795                }
13796                Iterator<String> it = mAvailableFeatures.keySet().iterator();
13797                while (it.hasNext()) {
13798                    String name = it.next();
13799                    if (!checkin) {
13800                        pw.print("  ");
13801                    } else {
13802                        pw.print("feat,");
13803                    }
13804                    pw.println(name);
13805                }
13806            }
13807
13808            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
13809                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
13810                        : "Activity Resolver Table:", "  ", packageName,
13811                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
13812                    dumpState.setTitlePrinted(true);
13813                }
13814                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
13815                        : "Receiver Resolver Table:", "  ", packageName,
13816                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
13817                    dumpState.setTitlePrinted(true);
13818                }
13819                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
13820                        : "Service Resolver Table:", "  ", packageName,
13821                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
13822                    dumpState.setTitlePrinted(true);
13823                }
13824                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
13825                        : "Provider Resolver Table:", "  ", packageName,
13826                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
13827                    dumpState.setTitlePrinted(true);
13828                }
13829            }
13830
13831            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
13832                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13833                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13834                    int user = mSettings.mPreferredActivities.keyAt(i);
13835                    if (pir.dump(pw,
13836                            dumpState.getTitlePrinted()
13837                                ? "\nPreferred Activities User " + user + ":"
13838                                : "Preferred Activities User " + user + ":", "  ",
13839                            packageName, true, false)) {
13840                        dumpState.setTitlePrinted(true);
13841                    }
13842                }
13843            }
13844
13845            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
13846                pw.flush();
13847                FileOutputStream fout = new FileOutputStream(fd);
13848                BufferedOutputStream str = new BufferedOutputStream(fout);
13849                XmlSerializer serializer = new FastXmlSerializer();
13850                try {
13851                    serializer.setOutput(str, "utf-8");
13852                    serializer.startDocument(null, true);
13853                    serializer.setFeature(
13854                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
13855                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
13856                    serializer.endDocument();
13857                    serializer.flush();
13858                } catch (IllegalArgumentException e) {
13859                    pw.println("Failed writing: " + e);
13860                } catch (IllegalStateException e) {
13861                    pw.println("Failed writing: " + e);
13862                } catch (IOException e) {
13863                    pw.println("Failed writing: " + e);
13864                }
13865            }
13866
13867            if (!checkin && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)) {
13868                pw.println();
13869                int count = mSettings.mPackages.size();
13870                if (count == 0) {
13871                    pw.println("No domain preferred apps!");
13872                    pw.println();
13873                } else {
13874                    final String prefix = "  ";
13875                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
13876                    if (allPackageSettings.size() == 0) {
13877                        pw.println("No domain preferred apps!");
13878                        pw.println();
13879                    } else {
13880                        pw.println("Domain preferred apps status:");
13881                        pw.println();
13882                        count = 0;
13883                        for (PackageSetting ps : allPackageSettings) {
13884                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
13885                            if (ivi == null || ivi.getPackageName() == null) continue;
13886                            pw.println(prefix + "Package Name: " + ivi.getPackageName());
13887                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
13888                            pw.println(prefix + "Status: " + ivi.getStatusString());
13889                            pw.println();
13890                            count++;
13891                        }
13892                        if (count == 0) {
13893                            pw.println(prefix + "No domain preferred app status!");
13894                            pw.println();
13895                        }
13896                        for (int userId : sUserManager.getUserIds()) {
13897                            pw.println("Domain preferred apps for User " + userId + ":");
13898                            pw.println();
13899                            count = 0;
13900                            for (PackageSetting ps : allPackageSettings) {
13901                                IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
13902                                if (ivi == null || ivi.getPackageName() == null) {
13903                                    continue;
13904                                }
13905                                final int status = ps.getDomainVerificationStatusForUser(userId);
13906                                if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
13907                                    continue;
13908                                }
13909                                pw.println(prefix + "Package Name: " + ivi.getPackageName());
13910                                pw.println(prefix + "Domains: " + ivi.getDomainsString());
13911                                String statusStr = IntentFilterVerificationInfo.
13912                                        getStatusStringFromValue(status);
13913                                pw.println(prefix + "Status: " + statusStr);
13914                                pw.println();
13915                                count++;
13916                            }
13917                            if (count == 0) {
13918                                pw.println(prefix + "No domain preferred apps!");
13919                                pw.println();
13920                            }
13921                        }
13922                    }
13923                }
13924            }
13925
13926            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
13927                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
13928                if (packageName == null) {
13929                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
13930                        if (iperm == 0) {
13931                            if (dumpState.onTitlePrinted())
13932                                pw.println();
13933                            pw.println("AppOp Permissions:");
13934                        }
13935                        pw.print("  AppOp Permission ");
13936                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
13937                        pw.println(":");
13938                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
13939                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
13940                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
13941                        }
13942                    }
13943                }
13944            }
13945
13946            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
13947                boolean printedSomething = false;
13948                for (PackageParser.Provider p : mProviders.mProviders.values()) {
13949                    if (packageName != null && !packageName.equals(p.info.packageName)) {
13950                        continue;
13951                    }
13952                    if (!printedSomething) {
13953                        if (dumpState.onTitlePrinted())
13954                            pw.println();
13955                        pw.println("Registered ContentProviders:");
13956                        printedSomething = true;
13957                    }
13958                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
13959                    pw.print("    "); pw.println(p.toString());
13960                }
13961                printedSomething = false;
13962                for (Map.Entry<String, PackageParser.Provider> entry :
13963                        mProvidersByAuthority.entrySet()) {
13964                    PackageParser.Provider p = entry.getValue();
13965                    if (packageName != null && !packageName.equals(p.info.packageName)) {
13966                        continue;
13967                    }
13968                    if (!printedSomething) {
13969                        if (dumpState.onTitlePrinted())
13970                            pw.println();
13971                        pw.println("ContentProvider Authorities:");
13972                        printedSomething = true;
13973                    }
13974                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
13975                    pw.print("    "); pw.println(p.toString());
13976                    if (p.info != null && p.info.applicationInfo != null) {
13977                        final String appInfo = p.info.applicationInfo.toString();
13978                        pw.print("      applicationInfo="); pw.println(appInfo);
13979                    }
13980                }
13981            }
13982
13983            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
13984                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
13985            }
13986
13987            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
13988                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
13989            }
13990
13991            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
13992                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin);
13993            }
13994
13995            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
13996                // XXX should handle packageName != null by dumping only install data that
13997                // the given package is involved with.
13998                if (dumpState.onTitlePrinted()) pw.println();
13999                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
14000            }
14001
14002            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
14003                if (dumpState.onTitlePrinted()) pw.println();
14004                mSettings.dumpReadMessagesLPr(pw, dumpState);
14005
14006                pw.println();
14007                pw.println("Package warning messages:");
14008                BufferedReader in = null;
14009                String line = null;
14010                try {
14011                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
14012                    while ((line = in.readLine()) != null) {
14013                        if (line.contains("ignored: updated version")) continue;
14014                        pw.println(line);
14015                    }
14016                } catch (IOException ignored) {
14017                } finally {
14018                    IoUtils.closeQuietly(in);
14019                }
14020            }
14021
14022            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
14023                BufferedReader in = null;
14024                String line = null;
14025                try {
14026                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
14027                    while ((line = in.readLine()) != null) {
14028                        if (line.contains("ignored: updated version")) continue;
14029                        pw.print("msg,");
14030                        pw.println(line);
14031                    }
14032                } catch (IOException ignored) {
14033                } finally {
14034                    IoUtils.closeQuietly(in);
14035                }
14036            }
14037        }
14038    }
14039
14040    // ------- apps on sdcard specific code -------
14041    static final boolean DEBUG_SD_INSTALL = false;
14042
14043    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
14044
14045    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
14046
14047    private boolean mMediaMounted = false;
14048
14049    static String getEncryptKey() {
14050        try {
14051            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
14052                    SD_ENCRYPTION_KEYSTORE_NAME);
14053            if (sdEncKey == null) {
14054                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
14055                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
14056                if (sdEncKey == null) {
14057                    Slog.e(TAG, "Failed to create encryption keys");
14058                    return null;
14059                }
14060            }
14061            return sdEncKey;
14062        } catch (NoSuchAlgorithmException nsae) {
14063            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
14064            return null;
14065        } catch (IOException ioe) {
14066            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
14067            return null;
14068        }
14069    }
14070
14071    /*
14072     * Update media status on PackageManager.
14073     */
14074    @Override
14075    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
14076        int callingUid = Binder.getCallingUid();
14077        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
14078            throw new SecurityException("Media status can only be updated by the system");
14079        }
14080        // reader; this apparently protects mMediaMounted, but should probably
14081        // be a different lock in that case.
14082        synchronized (mPackages) {
14083            Log.i(TAG, "Updating external media status from "
14084                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
14085                    + (mediaStatus ? "mounted" : "unmounted"));
14086            if (DEBUG_SD_INSTALL)
14087                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
14088                        + ", mMediaMounted=" + mMediaMounted);
14089            if (mediaStatus == mMediaMounted) {
14090                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
14091                        : 0, -1);
14092                mHandler.sendMessage(msg);
14093                return;
14094            }
14095            mMediaMounted = mediaStatus;
14096        }
14097        // Queue up an async operation since the package installation may take a
14098        // little while.
14099        mHandler.post(new Runnable() {
14100            public void run() {
14101                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
14102            }
14103        });
14104    }
14105
14106    /**
14107     * Called by MountService when the initial ASECs to scan are available.
14108     * Should block until all the ASEC containers are finished being scanned.
14109     */
14110    public void scanAvailableAsecs() {
14111        updateExternalMediaStatusInner(true, false, false);
14112        if (mShouldRestoreconData) {
14113            SELinuxMMAC.setRestoreconDone();
14114            mShouldRestoreconData = false;
14115        }
14116    }
14117
14118    /*
14119     * Collect information of applications on external media, map them against
14120     * existing containers and update information based on current mount status.
14121     * Please note that we always have to report status if reportStatus has been
14122     * set to true especially when unloading packages.
14123     */
14124    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
14125            boolean externalStorage) {
14126        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
14127        int[] uidArr = EmptyArray.INT;
14128
14129        final String[] list = PackageHelper.getSecureContainerList();
14130        if (ArrayUtils.isEmpty(list)) {
14131            Log.i(TAG, "No secure containers found");
14132        } else {
14133            // Process list of secure containers and categorize them
14134            // as active or stale based on their package internal state.
14135
14136            // reader
14137            synchronized (mPackages) {
14138                for (String cid : list) {
14139                    // Leave stages untouched for now; installer service owns them
14140                    if (PackageInstallerService.isStageName(cid)) continue;
14141
14142                    if (DEBUG_SD_INSTALL)
14143                        Log.i(TAG, "Processing container " + cid);
14144                    String pkgName = getAsecPackageName(cid);
14145                    if (pkgName == null) {
14146                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
14147                        continue;
14148                    }
14149                    if (DEBUG_SD_INSTALL)
14150                        Log.i(TAG, "Looking for pkg : " + pkgName);
14151
14152                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
14153                    if (ps == null) {
14154                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
14155                        continue;
14156                    }
14157
14158                    /*
14159                     * Skip packages that are not external if we're unmounting
14160                     * external storage.
14161                     */
14162                    if (externalStorage && !isMounted && !isExternal(ps)) {
14163                        continue;
14164                    }
14165
14166                    final AsecInstallArgs args = new AsecInstallArgs(cid,
14167                            getAppDexInstructionSets(ps), ps.isForwardLocked());
14168                    // The package status is changed only if the code path
14169                    // matches between settings and the container id.
14170                    if (ps.codePathString != null
14171                            && ps.codePathString.startsWith(args.getCodePath())) {
14172                        if (DEBUG_SD_INSTALL) {
14173                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
14174                                    + " at code path: " + ps.codePathString);
14175                        }
14176
14177                        // We do have a valid package installed on sdcard
14178                        processCids.put(args, ps.codePathString);
14179                        final int uid = ps.appId;
14180                        if (uid != -1) {
14181                            uidArr = ArrayUtils.appendInt(uidArr, uid);
14182                        }
14183                    } else {
14184                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
14185                                + ps.codePathString);
14186                    }
14187                }
14188            }
14189
14190            Arrays.sort(uidArr);
14191        }
14192
14193        // Process packages with valid entries.
14194        if (isMounted) {
14195            if (DEBUG_SD_INSTALL)
14196                Log.i(TAG, "Loading packages");
14197            loadMediaPackages(processCids, uidArr);
14198            startCleaningPackages();
14199            mInstallerService.onSecureContainersAvailable();
14200        } else {
14201            if (DEBUG_SD_INSTALL)
14202                Log.i(TAG, "Unloading packages");
14203            unloadMediaPackages(processCids, uidArr, reportStatus);
14204        }
14205    }
14206
14207    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14208            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
14209        final int size = infos.size();
14210        final String[] packageNames = new String[size];
14211        final int[] packageUids = new int[size];
14212        for (int i = 0; i < size; i++) {
14213            final ApplicationInfo info = infos.get(i);
14214            packageNames[i] = info.packageName;
14215            packageUids[i] = info.uid;
14216        }
14217        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
14218                finishedReceiver);
14219    }
14220
14221    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14222            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
14223        sendResourcesChangedBroadcast(mediaStatus, replacing,
14224                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
14225    }
14226
14227    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14228            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
14229        int size = pkgList.length;
14230        if (size > 0) {
14231            // Send broadcasts here
14232            Bundle extras = new Bundle();
14233            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14234            if (uidArr != null) {
14235                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
14236            }
14237            if (replacing) {
14238                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
14239            }
14240            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
14241                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
14242            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
14243        }
14244    }
14245
14246   /*
14247     * Look at potentially valid container ids from processCids If package
14248     * information doesn't match the one on record or package scanning fails,
14249     * the cid is added to list of removeCids. We currently don't delete stale
14250     * containers.
14251     */
14252    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
14253        ArrayList<String> pkgList = new ArrayList<String>();
14254        Set<AsecInstallArgs> keys = processCids.keySet();
14255
14256        for (AsecInstallArgs args : keys) {
14257            String codePath = processCids.get(args);
14258            if (DEBUG_SD_INSTALL)
14259                Log.i(TAG, "Loading container : " + args.cid);
14260            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14261            try {
14262                // Make sure there are no container errors first.
14263                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
14264                    Slog.e(TAG, "Failed to mount cid : " + args.cid
14265                            + " when installing from sdcard");
14266                    continue;
14267                }
14268                // Check code path here.
14269                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
14270                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
14271                            + " does not match one in settings " + codePath);
14272                    continue;
14273                }
14274                // Parse package
14275                int parseFlags = mDefParseFlags;
14276                if (args.isExternalAsec()) {
14277                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
14278                }
14279                if (args.isFwdLocked()) {
14280                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
14281                }
14282
14283                synchronized (mInstallLock) {
14284                    PackageParser.Package pkg = null;
14285                    try {
14286                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
14287                    } catch (PackageManagerException e) {
14288                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
14289                    }
14290                    // Scan the package
14291                    if (pkg != null) {
14292                        /*
14293                         * TODO why is the lock being held? doPostInstall is
14294                         * called in other places without the lock. This needs
14295                         * to be straightened out.
14296                         */
14297                        // writer
14298                        synchronized (mPackages) {
14299                            retCode = PackageManager.INSTALL_SUCCEEDED;
14300                            pkgList.add(pkg.packageName);
14301                            // Post process args
14302                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
14303                                    pkg.applicationInfo.uid);
14304                        }
14305                    } else {
14306                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
14307                    }
14308                }
14309
14310            } finally {
14311                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
14312                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
14313                }
14314            }
14315        }
14316        // writer
14317        synchronized (mPackages) {
14318            // If the platform SDK has changed since the last time we booted,
14319            // we need to re-grant app permission to catch any new ones that
14320            // appear. This is really a hack, and means that apps can in some
14321            // cases get permissions that the user didn't initially explicitly
14322            // allow... it would be nice to have some better way to handle
14323            // this situation.
14324            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
14325            if (regrantPermissions)
14326                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
14327                        + mSdkVersion + "; regranting permissions for external storage");
14328            mSettings.mExternalSdkPlatform = mSdkVersion;
14329
14330            // Make sure group IDs have been assigned, and any permission
14331            // changes in other apps are accounted for
14332            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
14333                    | (regrantPermissions
14334                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
14335                            : 0));
14336
14337            mSettings.updateExternalDatabaseVersion();
14338
14339            // can downgrade to reader
14340            // Persist settings
14341            mSettings.writeLPr();
14342        }
14343        // Send a broadcast to let everyone know we are done processing
14344        if (pkgList.size() > 0) {
14345            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
14346        }
14347    }
14348
14349   /*
14350     * Utility method to unload a list of specified containers
14351     */
14352    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
14353        // Just unmount all valid containers.
14354        for (AsecInstallArgs arg : cidArgs) {
14355            synchronized (mInstallLock) {
14356                arg.doPostDeleteLI(false);
14357           }
14358       }
14359   }
14360
14361    /*
14362     * Unload packages mounted on external media. This involves deleting package
14363     * data from internal structures, sending broadcasts about diabled packages,
14364     * gc'ing to free up references, unmounting all secure containers
14365     * corresponding to packages on external media, and posting a
14366     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
14367     * that we always have to post this message if status has been requested no
14368     * matter what.
14369     */
14370    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
14371            final boolean reportStatus) {
14372        if (DEBUG_SD_INSTALL)
14373            Log.i(TAG, "unloading media packages");
14374        ArrayList<String> pkgList = new ArrayList<String>();
14375        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
14376        final Set<AsecInstallArgs> keys = processCids.keySet();
14377        for (AsecInstallArgs args : keys) {
14378            String pkgName = args.getPackageName();
14379            if (DEBUG_SD_INSTALL)
14380                Log.i(TAG, "Trying to unload pkg : " + pkgName);
14381            // Delete package internally
14382            PackageRemovedInfo outInfo = new PackageRemovedInfo();
14383            synchronized (mInstallLock) {
14384                boolean res = deletePackageLI(pkgName, null, false, null, null,
14385                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
14386                if (res) {
14387                    pkgList.add(pkgName);
14388                } else {
14389                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
14390                    failedList.add(args);
14391                }
14392            }
14393        }
14394
14395        // reader
14396        synchronized (mPackages) {
14397            // We didn't update the settings after removing each package;
14398            // write them now for all packages.
14399            mSettings.writeLPr();
14400        }
14401
14402        // We have to absolutely send UPDATED_MEDIA_STATUS only
14403        // after confirming that all the receivers processed the ordered
14404        // broadcast when packages get disabled, force a gc to clean things up.
14405        // and unload all the containers.
14406        if (pkgList.size() > 0) {
14407            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
14408                    new IIntentReceiver.Stub() {
14409                public void performReceive(Intent intent, int resultCode, String data,
14410                        Bundle extras, boolean ordered, boolean sticky,
14411                        int sendingUser) throws RemoteException {
14412                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
14413                            reportStatus ? 1 : 0, 1, keys);
14414                    mHandler.sendMessage(msg);
14415                }
14416            });
14417        } else {
14418            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
14419                    keys);
14420            mHandler.sendMessage(msg);
14421        }
14422    }
14423
14424    private void loadPrivatePackages(VolumeInfo vol) {
14425        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
14426        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
14427        synchronized (mInstallLock) {
14428        synchronized (mPackages) {
14429            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
14430            for (PackageSetting ps : packages) {
14431                final PackageParser.Package pkg;
14432                try {
14433                    pkg = scanPackageLI(ps.codePath, parseFlags, 0, 0, null);
14434                    loaded.add(pkg.applicationInfo);
14435                } catch (PackageManagerException e) {
14436                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
14437                }
14438            }
14439
14440            // TODO: regrant any permissions that changed based since original install
14441
14442            mSettings.writeLPr();
14443        }
14444        }
14445
14446        Slog.d(TAG, "Loaded packages " + loaded);
14447        sendResourcesChangedBroadcast(true, false, loaded, null);
14448    }
14449
14450    private void unloadPrivatePackages(VolumeInfo vol) {
14451        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
14452        synchronized (mInstallLock) {
14453        synchronized (mPackages) {
14454            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
14455            for (PackageSetting ps : packages) {
14456                if (ps.pkg == null) continue;
14457
14458                final ApplicationInfo info = ps.pkg.applicationInfo;
14459                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
14460                if (deletePackageLI(ps.name, null, false, null, null,
14461                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
14462                    unloaded.add(info);
14463                } else {
14464                    Slog.w(TAG, "Failed to unload " + ps.codePath);
14465                }
14466            }
14467
14468            mSettings.writeLPr();
14469        }
14470        }
14471
14472        Slog.d(TAG, "Unloaded packages " + unloaded);
14473        sendResourcesChangedBroadcast(false, false, unloaded, null);
14474    }
14475
14476    private void unfreezePackage(String packageName) {
14477        synchronized (mPackages) {
14478            final PackageSetting ps = mSettings.mPackages.get(packageName);
14479            if (ps != null) {
14480                ps.frozen = false;
14481            }
14482        }
14483    }
14484
14485    @Override
14486    public int movePackage(final String packageName, final String volumeUuid) {
14487        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
14488
14489        final int moveId = mNextMoveId.getAndIncrement();
14490        try {
14491            movePackageInternal(packageName, volumeUuid, moveId);
14492        } catch (PackageManagerException e) {
14493            Slog.d(TAG, "Failed to move " + packageName, e);
14494            mMoveCallbacks.notifyStatusChanged(moveId,
14495                    PackageManager.MOVE_FAILED_INTERNAL_ERROR);
14496        }
14497        return moveId;
14498    }
14499
14500    private void movePackageInternal(final String packageName, final String volumeUuid,
14501            final int moveId) throws PackageManagerException {
14502        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
14503        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14504        final PackageManager pm = mContext.getPackageManager();
14505
14506        final boolean currentAsec;
14507        final String currentVolumeUuid;
14508        final File codeFile;
14509        final String installerPackageName;
14510        final String packageAbiOverride;
14511        final int appId;
14512        final String seinfo;
14513        final String label;
14514
14515        // reader
14516        synchronized (mPackages) {
14517            final PackageParser.Package pkg = mPackages.get(packageName);
14518            final PackageSetting ps = mSettings.mPackages.get(packageName);
14519            if (pkg == null || ps == null) {
14520                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
14521            }
14522
14523            if (pkg.applicationInfo.isSystemApp()) {
14524                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
14525                        "Cannot move system application");
14526            }
14527
14528            if (Objects.equals(ps.volumeUuid, volumeUuid)) {
14529                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14530                        "Package already moved to " + volumeUuid);
14531            }
14532
14533            final File probe = new File(pkg.codePath);
14534            final File probeOat = new File(probe, "oat");
14535            if (!probe.isDirectory() || !probeOat.isDirectory()) {
14536                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14537                        "Move only supported for modern cluster style installs");
14538            }
14539
14540            if (ps.frozen) {
14541                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
14542                        "Failed to move already frozen package");
14543            }
14544            ps.frozen = true;
14545
14546            currentAsec = pkg.applicationInfo.isForwardLocked()
14547                    || pkg.applicationInfo.isExternalAsec();
14548            currentVolumeUuid = ps.volumeUuid;
14549            codeFile = new File(pkg.codePath);
14550            installerPackageName = ps.installerPackageName;
14551            packageAbiOverride = ps.cpuAbiOverrideString;
14552            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
14553            seinfo = pkg.applicationInfo.seinfo;
14554            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
14555        }
14556
14557        // Now that we're guarded by frozen state, kill app during move
14558        killApplication(packageName, appId, "move pkg");
14559
14560        final Bundle extras = new Bundle();
14561        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
14562        extras.putString(Intent.EXTRA_TITLE, label);
14563        mMoveCallbacks.notifyCreated(moveId, extras);
14564
14565        int installFlags;
14566        final boolean moveCompleteApp;
14567        final File measurePath;
14568
14569        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
14570            installFlags = INSTALL_INTERNAL;
14571            moveCompleteApp = !currentAsec;
14572            measurePath = Environment.getDataAppDirectory(volumeUuid);
14573        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
14574            installFlags = INSTALL_EXTERNAL;
14575            moveCompleteApp = false;
14576            measurePath = storage.getPrimaryPhysicalVolume().getPath();
14577        } else {
14578            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
14579            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
14580                    || !volume.isMountedWritable()) {
14581                unfreezePackage(packageName);
14582                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14583                        "Move location not mounted private volume");
14584            }
14585
14586            Preconditions.checkState(!currentAsec);
14587
14588            installFlags = INSTALL_INTERNAL;
14589            moveCompleteApp = true;
14590            measurePath = Environment.getDataAppDirectory(volumeUuid);
14591        }
14592
14593        final PackageStats stats = new PackageStats(null, -1);
14594        synchronized (mInstaller) {
14595            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
14596                unfreezePackage(packageName);
14597                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14598                        "Failed to measure package size");
14599            }
14600        }
14601
14602        Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " + stats.dataSize);
14603
14604        final long startFreeBytes = measurePath.getFreeSpace();
14605        final long sizeBytes;
14606        if (moveCompleteApp) {
14607            sizeBytes = stats.codeSize + stats.dataSize;
14608        } else {
14609            sizeBytes = stats.codeSize;
14610        }
14611
14612        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
14613            unfreezePackage(packageName);
14614            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14615                    "Not enough free space to move");
14616        }
14617
14618        mMoveCallbacks.notifyStatusChanged(moveId, 10);
14619
14620        final CountDownLatch installedLatch = new CountDownLatch(1);
14621        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
14622            @Override
14623            public void onUserActionRequired(Intent intent) throws RemoteException {
14624                throw new IllegalStateException();
14625            }
14626
14627            @Override
14628            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
14629                    Bundle extras) throws RemoteException {
14630                Slog.d(TAG, "Install result for move: "
14631                        + PackageManager.installStatusToString(returnCode, msg));
14632
14633                installedLatch.countDown();
14634
14635                // Regardless of success or failure of the move operation,
14636                // always unfreeze the package
14637                unfreezePackage(packageName);
14638
14639                final int status = PackageManager.installStatusToPublicStatus(returnCode);
14640                switch (status) {
14641                    case PackageInstaller.STATUS_SUCCESS:
14642                        mMoveCallbacks.notifyStatusChanged(moveId,
14643                                PackageManager.MOVE_SUCCEEDED);
14644                        break;
14645                    case PackageInstaller.STATUS_FAILURE_STORAGE:
14646                        mMoveCallbacks.notifyStatusChanged(moveId,
14647                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
14648                        break;
14649                    default:
14650                        mMoveCallbacks.notifyStatusChanged(moveId,
14651                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
14652                        break;
14653                }
14654            }
14655        };
14656
14657        final MoveInfo move;
14658        if (moveCompleteApp) {
14659            // Kick off a thread to report progress estimates
14660            new Thread() {
14661                @Override
14662                public void run() {
14663                    while (true) {
14664                        try {
14665                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
14666                                break;
14667                            }
14668                        } catch (InterruptedException ignored) {
14669                        }
14670
14671                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
14672                        final int progress = 10 + (int) MathUtils.constrain(
14673                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
14674                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
14675                    }
14676                }
14677            }.start();
14678
14679            final String dataAppName = codeFile.getName();
14680            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
14681                    dataAppName, appId, seinfo);
14682        } else {
14683            move = null;
14684        }
14685
14686        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
14687
14688        final Message msg = mHandler.obtainMessage(INIT_COPY);
14689        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
14690        msg.obj = new InstallParams(origin, move, installObserver, installFlags,
14691                installerPackageName, volumeUuid, null, user, packageAbiOverride);
14692        mHandler.sendMessage(msg);
14693    }
14694
14695    @Override
14696    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
14697        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
14698
14699        final int realMoveId = mNextMoveId.getAndIncrement();
14700        final Bundle extras = new Bundle();
14701        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
14702        mMoveCallbacks.notifyCreated(realMoveId, extras);
14703
14704        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
14705            @Override
14706            public void onCreated(int moveId, Bundle extras) {
14707                // Ignored
14708            }
14709
14710            @Override
14711            public void onStatusChanged(int moveId, int status, long estMillis) {
14712                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
14713            }
14714        };
14715
14716        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14717        storage.setPrimaryStorageUuid(volumeUuid, callback);
14718        return realMoveId;
14719    }
14720
14721    @Override
14722    public int getMoveStatus(int moveId) {
14723        mContext.enforceCallingOrSelfPermission(
14724                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
14725        return mMoveCallbacks.mLastStatus.get(moveId);
14726    }
14727
14728    @Override
14729    public void registerMoveCallback(IPackageMoveObserver callback) {
14730        mContext.enforceCallingOrSelfPermission(
14731                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
14732        mMoveCallbacks.register(callback);
14733    }
14734
14735    @Override
14736    public void unregisterMoveCallback(IPackageMoveObserver callback) {
14737        mContext.enforceCallingOrSelfPermission(
14738                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
14739        mMoveCallbacks.unregister(callback);
14740    }
14741
14742    @Override
14743    public boolean setInstallLocation(int loc) {
14744        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
14745                null);
14746        if (getInstallLocation() == loc) {
14747            return true;
14748        }
14749        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
14750                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
14751            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
14752                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
14753            return true;
14754        }
14755        return false;
14756   }
14757
14758    @Override
14759    public int getInstallLocation() {
14760        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14761                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
14762                PackageHelper.APP_INSTALL_AUTO);
14763    }
14764
14765    /** Called by UserManagerService */
14766    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
14767        mDirtyUsers.remove(userHandle);
14768        mSettings.removeUserLPw(userHandle);
14769        mPendingBroadcasts.remove(userHandle);
14770        if (mInstaller != null) {
14771            // Technically, we shouldn't be doing this with the package lock
14772            // held.  However, this is very rare, and there is already so much
14773            // other disk I/O going on, that we'll let it slide for now.
14774            final StorageManager storage = StorageManager.from(mContext);
14775            final List<VolumeInfo> vols = storage.getVolumes();
14776            for (VolumeInfo vol : vols) {
14777                if (vol.getType() == VolumeInfo.TYPE_PRIVATE && vol.isMountedWritable()) {
14778                    final String volumeUuid = vol.getFsUuid();
14779                    Slog.d(TAG, "Removing user data on volume " + volumeUuid);
14780                    mInstaller.removeUserDataDirs(volumeUuid, userHandle);
14781                }
14782            }
14783        }
14784        mUserNeedsBadging.delete(userHandle);
14785        removeUnusedPackagesLILPw(userManager, userHandle);
14786    }
14787
14788    /**
14789     * We're removing userHandle and would like to remove any downloaded packages
14790     * that are no longer in use by any other user.
14791     * @param userHandle the user being removed
14792     */
14793    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
14794        final boolean DEBUG_CLEAN_APKS = false;
14795        int [] users = userManager.getUserIdsLPr();
14796        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
14797        while (psit.hasNext()) {
14798            PackageSetting ps = psit.next();
14799            if (ps.pkg == null) {
14800                continue;
14801            }
14802            final String packageName = ps.pkg.packageName;
14803            // Skip over if system app
14804            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
14805                continue;
14806            }
14807            if (DEBUG_CLEAN_APKS) {
14808                Slog.i(TAG, "Checking package " + packageName);
14809            }
14810            boolean keep = false;
14811            for (int i = 0; i < users.length; i++) {
14812                if (users[i] != userHandle && ps.getInstalled(users[i])) {
14813                    keep = true;
14814                    if (DEBUG_CLEAN_APKS) {
14815                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
14816                                + users[i]);
14817                    }
14818                    break;
14819                }
14820            }
14821            if (!keep) {
14822                if (DEBUG_CLEAN_APKS) {
14823                    Slog.i(TAG, "  Removing package " + packageName);
14824                }
14825                mHandler.post(new Runnable() {
14826                    public void run() {
14827                        deletePackageX(packageName, userHandle, 0);
14828                    } //end run
14829                });
14830            }
14831        }
14832    }
14833
14834    /** Called by UserManagerService */
14835    void createNewUserLILPw(int userHandle, File path) {
14836        if (mInstaller != null) {
14837            mInstaller.createUserConfig(userHandle);
14838            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
14839        }
14840    }
14841
14842    void newUserCreatedLILPw(int userHandle) {
14843        // Adding a user requires updating runtime permissions for system apps.
14844        updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
14845    }
14846
14847    @Override
14848    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
14849        mContext.enforceCallingOrSelfPermission(
14850                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14851                "Only package verification agents can read the verifier device identity");
14852
14853        synchronized (mPackages) {
14854            return mSettings.getVerifierDeviceIdentityLPw();
14855        }
14856    }
14857
14858    @Override
14859    public void setPermissionEnforced(String permission, boolean enforced) {
14860        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
14861        if (READ_EXTERNAL_STORAGE.equals(permission)) {
14862            synchronized (mPackages) {
14863                if (mSettings.mReadExternalStorageEnforced == null
14864                        || mSettings.mReadExternalStorageEnforced != enforced) {
14865                    mSettings.mReadExternalStorageEnforced = enforced;
14866                    mSettings.writeLPr();
14867                }
14868            }
14869            // kill any non-foreground processes so we restart them and
14870            // grant/revoke the GID.
14871            final IActivityManager am = ActivityManagerNative.getDefault();
14872            if (am != null) {
14873                final long token = Binder.clearCallingIdentity();
14874                try {
14875                    am.killProcessesBelowForeground("setPermissionEnforcement");
14876                } catch (RemoteException e) {
14877                } finally {
14878                    Binder.restoreCallingIdentity(token);
14879                }
14880            }
14881        } else {
14882            throw new IllegalArgumentException("No selective enforcement for " + permission);
14883        }
14884    }
14885
14886    @Override
14887    @Deprecated
14888    public boolean isPermissionEnforced(String permission) {
14889        return true;
14890    }
14891
14892    @Override
14893    public boolean isStorageLow() {
14894        final long token = Binder.clearCallingIdentity();
14895        try {
14896            final DeviceStorageMonitorInternal
14897                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
14898            if (dsm != null) {
14899                return dsm.isMemoryLow();
14900            } else {
14901                return false;
14902            }
14903        } finally {
14904            Binder.restoreCallingIdentity(token);
14905        }
14906    }
14907
14908    @Override
14909    public IPackageInstaller getPackageInstaller() {
14910        return mInstallerService;
14911    }
14912
14913    private boolean userNeedsBadging(int userId) {
14914        int index = mUserNeedsBadging.indexOfKey(userId);
14915        if (index < 0) {
14916            final UserInfo userInfo;
14917            final long token = Binder.clearCallingIdentity();
14918            try {
14919                userInfo = sUserManager.getUserInfo(userId);
14920            } finally {
14921                Binder.restoreCallingIdentity(token);
14922            }
14923            final boolean b;
14924            if (userInfo != null && userInfo.isManagedProfile()) {
14925                b = true;
14926            } else {
14927                b = false;
14928            }
14929            mUserNeedsBadging.put(userId, b);
14930            return b;
14931        }
14932        return mUserNeedsBadging.valueAt(index);
14933    }
14934
14935    @Override
14936    public KeySet getKeySetByAlias(String packageName, String alias) {
14937        if (packageName == null || alias == null) {
14938            return null;
14939        }
14940        synchronized(mPackages) {
14941            final PackageParser.Package pkg = mPackages.get(packageName);
14942            if (pkg == null) {
14943                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
14944                throw new IllegalArgumentException("Unknown package: " + packageName);
14945            }
14946            KeySetManagerService ksms = mSettings.mKeySetManagerService;
14947            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
14948        }
14949    }
14950
14951    @Override
14952    public KeySet getSigningKeySet(String packageName) {
14953        if (packageName == null) {
14954            return null;
14955        }
14956        synchronized(mPackages) {
14957            final PackageParser.Package pkg = mPackages.get(packageName);
14958            if (pkg == null) {
14959                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
14960                throw new IllegalArgumentException("Unknown package: " + packageName);
14961            }
14962            if (pkg.applicationInfo.uid != Binder.getCallingUid()
14963                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
14964                throw new SecurityException("May not access signing KeySet of other apps.");
14965            }
14966            KeySetManagerService ksms = mSettings.mKeySetManagerService;
14967            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
14968        }
14969    }
14970
14971    @Override
14972    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
14973        if (packageName == null || ks == null) {
14974            return false;
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            IBinder ksh = ks.getToken();
14983            if (ksh instanceof KeySetHandle) {
14984                KeySetManagerService ksms = mSettings.mKeySetManagerService;
14985                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
14986            }
14987            return false;
14988        }
14989    }
14990
14991    @Override
14992    public boolean isPackageSignedByKeySetExactly(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.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
15006            }
15007            return false;
15008        }
15009    }
15010
15011    public void getUsageStatsIfNoPackageUsageInfo() {
15012        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
15013            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
15014            if (usm == null) {
15015                throw new IllegalStateException("UsageStatsManager must be initialized");
15016            }
15017            long now = System.currentTimeMillis();
15018            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
15019            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
15020                String packageName = entry.getKey();
15021                PackageParser.Package pkg = mPackages.get(packageName);
15022                if (pkg == null) {
15023                    continue;
15024                }
15025                UsageStats usage = entry.getValue();
15026                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
15027                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
15028            }
15029        }
15030    }
15031
15032    /**
15033     * Check and throw if the given before/after packages would be considered a
15034     * downgrade.
15035     */
15036    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
15037            throws PackageManagerException {
15038        if (after.versionCode < before.mVersionCode) {
15039            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15040                    "Update version code " + after.versionCode + " is older than current "
15041                    + before.mVersionCode);
15042        } else if (after.versionCode == before.mVersionCode) {
15043            if (after.baseRevisionCode < before.baseRevisionCode) {
15044                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15045                        "Update base revision code " + after.baseRevisionCode
15046                        + " is older than current " + before.baseRevisionCode);
15047            }
15048
15049            if (!ArrayUtils.isEmpty(after.splitNames)) {
15050                for (int i = 0; i < after.splitNames.length; i++) {
15051                    final String splitName = after.splitNames[i];
15052                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
15053                    if (j != -1) {
15054                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
15055                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15056                                    "Update split " + splitName + " revision code "
15057                                    + after.splitRevisionCodes[i] + " is older than current "
15058                                    + before.splitRevisionCodes[j]);
15059                        }
15060                    }
15061                }
15062            }
15063        }
15064    }
15065
15066    private static class MoveCallbacks extends Handler {
15067        private static final int MSG_CREATED = 1;
15068        private static final int MSG_STATUS_CHANGED = 2;
15069
15070        private final RemoteCallbackList<IPackageMoveObserver>
15071                mCallbacks = new RemoteCallbackList<>();
15072
15073        private final SparseIntArray mLastStatus = new SparseIntArray();
15074
15075        public MoveCallbacks(Looper looper) {
15076            super(looper);
15077        }
15078
15079        public void register(IPackageMoveObserver callback) {
15080            mCallbacks.register(callback);
15081        }
15082
15083        public void unregister(IPackageMoveObserver callback) {
15084            mCallbacks.unregister(callback);
15085        }
15086
15087        @Override
15088        public void handleMessage(Message msg) {
15089            final SomeArgs args = (SomeArgs) msg.obj;
15090            final int n = mCallbacks.beginBroadcast();
15091            for (int i = 0; i < n; i++) {
15092                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
15093                try {
15094                    invokeCallback(callback, msg.what, args);
15095                } catch (RemoteException ignored) {
15096                }
15097            }
15098            mCallbacks.finishBroadcast();
15099            args.recycle();
15100        }
15101
15102        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
15103                throws RemoteException {
15104            switch (what) {
15105                case MSG_CREATED: {
15106                    callback.onCreated(args.argi1, (Bundle) args.arg2);
15107                    break;
15108                }
15109                case MSG_STATUS_CHANGED: {
15110                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
15111                    break;
15112                }
15113            }
15114        }
15115
15116        private void notifyCreated(int moveId, Bundle extras) {
15117            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
15118
15119            final SomeArgs args = SomeArgs.obtain();
15120            args.argi1 = moveId;
15121            args.arg2 = extras;
15122            obtainMessage(MSG_CREATED, args).sendToTarget();
15123        }
15124
15125        private void notifyStatusChanged(int moveId, int status) {
15126            notifyStatusChanged(moveId, status, -1);
15127        }
15128
15129        private void notifyStatusChanged(int moveId, int status, long estMillis) {
15130            Slog.v(TAG, "Move " + moveId + " status " + status);
15131
15132            final SomeArgs args = SomeArgs.obtain();
15133            args.argi1 = moveId;
15134            args.argi2 = status;
15135            args.arg3 = estMillis;
15136            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
15137
15138            synchronized (mLastStatus) {
15139                mLastStatus.put(moveId, status);
15140            }
15141        }
15142    }
15143}
15144