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