PackageManagerService.java revision de15edaa9bf486a4050bb067317d313fd807bb10
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.GRANT_REVOKE_PERMISSIONS;
20import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
21import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
27import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
28import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
29import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
30import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT;
31import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
32import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
33import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
34import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
35import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
36import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
37import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
38import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
39import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
40import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
41import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
42import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED;
43import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
44import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
45import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
46import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
47import static android.content.pm.PackageManager.INSTALL_INTERNAL;
48import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
49import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
50import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
51import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
52import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
53import static android.content.pm.PackageManager.MATCH_ALL;
54import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
55import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
56import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
57import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
58import static android.content.pm.PackageManager.PERMISSION_GRANTED;
59import static android.content.pm.PackageParser.isApkFile;
60import static android.os.Process.PACKAGE_INFO_GID;
61import static android.os.Process.SYSTEM_UID;
62import static android.system.OsConstants.O_CREAT;
63import static android.system.OsConstants.O_RDWR;
64import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
65import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER;
66import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
67import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
68import static com.android.internal.util.ArrayUtils.appendInt;
69import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
70import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
71import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
72import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
73import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
74
75import android.Manifest;
76import android.app.ActivityManager;
77import android.app.ActivityManagerNative;
78import android.app.AppGlobals;
79import android.app.IActivityManager;
80import android.app.admin.IDevicePolicyManager;
81import android.app.backup.IBackupManager;
82import android.app.usage.UsageStats;
83import android.app.usage.UsageStatsManager;
84import android.content.BroadcastReceiver;
85import android.content.ComponentName;
86import android.content.Context;
87import android.content.IIntentReceiver;
88import android.content.Intent;
89import android.content.IntentFilter;
90import android.content.IntentSender;
91import android.content.IntentSender.SendIntentException;
92import android.content.ServiceConnection;
93import android.content.pm.ActivityInfo;
94import android.content.pm.ApplicationInfo;
95import android.content.pm.FeatureInfo;
96import android.content.pm.IOnPermissionsChangeListener;
97import android.content.pm.IPackageDataObserver;
98import android.content.pm.IPackageDeleteObserver;
99import android.content.pm.IPackageDeleteObserver2;
100import android.content.pm.IPackageInstallObserver2;
101import android.content.pm.IPackageInstaller;
102import android.content.pm.IPackageManager;
103import android.content.pm.IPackageMoveObserver;
104import android.content.pm.IPackageStatsObserver;
105import android.content.pm.InstrumentationInfo;
106import android.content.pm.IntentFilterVerificationInfo;
107import android.content.pm.KeySet;
108import android.content.pm.ManifestDigest;
109import android.content.pm.PackageCleanItem;
110import android.content.pm.PackageInfo;
111import android.content.pm.PackageInfoLite;
112import android.content.pm.PackageInstaller;
113import android.content.pm.PackageManager;
114import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
115import android.content.pm.PackageManagerInternal;
116import android.content.pm.PackageParser;
117import android.content.pm.PackageParser.ActivityIntentInfo;
118import android.content.pm.PackageParser.PackageLite;
119import android.content.pm.PackageParser.PackageParserException;
120import android.content.pm.PackageStats;
121import android.content.pm.PackageUserState;
122import android.content.pm.ParceledListSlice;
123import android.content.pm.PermissionGroupInfo;
124import android.content.pm.PermissionInfo;
125import android.content.pm.ProviderInfo;
126import android.content.pm.ResolveInfo;
127import android.content.pm.ServiceInfo;
128import android.content.pm.Signature;
129import android.content.pm.UserInfo;
130import android.content.pm.VerificationParams;
131import android.content.pm.VerifierDeviceIdentity;
132import android.content.pm.VerifierInfo;
133import android.content.res.Resources;
134import android.hardware.display.DisplayManager;
135import android.net.Uri;
136import android.os.Binder;
137import android.os.Build;
138import android.os.Bundle;
139import android.os.Debug;
140import android.os.Environment;
141import android.os.Environment.UserEnvironment;
142import android.os.FileUtils;
143import android.os.Handler;
144import android.os.IBinder;
145import android.os.Looper;
146import android.os.Message;
147import android.os.Parcel;
148import android.os.ParcelFileDescriptor;
149import android.os.Process;
150import android.os.RemoteCallbackList;
151import android.os.RemoteException;
152import android.os.SELinux;
153import android.os.ServiceManager;
154import android.os.SystemClock;
155import android.os.SystemProperties;
156import android.os.UserHandle;
157import android.os.UserManager;
158import android.os.storage.IMountService;
159import android.os.storage.StorageEventListener;
160import android.os.storage.StorageManager;
161import android.os.storage.VolumeInfo;
162import android.os.storage.VolumeRecord;
163import android.security.KeyStore;
164import android.security.SystemKeyStore;
165import android.system.ErrnoException;
166import android.system.Os;
167import android.system.StructStat;
168import android.text.TextUtils;
169import android.text.format.DateUtils;
170import android.util.ArrayMap;
171import android.util.ArraySet;
172import android.util.AtomicFile;
173import android.util.DisplayMetrics;
174import android.util.EventLog;
175import android.util.ExceptionUtils;
176import android.util.Log;
177import android.util.LogPrinter;
178import android.util.MathUtils;
179import android.util.PrintStreamPrinter;
180import android.util.Slog;
181import android.util.SparseArray;
182import android.util.SparseBooleanArray;
183import android.util.SparseIntArray;
184import android.util.Xml;
185import android.view.Display;
186
187import dalvik.system.DexFile;
188import dalvik.system.VMRuntime;
189
190import libcore.io.IoUtils;
191import libcore.util.EmptyArray;
192
193import com.android.internal.R;
194import com.android.internal.app.IMediaContainerService;
195import com.android.internal.app.ResolverActivity;
196import com.android.internal.content.NativeLibraryHelper;
197import com.android.internal.content.PackageHelper;
198import com.android.internal.os.IParcelFileDescriptorFactory;
199import com.android.internal.os.SomeArgs;
200import com.android.internal.os.Zygote;
201import com.android.internal.util.ArrayUtils;
202import com.android.internal.util.FastPrintWriter;
203import com.android.internal.util.FastXmlSerializer;
204import com.android.internal.util.IndentingPrintWriter;
205import com.android.internal.util.Preconditions;
206import com.android.server.EventLogTags;
207import com.android.server.FgThread;
208import com.android.server.IntentResolver;
209import com.android.server.LocalServices;
210import com.android.server.ServiceThread;
211import com.android.server.SystemConfig;
212import com.android.server.Watchdog;
213import com.android.server.pm.PermissionsState.PermissionState;
214import com.android.server.pm.Settings.DatabaseVersion;
215import com.android.server.storage.DeviceStorageMonitorInternal;
216
217import org.xmlpull.v1.XmlPullParser;
218import org.xmlpull.v1.XmlPullParserException;
219import org.xmlpull.v1.XmlSerializer;
220
221import java.io.BufferedInputStream;
222import java.io.BufferedOutputStream;
223import java.io.BufferedReader;
224import java.io.ByteArrayInputStream;
225import java.io.ByteArrayOutputStream;
226import java.io.File;
227import java.io.FileDescriptor;
228import java.io.FileNotFoundException;
229import java.io.FileOutputStream;
230import java.io.FileReader;
231import java.io.FilenameFilter;
232import java.io.IOException;
233import java.io.InputStream;
234import java.io.PrintWriter;
235import java.nio.charset.StandardCharsets;
236import java.security.NoSuchAlgorithmException;
237import java.security.PublicKey;
238import java.security.cert.CertificateEncodingException;
239import java.security.cert.CertificateException;
240import java.text.SimpleDateFormat;
241import java.util.ArrayList;
242import java.util.Arrays;
243import java.util.Collection;
244import java.util.Collections;
245import java.util.Comparator;
246import java.util.Date;
247import java.util.Iterator;
248import java.util.List;
249import java.util.Map;
250import java.util.Objects;
251import java.util.Set;
252import java.util.concurrent.CountDownLatch;
253import java.util.concurrent.TimeUnit;
254import java.util.concurrent.atomic.AtomicBoolean;
255import java.util.concurrent.atomic.AtomicInteger;
256import java.util.concurrent.atomic.AtomicLong;
257
258/**
259 * Keep track of all those .apks everywhere.
260 *
261 * This is very central to the platform's security; please run the unit
262 * tests whenever making modifications here:
263 *
264mmm frameworks/base/tests/AndroidTests
265adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
266adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
267 *
268 * {@hide}
269 */
270public class PackageManagerService extends IPackageManager.Stub {
271    static final String TAG = "PackageManager";
272    static final boolean DEBUG_SETTINGS = false;
273    static final boolean DEBUG_PREFERRED = false;
274    static final boolean DEBUG_UPGRADE = false;
275    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
276    private static final boolean DEBUG_BACKUP = true;
277    private static final boolean DEBUG_INSTALL = false;
278    private static final boolean DEBUG_REMOVE = false;
279    private static final boolean DEBUG_BROADCASTS = false;
280    private static final boolean DEBUG_SHOW_INFO = false;
281    private static final boolean DEBUG_PACKAGE_INFO = false;
282    private static final boolean DEBUG_INTENT_MATCHING = false;
283    private static final boolean DEBUG_PACKAGE_SCANNING = false;
284    private static final boolean DEBUG_VERIFY = false;
285    private static final boolean DEBUG_DEXOPT = false;
286    private static final boolean DEBUG_ABI_SELECTION = false;
287
288    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = Build.IS_DEBUGGABLE;
289
290    private static final int RADIO_UID = Process.PHONE_UID;
291    private static final int LOG_UID = Process.LOG_UID;
292    private static final int NFC_UID = Process.NFC_UID;
293    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
294    private static final int SHELL_UID = Process.SHELL_UID;
295
296    // Cap the size of permission trees that 3rd party apps can define
297    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
298
299    // Suffix used during package installation when copying/moving
300    // package apks to install directory.
301    private static final String INSTALL_PACKAGE_SUFFIX = "-";
302
303    static final int SCAN_NO_DEX = 1<<1;
304    static final int SCAN_FORCE_DEX = 1<<2;
305    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
306    static final int SCAN_NEW_INSTALL = 1<<4;
307    static final int SCAN_NO_PATHS = 1<<5;
308    static final int SCAN_UPDATE_TIME = 1<<6;
309    static final int SCAN_DEFER_DEX = 1<<7;
310    static final int SCAN_BOOTING = 1<<8;
311    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
312    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
313    static final int SCAN_REQUIRE_KNOWN = 1<<12;
314    static final int SCAN_MOVE = 1<<13;
315    static final int SCAN_INITIAL = 1<<14;
316
317    static final int REMOVE_CHATTY = 1<<16;
318
319    private static final int[] EMPTY_INT_ARRAY = new int[0];
320
321    /**
322     * Timeout (in milliseconds) after which the watchdog should declare that
323     * our handler thread is wedged.  The usual default for such things is one
324     * minute but we sometimes do very lengthy I/O operations on this thread,
325     * such as installing multi-gigabyte applications, so ours needs to be longer.
326     */
327    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
328
329    /**
330     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
331     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
332     * settings entry if available, otherwise we use the hardcoded default.  If it's been
333     * more than this long since the last fstrim, we force one during the boot sequence.
334     *
335     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
336     * one gets run at the next available charging+idle time.  This final mandatory
337     * no-fstrim check kicks in only of the other scheduling criteria is never met.
338     */
339    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
340
341    /**
342     * Whether verification is enabled by default.
343     */
344    private static final boolean DEFAULT_VERIFY_ENABLE = true;
345
346    /**
347     * The default maximum time to wait for the verification agent to return in
348     * milliseconds.
349     */
350    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
351
352    /**
353     * The default response for package verification timeout.
354     *
355     * This can be either PackageManager.VERIFICATION_ALLOW or
356     * PackageManager.VERIFICATION_REJECT.
357     */
358    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
359
360    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
361
362    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
363            DEFAULT_CONTAINER_PACKAGE,
364            "com.android.defcontainer.DefaultContainerService");
365
366    private static final String KILL_APP_REASON_GIDS_CHANGED =
367            "permission grant or revoke changed gids";
368
369    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
370            "permissions revoked";
371
372    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
373
374    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
375
376    /** Permission grant: not grant the permission. */
377    private static final int GRANT_DENIED = 1;
378
379    /** Permission grant: grant the permission as an install permission. */
380    private static final int GRANT_INSTALL = 2;
381
382    /** Permission grant: grant the permission as an install permission for a legacy app. */
383    private static final int GRANT_INSTALL_LEGACY = 3;
384
385    /** Permission grant: grant the permission as a runtime one. */
386    private static final int GRANT_RUNTIME = 4;
387
388    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
389    private static final int GRANT_UPGRADE = 5;
390
391    final ServiceThread mHandlerThread;
392
393    final PackageHandler mHandler;
394
395    /**
396     * Messages for {@link #mHandler} that need to wait for system ready before
397     * being dispatched.
398     */
399    private ArrayList<Message> mPostSystemReadyMessages;
400
401    final int mSdkVersion = Build.VERSION.SDK_INT;
402
403    final Context mContext;
404    final boolean mFactoryTest;
405    final boolean mOnlyCore;
406    final boolean mLazyDexOpt;
407    final long mDexOptLRUThresholdInMills;
408    final DisplayMetrics mMetrics;
409    final int mDefParseFlags;
410    final String[] mSeparateProcesses;
411    final boolean mIsUpgrade;
412
413    // This is where all application persistent data goes.
414    final File mAppDataDir;
415
416    // This is where all application persistent data goes for secondary users.
417    final File mUserAppDataDir;
418
419    /** The location for ASEC container files on internal storage. */
420    final String mAsecInternalPath;
421
422    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
423    // LOCK HELD.  Can be called with mInstallLock held.
424    final Installer mInstaller;
425
426    /** Directory where installed third-party apps stored */
427    final File mAppInstallDir;
428
429    /**
430     * Directory to which applications installed internally have their
431     * 32 bit native libraries copied.
432     */
433    private File mAppLib32InstallDir;
434
435    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
436    // apps.
437    final File mDrmAppPrivateInstallDir;
438
439    // ----------------------------------------------------------------
440
441    // Lock for state used when installing and doing other long running
442    // operations.  Methods that must be called with this lock held have
443    // the suffix "LI".
444    final Object mInstallLock = new Object();
445
446    // ----------------------------------------------------------------
447
448    // Keys are String (package name), values are Package.  This also serves
449    // as the lock for the global state.  Methods that must be called with
450    // this lock held have the prefix "LP".
451    final ArrayMap<String, PackageParser.Package> mPackages =
452            new ArrayMap<String, PackageParser.Package>();
453
454    // Tracks available target package names -> overlay package paths.
455    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
456        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
457
458    final Settings mSettings;
459    boolean mRestoredSettings;
460
461    // System configuration read by SystemConfig.
462    final int[] mGlobalGids;
463    final SparseArray<ArraySet<String>> mSystemPermissions;
464    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
465
466    // If mac_permissions.xml was found for seinfo labeling.
467    boolean mFoundPolicyFile;
468
469    // If a recursive restorecon of /data/data/<pkg> is needed.
470    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
471
472    public static final class SharedLibraryEntry {
473        public final String path;
474        public final String apk;
475
476        SharedLibraryEntry(String _path, String _apk) {
477            path = _path;
478            apk = _apk;
479        }
480    }
481
482    // Currently known shared libraries.
483    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
484            new ArrayMap<String, SharedLibraryEntry>();
485
486    // All available activities, for your resolving pleasure.
487    final ActivityIntentResolver mActivities =
488            new ActivityIntentResolver();
489
490    // All available receivers, for your resolving pleasure.
491    final ActivityIntentResolver mReceivers =
492            new ActivityIntentResolver();
493
494    // All available services, for your resolving pleasure.
495    final ServiceIntentResolver mServices = new ServiceIntentResolver();
496
497    // All available providers, for your resolving pleasure.
498    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
499
500    // Mapping from provider base names (first directory in content URI codePath)
501    // to the provider information.
502    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
503            new ArrayMap<String, PackageParser.Provider>();
504
505    // Mapping from instrumentation class names to info about them.
506    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
507            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
508
509    // Mapping from permission names to info about them.
510    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
511            new ArrayMap<String, PackageParser.PermissionGroup>();
512
513    // Packages whose data we have transfered into another package, thus
514    // should no longer exist.
515    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
516
517    // Broadcast actions that are only available to the system.
518    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
519
520    /** List of packages waiting for verification. */
521    final SparseArray<PackageVerificationState> mPendingVerification
522            = new SparseArray<PackageVerificationState>();
523
524    /** Set of packages associated with each app op permission. */
525    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
526
527    final PackageInstallerService mInstallerService;
528
529    private final PackageDexOptimizer mPackageDexOptimizer;
530
531    private AtomicInteger mNextMoveId = new AtomicInteger();
532    private final MoveCallbacks mMoveCallbacks;
533
534    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
535
536    // Cache of users who need badging.
537    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
538
539    /** Token for keys in mPendingVerification. */
540    private int mPendingVerificationToken = 0;
541
542    volatile boolean mSystemReady;
543    volatile boolean mSafeMode;
544    volatile boolean mHasSystemUidErrors;
545
546    ApplicationInfo mAndroidApplication;
547    final ActivityInfo mResolveActivity = new ActivityInfo();
548    final ResolveInfo mResolveInfo = new ResolveInfo();
549    ComponentName mResolveComponentName;
550    PackageParser.Package mPlatformPackage;
551    ComponentName mCustomResolverComponentName;
552
553    boolean mResolverReplaced = false;
554
555    private final ComponentName mIntentFilterVerifierComponent;
556    private int mIntentFilterVerificationToken = 0;
557
558    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
559            = new SparseArray<IntentFilterVerificationState>();
560
561    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
562            new DefaultPermissionGrantPolicy(this);
563
564    private static class IFVerificationParams {
565        PackageParser.Package pkg;
566        boolean replacing;
567        int userId;
568        int verifierUid;
569
570        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
571                int _userId, int _verifierUid) {
572            pkg = _pkg;
573            replacing = _replacing;
574            userId = _userId;
575            replacing = _replacing;
576            verifierUid = _verifierUid;
577        }
578    }
579
580    private interface IntentFilterVerifier<T extends IntentFilter> {
581        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
582                                               T filter, String packageName);
583        void startVerifications(int userId);
584        void receiveVerificationResponse(int verificationId);
585    }
586
587    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
588        private Context mContext;
589        private ComponentName mIntentFilterVerifierComponent;
590        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
591
592        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
593            mContext = context;
594            mIntentFilterVerifierComponent = verifierComponent;
595        }
596
597        private String getDefaultScheme() {
598            return IntentFilter.SCHEME_HTTPS;
599        }
600
601        @Override
602        public void startVerifications(int userId) {
603            // Launch verifications requests
604            int count = mCurrentIntentFilterVerifications.size();
605            for (int n=0; n<count; n++) {
606                int verificationId = mCurrentIntentFilterVerifications.get(n);
607                final IntentFilterVerificationState ivs =
608                        mIntentFilterVerificationStates.get(verificationId);
609
610                String packageName = ivs.getPackageName();
611
612                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
613                final int filterCount = filters.size();
614                ArraySet<String> domainsSet = new ArraySet<>();
615                for (int m=0; m<filterCount; m++) {
616                    PackageParser.ActivityIntentInfo filter = filters.get(m);
617                    domainsSet.addAll(filter.getHostsList());
618                }
619                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
620                synchronized (mPackages) {
621                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
622                            packageName, domainsList) != null) {
623                        scheduleWriteSettingsLocked();
624                    }
625                }
626                sendVerificationRequest(userId, verificationId, ivs);
627            }
628            mCurrentIntentFilterVerifications.clear();
629        }
630
631        private void sendVerificationRequest(int userId, int verificationId,
632                IntentFilterVerificationState ivs) {
633
634            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
635            verificationIntent.putExtra(
636                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
637                    verificationId);
638            verificationIntent.putExtra(
639                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
640                    getDefaultScheme());
641            verificationIntent.putExtra(
642                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
643                    ivs.getHostsString());
644            verificationIntent.putExtra(
645                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
646                    ivs.getPackageName());
647            verificationIntent.setComponent(mIntentFilterVerifierComponent);
648            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
649
650            UserHandle user = new UserHandle(userId);
651            mContext.sendBroadcastAsUser(verificationIntent, user);
652            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
653                    "Sending IntentFilter verification broadcast");
654        }
655
656        public void receiveVerificationResponse(int verificationId) {
657            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
658
659            final boolean verified = ivs.isVerified();
660
661            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
662            final int count = filters.size();
663            if (DEBUG_DOMAIN_VERIFICATION) {
664                Slog.i(TAG, "Received verification response " + verificationId
665                        + " for " + count + " filters, verified=" + verified);
666            }
667            for (int n=0; n<count; n++) {
668                PackageParser.ActivityIntentInfo filter = filters.get(n);
669                filter.setVerified(verified);
670
671                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
672                        + " verified with result:" + verified + " and hosts:"
673                        + ivs.getHostsString());
674            }
675
676            mIntentFilterVerificationStates.remove(verificationId);
677
678            final String packageName = ivs.getPackageName();
679            IntentFilterVerificationInfo ivi = null;
680
681            synchronized (mPackages) {
682                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
683            }
684            if (ivi == null) {
685                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
686                        + verificationId + " packageName:" + packageName);
687                return;
688            }
689            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
690                    "Updating IntentFilterVerificationInfo for verificationId:" + verificationId);
691
692            synchronized (mPackages) {
693                if (verified) {
694                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
695                } else {
696                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
697                }
698                scheduleWriteSettingsLocked();
699
700                final int userId = ivs.getUserId();
701                if (userId != UserHandle.USER_ALL) {
702                    final int userStatus =
703                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
704
705                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
706                    boolean needUpdate = false;
707
708                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
709                    // already been set by the User thru the Disambiguation dialog
710                    switch (userStatus) {
711                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
712                            if (verified) {
713                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
714                            } else {
715                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
716                            }
717                            needUpdate = true;
718                            break;
719
720                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
721                            if (verified) {
722                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
723                                needUpdate = true;
724                            }
725                            break;
726
727                        default:
728                            // Nothing to do
729                    }
730
731                    if (needUpdate) {
732                        mSettings.updateIntentFilterVerificationStatusLPw(
733                                packageName, updatedStatus, userId);
734                        scheduleWritePackageRestrictionsLocked(userId);
735                    }
736                }
737            }
738        }
739
740        @Override
741        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
742                    ActivityIntentInfo filter, String packageName) {
743            if (!hasValidDomains(filter)) {
744                return false;
745            }
746            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
747            if (ivs == null) {
748                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
749                        packageName);
750            }
751            if (DEBUG_DOMAIN_VERIFICATION) {
752                Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter);
753            }
754            ivs.addFilter(filter);
755            return true;
756        }
757
758        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
759                int userId, int verificationId, String packageName) {
760            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
761                    verifierUid, userId, packageName);
762            ivs.setPendingState();
763            synchronized (mPackages) {
764                mIntentFilterVerificationStates.append(verificationId, ivs);
765                mCurrentIntentFilterVerifications.add(verificationId);
766            }
767            return ivs;
768        }
769    }
770
771    private static boolean hasValidDomains(ActivityIntentInfo filter) {
772        boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
773                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS);
774        if (!hasHTTPorHTTPS) {
775            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
776                    "IntentFilter does not contain any HTTP or HTTPS data scheme");
777            return false;
778        }
779        return true;
780    }
781
782    private IntentFilterVerifier mIntentFilterVerifier;
783
784    // Set of pending broadcasts for aggregating enable/disable of components.
785    static class PendingPackageBroadcasts {
786        // for each user id, a map of <package name -> components within that package>
787        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
788
789        public PendingPackageBroadcasts() {
790            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
791        }
792
793        public ArrayList<String> get(int userId, String packageName) {
794            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
795            return packages.get(packageName);
796        }
797
798        public void put(int userId, String packageName, ArrayList<String> components) {
799            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
800            packages.put(packageName, components);
801        }
802
803        public void remove(int userId, String packageName) {
804            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
805            if (packages != null) {
806                packages.remove(packageName);
807            }
808        }
809
810        public void remove(int userId) {
811            mUidMap.remove(userId);
812        }
813
814        public int userIdCount() {
815            return mUidMap.size();
816        }
817
818        public int userIdAt(int n) {
819            return mUidMap.keyAt(n);
820        }
821
822        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
823            return mUidMap.get(userId);
824        }
825
826        public int size() {
827            // total number of pending broadcast entries across all userIds
828            int num = 0;
829            for (int i = 0; i< mUidMap.size(); i++) {
830                num += mUidMap.valueAt(i).size();
831            }
832            return num;
833        }
834
835        public void clear() {
836            mUidMap.clear();
837        }
838
839        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
840            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
841            if (map == null) {
842                map = new ArrayMap<String, ArrayList<String>>();
843                mUidMap.put(userId, map);
844            }
845            return map;
846        }
847    }
848    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
849
850    // Service Connection to remote media container service to copy
851    // package uri's from external media onto secure containers
852    // or internal storage.
853    private IMediaContainerService mContainerService = null;
854
855    static final int SEND_PENDING_BROADCAST = 1;
856    static final int MCS_BOUND = 3;
857    static final int END_COPY = 4;
858    static final int INIT_COPY = 5;
859    static final int MCS_UNBIND = 6;
860    static final int START_CLEANING_PACKAGE = 7;
861    static final int FIND_INSTALL_LOC = 8;
862    static final int POST_INSTALL = 9;
863    static final int MCS_RECONNECT = 10;
864    static final int MCS_GIVE_UP = 11;
865    static final int UPDATED_MEDIA_STATUS = 12;
866    static final int WRITE_SETTINGS = 13;
867    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
868    static final int PACKAGE_VERIFIED = 15;
869    static final int CHECK_PENDING_VERIFICATION = 16;
870    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
871    static final int INTENT_FILTER_VERIFIED = 18;
872
873    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
874
875    // Delay time in millisecs
876    static final int BROADCAST_DELAY = 10 * 1000;
877
878    static UserManagerService sUserManager;
879
880    // Stores a list of users whose package restrictions file needs to be updated
881    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
882
883    final private DefaultContainerConnection mDefContainerConn =
884            new DefaultContainerConnection();
885    class DefaultContainerConnection implements ServiceConnection {
886        public void onServiceConnected(ComponentName name, IBinder service) {
887            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
888            IMediaContainerService imcs =
889                IMediaContainerService.Stub.asInterface(service);
890            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
891        }
892
893        public void onServiceDisconnected(ComponentName name) {
894            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
895        }
896    }
897
898    // Recordkeeping of restore-after-install operations that are currently in flight
899    // between the Package Manager and the Backup Manager
900    class PostInstallData {
901        public InstallArgs args;
902        public PackageInstalledInfo res;
903
904        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
905            args = _a;
906            res = _r;
907        }
908    }
909
910    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
911    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
912
913    // XML tags for backup/restore of various bits of state
914    private static final String TAG_PREFERRED_BACKUP = "pa";
915    private static final String TAG_DEFAULT_APPS = "da";
916    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
917
918    private final String mRequiredVerifierPackage;
919
920    private final PackageUsage mPackageUsage = new PackageUsage();
921
922    private class PackageUsage {
923        private static final int WRITE_INTERVAL
924            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
925
926        private final Object mFileLock = new Object();
927        private final AtomicLong mLastWritten = new AtomicLong(0);
928        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
929
930        private boolean mIsHistoricalPackageUsageAvailable = true;
931
932        boolean isHistoricalPackageUsageAvailable() {
933            return mIsHistoricalPackageUsageAvailable;
934        }
935
936        void write(boolean force) {
937            if (force) {
938                writeInternal();
939                return;
940            }
941            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
942                && !DEBUG_DEXOPT) {
943                return;
944            }
945            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
946                new Thread("PackageUsage_DiskWriter") {
947                    @Override
948                    public void run() {
949                        try {
950                            writeInternal();
951                        } finally {
952                            mBackgroundWriteRunning.set(false);
953                        }
954                    }
955                }.start();
956            }
957        }
958
959        private void writeInternal() {
960            synchronized (mPackages) {
961                synchronized (mFileLock) {
962                    AtomicFile file = getFile();
963                    FileOutputStream f = null;
964                    try {
965                        f = file.startWrite();
966                        BufferedOutputStream out = new BufferedOutputStream(f);
967                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
968                        StringBuilder sb = new StringBuilder();
969                        for (PackageParser.Package pkg : mPackages.values()) {
970                            if (pkg.mLastPackageUsageTimeInMills == 0) {
971                                continue;
972                            }
973                            sb.setLength(0);
974                            sb.append(pkg.packageName);
975                            sb.append(' ');
976                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
977                            sb.append('\n');
978                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
979                        }
980                        out.flush();
981                        file.finishWrite(f);
982                    } catch (IOException e) {
983                        if (f != null) {
984                            file.failWrite(f);
985                        }
986                        Log.e(TAG, "Failed to write package usage times", e);
987                    }
988                }
989            }
990            mLastWritten.set(SystemClock.elapsedRealtime());
991        }
992
993        void readLP() {
994            synchronized (mFileLock) {
995                AtomicFile file = getFile();
996                BufferedInputStream in = null;
997                try {
998                    in = new BufferedInputStream(file.openRead());
999                    StringBuffer sb = new StringBuffer();
1000                    while (true) {
1001                        String packageName = readToken(in, sb, ' ');
1002                        if (packageName == null) {
1003                            break;
1004                        }
1005                        String timeInMillisString = readToken(in, sb, '\n');
1006                        if (timeInMillisString == null) {
1007                            throw new IOException("Failed to find last usage time for package "
1008                                                  + packageName);
1009                        }
1010                        PackageParser.Package pkg = mPackages.get(packageName);
1011                        if (pkg == null) {
1012                            continue;
1013                        }
1014                        long timeInMillis;
1015                        try {
1016                            timeInMillis = Long.parseLong(timeInMillisString.toString());
1017                        } catch (NumberFormatException e) {
1018                            throw new IOException("Failed to parse " + timeInMillisString
1019                                                  + " as a long.", e);
1020                        }
1021                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1022                    }
1023                } catch (FileNotFoundException expected) {
1024                    mIsHistoricalPackageUsageAvailable = false;
1025                } catch (IOException e) {
1026                    Log.w(TAG, "Failed to read package usage times", e);
1027                } finally {
1028                    IoUtils.closeQuietly(in);
1029                }
1030            }
1031            mLastWritten.set(SystemClock.elapsedRealtime());
1032        }
1033
1034        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1035                throws IOException {
1036            sb.setLength(0);
1037            while (true) {
1038                int ch = in.read();
1039                if (ch == -1) {
1040                    if (sb.length() == 0) {
1041                        return null;
1042                    }
1043                    throw new IOException("Unexpected EOF");
1044                }
1045                if (ch == endOfToken) {
1046                    return sb.toString();
1047                }
1048                sb.append((char)ch);
1049            }
1050        }
1051
1052        private AtomicFile getFile() {
1053            File dataDir = Environment.getDataDirectory();
1054            File systemDir = new File(dataDir, "system");
1055            File fname = new File(systemDir, "package-usage.list");
1056            return new AtomicFile(fname);
1057        }
1058    }
1059
1060    class PackageHandler extends Handler {
1061        private boolean mBound = false;
1062        final ArrayList<HandlerParams> mPendingInstalls =
1063            new ArrayList<HandlerParams>();
1064
1065        private boolean connectToService() {
1066            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1067                    " DefaultContainerService");
1068            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1069            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1070            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1071                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
1072                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1073                mBound = true;
1074                return true;
1075            }
1076            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1077            return false;
1078        }
1079
1080        private void disconnectService() {
1081            mContainerService = null;
1082            mBound = false;
1083            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1084            mContext.unbindService(mDefContainerConn);
1085            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1086        }
1087
1088        PackageHandler(Looper looper) {
1089            super(looper);
1090        }
1091
1092        public void handleMessage(Message msg) {
1093            try {
1094                doHandleMessage(msg);
1095            } finally {
1096                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1097            }
1098        }
1099
1100        void doHandleMessage(Message msg) {
1101            switch (msg.what) {
1102                case INIT_COPY: {
1103                    HandlerParams params = (HandlerParams) msg.obj;
1104                    int idx = mPendingInstalls.size();
1105                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1106                    // If a bind was already initiated we dont really
1107                    // need to do anything. The pending install
1108                    // will be processed later on.
1109                    if (!mBound) {
1110                        // If this is the only one pending we might
1111                        // have to bind to the service again.
1112                        if (!connectToService()) {
1113                            Slog.e(TAG, "Failed to bind to media container service");
1114                            params.serviceError();
1115                            return;
1116                        } else {
1117                            // Once we bind to the service, the first
1118                            // pending request will be processed.
1119                            mPendingInstalls.add(idx, params);
1120                        }
1121                    } else {
1122                        mPendingInstalls.add(idx, params);
1123                        // Already bound to the service. Just make
1124                        // sure we trigger off processing the first request.
1125                        if (idx == 0) {
1126                            mHandler.sendEmptyMessage(MCS_BOUND);
1127                        }
1128                    }
1129                    break;
1130                }
1131                case MCS_BOUND: {
1132                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1133                    if (msg.obj != null) {
1134                        mContainerService = (IMediaContainerService) msg.obj;
1135                    }
1136                    if (mContainerService == null) {
1137                        if (!mBound) {
1138                            // Something seriously wrong since we are not bound and we are not
1139                            // waiting for connection. Bail out.
1140                            Slog.e(TAG, "Cannot bind to media container service");
1141                            for (HandlerParams params : mPendingInstalls) {
1142                                // Indicate service bind error
1143                                params.serviceError();
1144                            }
1145                            mPendingInstalls.clear();
1146                        } else {
1147                            Slog.w(TAG, "Waiting to connect to media container service");
1148                        }
1149                    } else if (mPendingInstalls.size() > 0) {
1150                        HandlerParams params = mPendingInstalls.get(0);
1151                        if (params != null) {
1152                            if (params.startCopy()) {
1153                                // We are done...  look for more work or to
1154                                // go idle.
1155                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1156                                        "Checking for more work or unbind...");
1157                                // Delete pending install
1158                                if (mPendingInstalls.size() > 0) {
1159                                    mPendingInstalls.remove(0);
1160                                }
1161                                if (mPendingInstalls.size() == 0) {
1162                                    if (mBound) {
1163                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1164                                                "Posting delayed MCS_UNBIND");
1165                                        removeMessages(MCS_UNBIND);
1166                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1167                                        // Unbind after a little delay, to avoid
1168                                        // continual thrashing.
1169                                        sendMessageDelayed(ubmsg, 10000);
1170                                    }
1171                                } else {
1172                                    // There are more pending requests in queue.
1173                                    // Just post MCS_BOUND message to trigger processing
1174                                    // of next pending install.
1175                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1176                                            "Posting MCS_BOUND for next work");
1177                                    mHandler.sendEmptyMessage(MCS_BOUND);
1178                                }
1179                            }
1180                        }
1181                    } else {
1182                        // Should never happen ideally.
1183                        Slog.w(TAG, "Empty queue");
1184                    }
1185                    break;
1186                }
1187                case MCS_RECONNECT: {
1188                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1189                    if (mPendingInstalls.size() > 0) {
1190                        if (mBound) {
1191                            disconnectService();
1192                        }
1193                        if (!connectToService()) {
1194                            Slog.e(TAG, "Failed to bind to media container service");
1195                            for (HandlerParams params : mPendingInstalls) {
1196                                // Indicate service bind error
1197                                params.serviceError();
1198                            }
1199                            mPendingInstalls.clear();
1200                        }
1201                    }
1202                    break;
1203                }
1204                case MCS_UNBIND: {
1205                    // If there is no actual work left, then time to unbind.
1206                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1207
1208                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1209                        if (mBound) {
1210                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1211
1212                            disconnectService();
1213                        }
1214                    } else if (mPendingInstalls.size() > 0) {
1215                        // There are more pending requests in queue.
1216                        // Just post MCS_BOUND message to trigger processing
1217                        // of next pending install.
1218                        mHandler.sendEmptyMessage(MCS_BOUND);
1219                    }
1220
1221                    break;
1222                }
1223                case MCS_GIVE_UP: {
1224                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1225                    mPendingInstalls.remove(0);
1226                    break;
1227                }
1228                case SEND_PENDING_BROADCAST: {
1229                    String packages[];
1230                    ArrayList<String> components[];
1231                    int size = 0;
1232                    int uids[];
1233                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1234                    synchronized (mPackages) {
1235                        if (mPendingBroadcasts == null) {
1236                            return;
1237                        }
1238                        size = mPendingBroadcasts.size();
1239                        if (size <= 0) {
1240                            // Nothing to be done. Just return
1241                            return;
1242                        }
1243                        packages = new String[size];
1244                        components = new ArrayList[size];
1245                        uids = new int[size];
1246                        int i = 0;  // filling out the above arrays
1247
1248                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1249                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1250                            Iterator<Map.Entry<String, ArrayList<String>>> it
1251                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1252                                            .entrySet().iterator();
1253                            while (it.hasNext() && i < size) {
1254                                Map.Entry<String, ArrayList<String>> ent = it.next();
1255                                packages[i] = ent.getKey();
1256                                components[i] = ent.getValue();
1257                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1258                                uids[i] = (ps != null)
1259                                        ? UserHandle.getUid(packageUserId, ps.appId)
1260                                        : -1;
1261                                i++;
1262                            }
1263                        }
1264                        size = i;
1265                        mPendingBroadcasts.clear();
1266                    }
1267                    // Send broadcasts
1268                    for (int i = 0; i < size; i++) {
1269                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1270                    }
1271                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1272                    break;
1273                }
1274                case START_CLEANING_PACKAGE: {
1275                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1276                    final String packageName = (String)msg.obj;
1277                    final int userId = msg.arg1;
1278                    final boolean andCode = msg.arg2 != 0;
1279                    synchronized (mPackages) {
1280                        if (userId == UserHandle.USER_ALL) {
1281                            int[] users = sUserManager.getUserIds();
1282                            for (int user : users) {
1283                                mSettings.addPackageToCleanLPw(
1284                                        new PackageCleanItem(user, packageName, andCode));
1285                            }
1286                        } else {
1287                            mSettings.addPackageToCleanLPw(
1288                                    new PackageCleanItem(userId, packageName, andCode));
1289                        }
1290                    }
1291                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1292                    startCleaningPackages();
1293                } break;
1294                case POST_INSTALL: {
1295                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1296                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1297                    mRunningInstalls.delete(msg.arg1);
1298                    boolean deleteOld = false;
1299
1300                    if (data != null) {
1301                        InstallArgs args = data.args;
1302                        PackageInstalledInfo res = data.res;
1303
1304                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1305                            res.removedInfo.sendBroadcast(false, true, false);
1306                            Bundle extras = new Bundle(1);
1307                            extras.putInt(Intent.EXTRA_UID, res.uid);
1308
1309                            // Now that we successfully installed the package, grant runtime
1310                            // permissions if requested before broadcasting the install.
1311                            if ((args.installFlags
1312                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) {
1313                                grantRequestedRuntimePermissions(res.pkg,
1314                                        args.user.getIdentifier());
1315                            }
1316
1317                            // Determine the set of users who are adding this
1318                            // package for the first time vs. those who are seeing
1319                            // an update.
1320                            int[] firstUsers;
1321                            int[] updateUsers = new int[0];
1322                            if (res.origUsers == null || res.origUsers.length == 0) {
1323                                firstUsers = res.newUsers;
1324                            } else {
1325                                firstUsers = new int[0];
1326                                for (int i=0; i<res.newUsers.length; i++) {
1327                                    int user = res.newUsers[i];
1328                                    boolean isNew = true;
1329                                    for (int j=0; j<res.origUsers.length; j++) {
1330                                        if (res.origUsers[j] == user) {
1331                                            isNew = false;
1332                                            break;
1333                                        }
1334                                    }
1335                                    if (isNew) {
1336                                        int[] newFirst = new int[firstUsers.length+1];
1337                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1338                                                firstUsers.length);
1339                                        newFirst[firstUsers.length] = user;
1340                                        firstUsers = newFirst;
1341                                    } else {
1342                                        int[] newUpdate = new int[updateUsers.length+1];
1343                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1344                                                updateUsers.length);
1345                                        newUpdate[updateUsers.length] = user;
1346                                        updateUsers = newUpdate;
1347                                    }
1348                                }
1349                            }
1350                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1351                                    res.pkg.applicationInfo.packageName,
1352                                    extras, null, null, firstUsers);
1353                            final boolean update = res.removedInfo.removedPackage != null;
1354                            if (update) {
1355                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1356                            }
1357                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1358                                    res.pkg.applicationInfo.packageName,
1359                                    extras, null, null, updateUsers);
1360                            if (update) {
1361                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1362                                        res.pkg.applicationInfo.packageName,
1363                                        extras, null, null, updateUsers);
1364                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1365                                        null, null,
1366                                        res.pkg.applicationInfo.packageName, null, updateUsers);
1367
1368                                // treat asec-hosted packages like removable media on upgrade
1369                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1370                                    if (DEBUG_INSTALL) {
1371                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1372                                                + " is ASEC-hosted -> AVAILABLE");
1373                                    }
1374                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1375                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1376                                    pkgList.add(res.pkg.applicationInfo.packageName);
1377                                    sendResourcesChangedBroadcast(true, true,
1378                                            pkgList,uidArray, null);
1379                                }
1380                            }
1381                            if (res.removedInfo.args != null) {
1382                                // Remove the replaced package's older resources safely now
1383                                deleteOld = true;
1384                            }
1385
1386                            // Log current value of "unknown sources" setting
1387                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1388                                getUnknownSourcesSettings());
1389                        }
1390                        // Force a gc to clear up things
1391                        Runtime.getRuntime().gc();
1392                        // We delete after a gc for applications  on sdcard.
1393                        if (deleteOld) {
1394                            synchronized (mInstallLock) {
1395                                res.removedInfo.args.doPostDeleteLI(true);
1396                            }
1397                        }
1398                        if (args.observer != null) {
1399                            try {
1400                                Bundle extras = extrasForInstallResult(res);
1401                                args.observer.onPackageInstalled(res.name, res.returnCode,
1402                                        res.returnMsg, extras);
1403                            } catch (RemoteException e) {
1404                                Slog.i(TAG, "Observer no longer exists.");
1405                            }
1406                        }
1407                    } else {
1408                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1409                    }
1410                } break;
1411                case UPDATED_MEDIA_STATUS: {
1412                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1413                    boolean reportStatus = msg.arg1 == 1;
1414                    boolean doGc = msg.arg2 == 1;
1415                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1416                    if (doGc) {
1417                        // Force a gc to clear up stale containers.
1418                        Runtime.getRuntime().gc();
1419                    }
1420                    if (msg.obj != null) {
1421                        @SuppressWarnings("unchecked")
1422                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1423                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1424                        // Unload containers
1425                        unloadAllContainers(args);
1426                    }
1427                    if (reportStatus) {
1428                        try {
1429                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1430                            PackageHelper.getMountService().finishMediaUpdate();
1431                        } catch (RemoteException e) {
1432                            Log.e(TAG, "MountService not running?");
1433                        }
1434                    }
1435                } break;
1436                case WRITE_SETTINGS: {
1437                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1438                    synchronized (mPackages) {
1439                        removeMessages(WRITE_SETTINGS);
1440                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1441                        mSettings.writeLPr();
1442                        mDirtyUsers.clear();
1443                    }
1444                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1445                } break;
1446                case WRITE_PACKAGE_RESTRICTIONS: {
1447                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1448                    synchronized (mPackages) {
1449                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1450                        for (int userId : mDirtyUsers) {
1451                            mSettings.writePackageRestrictionsLPr(userId);
1452                        }
1453                        mDirtyUsers.clear();
1454                    }
1455                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1456                } break;
1457                case CHECK_PENDING_VERIFICATION: {
1458                    final int verificationId = msg.arg1;
1459                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1460
1461                    if ((state != null) && !state.timeoutExtended()) {
1462                        final InstallArgs args = state.getInstallArgs();
1463                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1464
1465                        Slog.i(TAG, "Verification timed out for " + originUri);
1466                        mPendingVerification.remove(verificationId);
1467
1468                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1469
1470                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1471                            Slog.i(TAG, "Continuing with installation of " + originUri);
1472                            state.setVerifierResponse(Binder.getCallingUid(),
1473                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1474                            broadcastPackageVerified(verificationId, originUri,
1475                                    PackageManager.VERIFICATION_ALLOW,
1476                                    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                            broadcastPackageVerified(verificationId, originUri,
1484                                    PackageManager.VERIFICATION_REJECT,
1485                                    state.getInstallArgs().getUser());
1486                        }
1487
1488                        processPendingInstall(args, ret);
1489                        mHandler.sendEmptyMessage(MCS_UNBIND);
1490                    }
1491                    break;
1492                }
1493                case PACKAGE_VERIFIED: {
1494                    final int verificationId = msg.arg1;
1495
1496                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1497                    if (state == null) {
1498                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1499                        break;
1500                    }
1501
1502                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1503
1504                    state.setVerifierResponse(response.callerUid, response.code);
1505
1506                    if (state.isVerificationComplete()) {
1507                        mPendingVerification.remove(verificationId);
1508
1509                        final InstallArgs args = state.getInstallArgs();
1510                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1511
1512                        int ret;
1513                        if (state.isInstallAllowed()) {
1514                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1515                            broadcastPackageVerified(verificationId, originUri,
1516                                    response.code, state.getInstallArgs().getUser());
1517                            try {
1518                                ret = args.copyApk(mContainerService, true);
1519                            } catch (RemoteException e) {
1520                                Slog.e(TAG, "Could not contact the ContainerService");
1521                            }
1522                        } else {
1523                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1524                        }
1525
1526                        processPendingInstall(args, ret);
1527
1528                        mHandler.sendEmptyMessage(MCS_UNBIND);
1529                    }
1530
1531                    break;
1532                }
1533                case START_INTENT_FILTER_VERIFICATIONS: {
1534                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1535                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1536                            params.replacing, params.pkg);
1537                    break;
1538                }
1539                case INTENT_FILTER_VERIFIED: {
1540                    final int verificationId = msg.arg1;
1541
1542                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1543                            verificationId);
1544                    if (state == null) {
1545                        Slog.w(TAG, "Invalid IntentFilter verification token "
1546                                + verificationId + " received");
1547                        break;
1548                    }
1549
1550                    final int userId = state.getUserId();
1551
1552                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1553                            "Processing IntentFilter verification with token:"
1554                            + verificationId + " and userId:" + userId);
1555
1556                    final IntentFilterVerificationResponse response =
1557                            (IntentFilterVerificationResponse) msg.obj;
1558
1559                    state.setVerifierResponse(response.callerUid, response.code);
1560
1561                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1562                            "IntentFilter verification with token:" + verificationId
1563                            + " and userId:" + userId
1564                            + " is settings verifier response with response code:"
1565                            + response.code);
1566
1567                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1568                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1569                                + response.getFailedDomainsString());
1570                    }
1571
1572                    if (state.isVerificationComplete()) {
1573                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1574                    } else {
1575                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1576                                "IntentFilter verification with token:" + verificationId
1577                                + " was not said to be complete");
1578                    }
1579
1580                    break;
1581                }
1582            }
1583        }
1584    }
1585
1586    private StorageEventListener mStorageListener = new StorageEventListener() {
1587        @Override
1588        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1589            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1590                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1591                    // TODO: ensure that private directories exist for all active users
1592                    // TODO: remove user data whose serial number doesn't match
1593                    loadPrivatePackages(vol);
1594                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1595                    unloadPrivatePackages(vol);
1596                }
1597            }
1598
1599            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1600                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1601                    updateExternalMediaStatus(true, false);
1602                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1603                    updateExternalMediaStatus(false, false);
1604                }
1605            }
1606        }
1607
1608        @Override
1609        public void onVolumeForgotten(String fsUuid) {
1610            // TODO: remove all packages hosted on this uuid
1611        }
1612    };
1613
1614    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) {
1615        if (userId >= UserHandle.USER_OWNER) {
1616            grantRequestedRuntimePermissionsForUser(pkg, userId);
1617        } else if (userId == UserHandle.USER_ALL) {
1618            for (int someUserId : UserManagerService.getInstance().getUserIds()) {
1619                grantRequestedRuntimePermissionsForUser(pkg, someUserId);
1620            }
1621        }
1622
1623        // We could have touched GID membership, so flush out packages.list
1624        synchronized (mPackages) {
1625            mSettings.writePackageListLPr();
1626        }
1627    }
1628
1629    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) {
1630        SettingBase sb = (SettingBase) pkg.mExtras;
1631        if (sb == null) {
1632            return;
1633        }
1634
1635        PermissionsState permissionsState = sb.getPermissionsState();
1636
1637        for (String permission : pkg.requestedPermissions) {
1638            BasePermission bp = mSettings.mPermissions.get(permission);
1639            if (bp != null && bp.isRuntime()) {
1640                permissionsState.grantRuntimePermission(bp, userId);
1641            }
1642        }
1643    }
1644
1645    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1646        Bundle extras = null;
1647        switch (res.returnCode) {
1648            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1649                extras = new Bundle();
1650                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1651                        res.origPermission);
1652                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1653                        res.origPackage);
1654                break;
1655            }
1656            case PackageManager.INSTALL_SUCCEEDED: {
1657                extras = new Bundle();
1658                extras.putBoolean(Intent.EXTRA_REPLACING,
1659                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1660                break;
1661            }
1662        }
1663        return extras;
1664    }
1665
1666    void scheduleWriteSettingsLocked() {
1667        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1668            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1669        }
1670    }
1671
1672    void scheduleWritePackageRestrictionsLocked(int userId) {
1673        if (!sUserManager.exists(userId)) return;
1674        mDirtyUsers.add(userId);
1675        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1676            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1677        }
1678    }
1679
1680    public static PackageManagerService main(Context context, Installer installer,
1681            boolean factoryTest, boolean onlyCore) {
1682        PackageManagerService m = new PackageManagerService(context, installer,
1683                factoryTest, onlyCore);
1684        ServiceManager.addService("package", m);
1685        return m;
1686    }
1687
1688    static String[] splitString(String str, char sep) {
1689        int count = 1;
1690        int i = 0;
1691        while ((i=str.indexOf(sep, i)) >= 0) {
1692            count++;
1693            i++;
1694        }
1695
1696        String[] res = new String[count];
1697        i=0;
1698        count = 0;
1699        int lastI=0;
1700        while ((i=str.indexOf(sep, i)) >= 0) {
1701            res[count] = str.substring(lastI, i);
1702            count++;
1703            i++;
1704            lastI = i;
1705        }
1706        res[count] = str.substring(lastI, str.length());
1707        return res;
1708    }
1709
1710    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1711        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1712                Context.DISPLAY_SERVICE);
1713        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1714    }
1715
1716    public PackageManagerService(Context context, Installer installer,
1717            boolean factoryTest, boolean onlyCore) {
1718        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1719                SystemClock.uptimeMillis());
1720
1721        if (mSdkVersion <= 0) {
1722            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1723        }
1724
1725        mContext = context;
1726        mFactoryTest = factoryTest;
1727        mOnlyCore = onlyCore;
1728        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1729        mMetrics = new DisplayMetrics();
1730        mSettings = new Settings(mPackages);
1731        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1732                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1733        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1734                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1735        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1736                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1737        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1738                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1739        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1740                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1741        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1742                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1743
1744        // TODO: add a property to control this?
1745        long dexOptLRUThresholdInMinutes;
1746        if (mLazyDexOpt) {
1747            dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1748        } else {
1749            dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1750        }
1751        mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1752
1753        String separateProcesses = SystemProperties.get("debug.separate_processes");
1754        if (separateProcesses != null && separateProcesses.length() > 0) {
1755            if ("*".equals(separateProcesses)) {
1756                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1757                mSeparateProcesses = null;
1758                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1759            } else {
1760                mDefParseFlags = 0;
1761                mSeparateProcesses = separateProcesses.split(",");
1762                Slog.w(TAG, "Running with debug.separate_processes: "
1763                        + separateProcesses);
1764            }
1765        } else {
1766            mDefParseFlags = 0;
1767            mSeparateProcesses = null;
1768        }
1769
1770        mInstaller = installer;
1771        mPackageDexOptimizer = new PackageDexOptimizer(this);
1772        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1773
1774        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1775                FgThread.get().getLooper());
1776
1777        getDefaultDisplayMetrics(context, mMetrics);
1778
1779        SystemConfig systemConfig = SystemConfig.getInstance();
1780        mGlobalGids = systemConfig.getGlobalGids();
1781        mSystemPermissions = systemConfig.getSystemPermissions();
1782        mAvailableFeatures = systemConfig.getAvailableFeatures();
1783
1784        synchronized (mInstallLock) {
1785        // writer
1786        synchronized (mPackages) {
1787            mHandlerThread = new ServiceThread(TAG,
1788                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1789            mHandlerThread.start();
1790            mHandler = new PackageHandler(mHandlerThread.getLooper());
1791            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1792
1793            File dataDir = Environment.getDataDirectory();
1794            mAppDataDir = new File(dataDir, "data");
1795            mAppInstallDir = new File(dataDir, "app");
1796            mAppLib32InstallDir = new File(dataDir, "app-lib");
1797            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1798            mUserAppDataDir = new File(dataDir, "user");
1799            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1800
1801            sUserManager = new UserManagerService(context, this,
1802                    mInstallLock, mPackages);
1803
1804            // Propagate permission configuration in to package manager.
1805            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1806                    = systemConfig.getPermissions();
1807            for (int i=0; i<permConfig.size(); i++) {
1808                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1809                BasePermission bp = mSettings.mPermissions.get(perm.name);
1810                if (bp == null) {
1811                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1812                    mSettings.mPermissions.put(perm.name, bp);
1813                }
1814                if (perm.gids != null) {
1815                    bp.setGids(perm.gids, perm.perUser);
1816                }
1817            }
1818
1819            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1820            for (int i=0; i<libConfig.size(); i++) {
1821                mSharedLibraries.put(libConfig.keyAt(i),
1822                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1823            }
1824
1825            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1826
1827            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1828                    mSdkVersion, mOnlyCore);
1829
1830            String customResolverActivity = Resources.getSystem().getString(
1831                    R.string.config_customResolverActivity);
1832            if (TextUtils.isEmpty(customResolverActivity)) {
1833                customResolverActivity = null;
1834            } else {
1835                mCustomResolverComponentName = ComponentName.unflattenFromString(
1836                        customResolverActivity);
1837            }
1838
1839            long startTime = SystemClock.uptimeMillis();
1840
1841            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1842                    startTime);
1843
1844            // Set flag to monitor and not change apk file paths when
1845            // scanning install directories.
1846            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
1847
1848            final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1849
1850            /**
1851             * Add everything in the in the boot class path to the
1852             * list of process files because dexopt will have been run
1853             * if necessary during zygote startup.
1854             */
1855            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1856            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1857
1858            if (bootClassPath != null) {
1859                String[] bootClassPathElements = splitString(bootClassPath, ':');
1860                for (String element : bootClassPathElements) {
1861                    alreadyDexOpted.add(element);
1862                }
1863            } else {
1864                Slog.w(TAG, "No BOOTCLASSPATH found!");
1865            }
1866
1867            if (systemServerClassPath != null) {
1868                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1869                for (String element : systemServerClassPathElements) {
1870                    alreadyDexOpted.add(element);
1871                }
1872            } else {
1873                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1874            }
1875
1876            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
1877            final String[] dexCodeInstructionSets =
1878                    getDexCodeInstructionSets(
1879                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
1880
1881            /**
1882             * Ensure all external libraries have had dexopt run on them.
1883             */
1884            if (mSharedLibraries.size() > 0) {
1885                // NOTE: For now, we're compiling these system "shared libraries"
1886                // (and framework jars) into all available architectures. It's possible
1887                // to compile them only when we come across an app that uses them (there's
1888                // already logic for that in scanPackageLI) but that adds some complexity.
1889                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1890                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1891                        final String lib = libEntry.path;
1892                        if (lib == null) {
1893                            continue;
1894                        }
1895
1896                        try {
1897                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
1898                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1899                                alreadyDexOpted.add(lib);
1900                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1901                            }
1902                        } catch (FileNotFoundException e) {
1903                            Slog.w(TAG, "Library not found: " + lib);
1904                        } catch (IOException e) {
1905                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1906                                    + e.getMessage());
1907                        }
1908                    }
1909                }
1910            }
1911
1912            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1913
1914            // Gross hack for now: we know this file doesn't contain any
1915            // code, so don't dexopt it to avoid the resulting log spew.
1916            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1917
1918            // Gross hack for now: we know this file is only part of
1919            // the boot class path for art, so don't dexopt it to
1920            // avoid the resulting log spew.
1921            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1922
1923            /**
1924             * There are a number of commands implemented in Java, which
1925             * we currently need to do the dexopt on so that they can be
1926             * run from a non-root shell.
1927             */
1928            String[] frameworkFiles = frameworkDir.list();
1929            if (frameworkFiles != null) {
1930                // TODO: We could compile these only for the most preferred ABI. We should
1931                // first double check that the dex files for these commands are not referenced
1932                // by other system apps.
1933                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1934                    for (int i=0; i<frameworkFiles.length; i++) {
1935                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1936                        String path = libPath.getPath();
1937                        // Skip the file if we already did it.
1938                        if (alreadyDexOpted.contains(path)) {
1939                            continue;
1940                        }
1941                        // Skip the file if it is not a type we want to dexopt.
1942                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1943                            continue;
1944                        }
1945                        try {
1946                            int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false);
1947                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1948                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1949                            }
1950                        } catch (FileNotFoundException e) {
1951                            Slog.w(TAG, "Jar not found: " + path);
1952                        } catch (IOException e) {
1953                            Slog.w(TAG, "Exception reading jar: " + path, e);
1954                        }
1955                    }
1956                }
1957            }
1958
1959            // Collect vendor overlay packages.
1960            // (Do this before scanning any apps.)
1961            // For security and version matching reason, only consider
1962            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1963            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1964            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1965                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
1966
1967            // Find base frameworks (resource packages without code).
1968            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1969                    | PackageParser.PARSE_IS_SYSTEM_DIR
1970                    | PackageParser.PARSE_IS_PRIVILEGED,
1971                    scanFlags | SCAN_NO_DEX, 0);
1972
1973            // Collected privileged system packages.
1974            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1975            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1976                    | PackageParser.PARSE_IS_SYSTEM_DIR
1977                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
1978
1979            // Collect ordinary system packages.
1980            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
1981            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1982                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1983
1984            // Collect all vendor packages.
1985            File vendorAppDir = new File("/vendor/app");
1986            try {
1987                vendorAppDir = vendorAppDir.getCanonicalFile();
1988            } catch (IOException e) {
1989                // failed to look up canonical path, continue with original one
1990            }
1991            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1992                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1993
1994            // Collect all OEM packages.
1995            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
1996            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
1997                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1998
1999            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
2000            mInstaller.moveFiles();
2001
2002            // Prune any system packages that no longer exist.
2003            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2004            final ArrayMap<String, File> expectingBetter = new ArrayMap<>();
2005            if (!mOnlyCore) {
2006                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2007                while (psit.hasNext()) {
2008                    PackageSetting ps = psit.next();
2009
2010                    /*
2011                     * If this is not a system app, it can't be a
2012                     * disable system app.
2013                     */
2014                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2015                        continue;
2016                    }
2017
2018                    /*
2019                     * If the package is scanned, it's not erased.
2020                     */
2021                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2022                    if (scannedPkg != null) {
2023                        /*
2024                         * If the system app is both scanned and in the
2025                         * disabled packages list, then it must have been
2026                         * added via OTA. Remove it from the currently
2027                         * scanned package so the previously user-installed
2028                         * application can be scanned.
2029                         */
2030                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2031                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2032                                    + ps.name + "; removing system app.  Last known codePath="
2033                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2034                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2035                                    + scannedPkg.mVersionCode);
2036                            removePackageLI(ps, true);
2037                            expectingBetter.put(ps.name, ps.codePath);
2038                        }
2039
2040                        continue;
2041                    }
2042
2043                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2044                        psit.remove();
2045                        logCriticalInfo(Log.WARN, "System package " + ps.name
2046                                + " no longer exists; wiping its data");
2047                        removeDataDirsLI(null, ps.name);
2048                    } else {
2049                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2050                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2051                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2052                        }
2053                    }
2054                }
2055            }
2056
2057            //look for any incomplete package installations
2058            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2059            //clean up list
2060            for(int i = 0; i < deletePkgsList.size(); i++) {
2061                //clean up here
2062                cleanupInstallFailedPackage(deletePkgsList.get(i));
2063            }
2064            //delete tmp files
2065            deleteTempPackageFiles();
2066
2067            // Remove any shared userIDs that have no associated packages
2068            mSettings.pruneSharedUsersLPw();
2069
2070            if (!mOnlyCore) {
2071                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2072                        SystemClock.uptimeMillis());
2073                scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2074
2075                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2076                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2077
2078                /**
2079                 * Remove disable package settings for any updated system
2080                 * apps that were removed via an OTA. If they're not a
2081                 * previously-updated app, remove them completely.
2082                 * Otherwise, just revoke their system-level permissions.
2083                 */
2084                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2085                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2086                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2087
2088                    String msg;
2089                    if (deletedPkg == null) {
2090                        msg = "Updated system package " + deletedAppName
2091                                + " no longer exists; wiping its data";
2092                        removeDataDirsLI(null, deletedAppName);
2093                    } else {
2094                        msg = "Updated system app + " + deletedAppName
2095                                + " no longer present; removing system privileges for "
2096                                + deletedAppName;
2097
2098                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2099
2100                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2101                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2102                    }
2103                    logCriticalInfo(Log.WARN, msg);
2104                }
2105
2106                /**
2107                 * Make sure all system apps that we expected to appear on
2108                 * the userdata partition actually showed up. If they never
2109                 * appeared, crawl back and revive the system version.
2110                 */
2111                for (int i = 0; i < expectingBetter.size(); i++) {
2112                    final String packageName = expectingBetter.keyAt(i);
2113                    if (!mPackages.containsKey(packageName)) {
2114                        final File scanFile = expectingBetter.valueAt(i);
2115
2116                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2117                                + " but never showed up; reverting to system");
2118
2119                        final int reparseFlags;
2120                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2121                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2122                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2123                                    | PackageParser.PARSE_IS_PRIVILEGED;
2124                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2125                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2126                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2127                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2128                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2129                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2130                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2131                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2132                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2133                        } else {
2134                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2135                            continue;
2136                        }
2137
2138                        mSettings.enableSystemPackageLPw(packageName);
2139
2140                        try {
2141                            scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
2142                        } catch (PackageManagerException e) {
2143                            Slog.e(TAG, "Failed to parse original system package: "
2144                                    + e.getMessage());
2145                        }
2146                    }
2147                }
2148            }
2149
2150            // Now that we know all of the shared libraries, update all clients to have
2151            // the correct library paths.
2152            updateAllSharedLibrariesLPw();
2153
2154            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2155                // NOTE: We ignore potential failures here during a system scan (like
2156                // the rest of the commands above) because there's precious little we
2157                // can do about it. A settings error is reported, though.
2158                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2159                        false /* force dexopt */, false /* defer dexopt */);
2160            }
2161
2162            // Now that we know all the packages we are keeping,
2163            // read and update their last usage times.
2164            mPackageUsage.readLP();
2165
2166            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2167                    SystemClock.uptimeMillis());
2168            Slog.i(TAG, "Time to scan packages: "
2169                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2170                    + " seconds");
2171
2172            // If the platform SDK has changed since the last time we booted,
2173            // we need to re-grant app permission to catch any new ones that
2174            // appear.  This is really a hack, and means that apps can in some
2175            // cases get permissions that the user didn't initially explicitly
2176            // allow...  it would be nice to have some better way to handle
2177            // this situation.
2178            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
2179                    != mSdkVersion;
2180            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
2181                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
2182                    + "; regranting permissions for internal storage");
2183            mSettings.mInternalSdkPlatform = mSdkVersion;
2184
2185            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
2186                    | (regrantPermissions
2187                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
2188                            : 0));
2189
2190            // If this is the first boot, and it is a normal boot, then
2191            // we need to initialize the default preferred apps.
2192            if (!mRestoredSettings && !onlyCore) {
2193                mSettings.applyDefaultPreferredAppsLPw(this, UserHandle.USER_OWNER);
2194                applyFactoryDefaultBrowserLPw(UserHandle.USER_OWNER);
2195            }
2196
2197            // If this is first boot after an OTA, and a normal boot, then
2198            // we need to clear code cache directories.
2199            mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint);
2200            if (mIsUpgrade && !onlyCore) {
2201                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2202                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2203                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2204                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2205                }
2206                mSettings.mFingerprint = Build.FINGERPRINT;
2207            }
2208
2209            primeDomainVerificationsLPw();
2210            checkDefaultBrowser();
2211
2212            // All the changes are done during package scanning.
2213            mSettings.updateInternalDatabaseVersion();
2214
2215            // can downgrade to reader
2216            mSettings.writeLPr();
2217
2218            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2219                    SystemClock.uptimeMillis());
2220
2221            mRequiredVerifierPackage = getRequiredVerifierLPr();
2222
2223            mInstallerService = new PackageInstallerService(context, this);
2224
2225            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2226            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2227                    mIntentFilterVerifierComponent);
2228
2229        } // synchronized (mPackages)
2230        } // synchronized (mInstallLock)
2231
2232        // Now after opening every single application zip, make sure they
2233        // are all flushed.  Not really needed, but keeps things nice and
2234        // tidy.
2235        Runtime.getRuntime().gc();
2236
2237        // Expose private service for system components to use.
2238        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2239    }
2240
2241    @Override
2242    public boolean isFirstBoot() {
2243        return !mRestoredSettings;
2244    }
2245
2246    @Override
2247    public boolean isOnlyCoreApps() {
2248        return mOnlyCore;
2249    }
2250
2251    @Override
2252    public boolean isUpgrade() {
2253        return mIsUpgrade;
2254    }
2255
2256    private String getRequiredVerifierLPr() {
2257        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2258        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2259                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
2260
2261        String requiredVerifier = null;
2262
2263        final int N = receivers.size();
2264        for (int i = 0; i < N; i++) {
2265            final ResolveInfo info = receivers.get(i);
2266
2267            if (info.activityInfo == null) {
2268                continue;
2269            }
2270
2271            final String packageName = info.activityInfo.packageName;
2272
2273            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2274                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2275                continue;
2276            }
2277
2278            if (requiredVerifier != null) {
2279                throw new RuntimeException("There can be only one required verifier");
2280            }
2281
2282            requiredVerifier = packageName;
2283        }
2284
2285        return requiredVerifier;
2286    }
2287
2288    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2289        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2290        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2291                PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */);
2292
2293        ComponentName verifierComponentName = null;
2294
2295        int priority = -1000;
2296        final int N = receivers.size();
2297        for (int i = 0; i < N; i++) {
2298            final ResolveInfo info = receivers.get(i);
2299
2300            if (info.activityInfo == null) {
2301                continue;
2302            }
2303
2304            final String packageName = info.activityInfo.packageName;
2305
2306            final PackageSetting ps = mSettings.mPackages.get(packageName);
2307            if (ps == null) {
2308                continue;
2309            }
2310
2311            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2312                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2313                continue;
2314            }
2315
2316            // Select the IntentFilterVerifier with the highest priority
2317            if (priority < info.priority) {
2318                priority = info.priority;
2319                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2320                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2321                        + verifierComponentName + " with priority: " + info.priority);
2322            }
2323        }
2324
2325        return verifierComponentName;
2326    }
2327
2328    private void primeDomainVerificationsLPw() {
2329        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Start priming domain verifications");
2330        boolean updated = false;
2331        ArraySet<String> allHostsSet = new ArraySet<>();
2332        for (PackageParser.Package pkg : mPackages.values()) {
2333            final String packageName = pkg.packageName;
2334            if (!hasDomainURLs(pkg)) {
2335                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "No priming domain verifications for " +
2336                            "package with no domain URLs: " + packageName);
2337                continue;
2338            }
2339            if (!pkg.isSystemApp()) {
2340                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2341                        "No priming domain verifications for a non system package : " +
2342                                packageName);
2343                continue;
2344            }
2345            for (PackageParser.Activity a : pkg.activities) {
2346                for (ActivityIntentInfo filter : a.intents) {
2347                    if (hasValidDomains(filter)) {
2348                        allHostsSet.addAll(filter.getHostsList());
2349                    }
2350                }
2351            }
2352            if (allHostsSet.size() == 0) {
2353                allHostsSet.add("*");
2354            }
2355            ArrayList<String> allHostsList = new ArrayList<>(allHostsSet);
2356            IntentFilterVerificationInfo ivi =
2357                    mSettings.createIntentFilterVerificationIfNeededLPw(packageName, allHostsList);
2358            if (ivi != null) {
2359                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2360                        "Priming domain verifications for package: " + packageName +
2361                        " with hosts:" + ivi.getDomainsString());
2362                ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
2363                updated = true;
2364            }
2365            else {
2366                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2367                        "No priming domain verifications for package: " + packageName);
2368            }
2369            allHostsSet.clear();
2370        }
2371        if (updated) {
2372            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2373                    "Will need to write primed domain verifications");
2374        }
2375        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "End priming domain verifications");
2376    }
2377
2378    private void applyFactoryDefaultBrowserLPw(int userId) {
2379        // The default browser app's package name is stored in a string resource,
2380        // with a product-specific overlay used for vendor customization.
2381        String browserPkg = mContext.getResources().getString(
2382                com.android.internal.R.string.default_browser);
2383        if (browserPkg != null) {
2384            // non-empty string => required to be a known package
2385            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2386            if (ps == null) {
2387                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2388                browserPkg = null;
2389            } else {
2390                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2391            }
2392        }
2393
2394        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2395        // default.  If there's more than one, just leave everything alone.
2396        if (browserPkg == null) {
2397            calculateDefaultBrowserLPw(userId);
2398        }
2399    }
2400
2401    private void calculateDefaultBrowserLPw(int userId) {
2402        List<String> allBrowsers = resolveAllBrowserApps(userId);
2403        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2404        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2405    }
2406
2407    private List<String> resolveAllBrowserApps(int userId) {
2408        // Match all generic http: browser apps
2409        Intent intent = new Intent();
2410        intent.setAction(Intent.ACTION_VIEW);
2411        intent.addCategory(Intent.CATEGORY_BROWSABLE);
2412        intent.setData(Uri.parse("http:"));
2413
2414        // Resolve that intent and check that the handleAllWebDataURI boolean is set
2415        List<ResolveInfo> list = queryIntentActivities(intent, null, 0, userId);
2416
2417        final int count = list.size();
2418        List<String> result = new ArrayList<String>(count);
2419        for (int i=0; i<count; i++) {
2420            ResolveInfo info = list.get(i);
2421            if (info.activityInfo == null
2422                    || !info.handleAllWebDataURI
2423                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2424                    || result.contains(info.activityInfo.packageName)) {
2425                continue;
2426            }
2427            result.add(info.activityInfo.packageName);
2428        }
2429
2430        return result;
2431    }
2432
2433    private void checkDefaultBrowser() {
2434        final int myUserId = UserHandle.myUserId();
2435        final String packageName = getDefaultBrowserPackageName(myUserId);
2436        if (packageName != null) {
2437            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2438            if (info == null) {
2439                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2440                synchronized (mPackages) {
2441                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2442                }
2443            }
2444        }
2445    }
2446
2447    @Override
2448    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2449            throws RemoteException {
2450        try {
2451            return super.onTransact(code, data, reply, flags);
2452        } catch (RuntimeException e) {
2453            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2454                Slog.wtf(TAG, "Package Manager Crash", e);
2455            }
2456            throw e;
2457        }
2458    }
2459
2460    void cleanupInstallFailedPackage(PackageSetting ps) {
2461        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2462
2463        removeDataDirsLI(ps.volumeUuid, ps.name);
2464        if (ps.codePath != null) {
2465            if (ps.codePath.isDirectory()) {
2466                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2467            } else {
2468                ps.codePath.delete();
2469            }
2470        }
2471        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2472            if (ps.resourcePath.isDirectory()) {
2473                FileUtils.deleteContents(ps.resourcePath);
2474            }
2475            ps.resourcePath.delete();
2476        }
2477        mSettings.removePackageLPw(ps.name);
2478    }
2479
2480    static int[] appendInts(int[] cur, int[] add) {
2481        if (add == null) return cur;
2482        if (cur == null) return add;
2483        final int N = add.length;
2484        for (int i=0; i<N; i++) {
2485            cur = appendInt(cur, add[i]);
2486        }
2487        return cur;
2488    }
2489
2490    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2491        if (!sUserManager.exists(userId)) return null;
2492        final PackageSetting ps = (PackageSetting) p.mExtras;
2493        if (ps == null) {
2494            return null;
2495        }
2496
2497        final PermissionsState permissionsState = ps.getPermissionsState();
2498
2499        final int[] gids = permissionsState.computeGids(userId);
2500        final Set<String> permissions = permissionsState.getPermissions(userId);
2501        final PackageUserState state = ps.readUserState(userId);
2502
2503        return PackageParser.generatePackageInfo(p, gids, flags,
2504                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2505    }
2506
2507    @Override
2508    public boolean isPackageFrozen(String packageName) {
2509        synchronized (mPackages) {
2510            final PackageSetting ps = mSettings.mPackages.get(packageName);
2511            if (ps != null) {
2512                return ps.frozen;
2513            }
2514        }
2515        Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen");
2516        return true;
2517    }
2518
2519    @Override
2520    public boolean isPackageAvailable(String packageName, int userId) {
2521        if (!sUserManager.exists(userId)) return false;
2522        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2523        synchronized (mPackages) {
2524            PackageParser.Package p = mPackages.get(packageName);
2525            if (p != null) {
2526                final PackageSetting ps = (PackageSetting) p.mExtras;
2527                if (ps != null) {
2528                    final PackageUserState state = ps.readUserState(userId);
2529                    if (state != null) {
2530                        return PackageParser.isAvailable(state);
2531                    }
2532                }
2533            }
2534        }
2535        return false;
2536    }
2537
2538    @Override
2539    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2540        if (!sUserManager.exists(userId)) return null;
2541        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2542        // reader
2543        synchronized (mPackages) {
2544            PackageParser.Package p = mPackages.get(packageName);
2545            if (DEBUG_PACKAGE_INFO)
2546                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2547            if (p != null) {
2548                return generatePackageInfo(p, flags, userId);
2549            }
2550            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2551                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2552            }
2553        }
2554        return null;
2555    }
2556
2557    @Override
2558    public String[] currentToCanonicalPackageNames(String[] names) {
2559        String[] out = new String[names.length];
2560        // reader
2561        synchronized (mPackages) {
2562            for (int i=names.length-1; i>=0; i--) {
2563                PackageSetting ps = mSettings.mPackages.get(names[i]);
2564                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2565            }
2566        }
2567        return out;
2568    }
2569
2570    @Override
2571    public String[] canonicalToCurrentPackageNames(String[] names) {
2572        String[] out = new String[names.length];
2573        // reader
2574        synchronized (mPackages) {
2575            for (int i=names.length-1; i>=0; i--) {
2576                String cur = mSettings.mRenamedPackages.get(names[i]);
2577                out[i] = cur != null ? cur : names[i];
2578            }
2579        }
2580        return out;
2581    }
2582
2583    @Override
2584    public int getPackageUid(String packageName, int userId) {
2585        if (!sUserManager.exists(userId)) return -1;
2586        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2587
2588        // reader
2589        synchronized (mPackages) {
2590            PackageParser.Package p = mPackages.get(packageName);
2591            if(p != null) {
2592                return UserHandle.getUid(userId, p.applicationInfo.uid);
2593            }
2594            PackageSetting ps = mSettings.mPackages.get(packageName);
2595            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2596                return -1;
2597            }
2598            p = ps.pkg;
2599            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2600        }
2601    }
2602
2603    @Override
2604    public int[] getPackageGids(String packageName, int userId) throws RemoteException {
2605        if (!sUserManager.exists(userId)) {
2606            return null;
2607        }
2608
2609        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2610                "getPackageGids");
2611
2612        // reader
2613        synchronized (mPackages) {
2614            PackageParser.Package p = mPackages.get(packageName);
2615            if (DEBUG_PACKAGE_INFO) {
2616                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2617            }
2618            if (p != null) {
2619                PackageSetting ps = (PackageSetting) p.mExtras;
2620                return ps.getPermissionsState().computeGids(userId);
2621            }
2622        }
2623
2624        return null;
2625    }
2626
2627    @Override
2628    public int getMountExternalMode(int uid) {
2629        if (Process.isIsolated(uid)) {
2630            return Zygote.MOUNT_EXTERNAL_NONE;
2631        } else {
2632            if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_GRANTED) {
2633                return Zygote.MOUNT_EXTERNAL_WRITE;
2634            } else if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_GRANTED) {
2635                return Zygote.MOUNT_EXTERNAL_READ;
2636            } else {
2637                return Zygote.MOUNT_EXTERNAL_DEFAULT;
2638            }
2639        }
2640    }
2641
2642    static PermissionInfo generatePermissionInfo(
2643            BasePermission bp, int flags) {
2644        if (bp.perm != null) {
2645            return PackageParser.generatePermissionInfo(bp.perm, flags);
2646        }
2647        PermissionInfo pi = new PermissionInfo();
2648        pi.name = bp.name;
2649        pi.packageName = bp.sourcePackage;
2650        pi.nonLocalizedLabel = bp.name;
2651        pi.protectionLevel = bp.protectionLevel;
2652        return pi;
2653    }
2654
2655    @Override
2656    public PermissionInfo getPermissionInfo(String name, int flags) {
2657        // reader
2658        synchronized (mPackages) {
2659            final BasePermission p = mSettings.mPermissions.get(name);
2660            if (p != null) {
2661                return generatePermissionInfo(p, flags);
2662            }
2663            return null;
2664        }
2665    }
2666
2667    @Override
2668    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2669        // reader
2670        synchronized (mPackages) {
2671            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2672            for (BasePermission p : mSettings.mPermissions.values()) {
2673                if (group == null) {
2674                    if (p.perm == null || p.perm.info.group == null) {
2675                        out.add(generatePermissionInfo(p, flags));
2676                    }
2677                } else {
2678                    if (p.perm != null && group.equals(p.perm.info.group)) {
2679                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2680                    }
2681                }
2682            }
2683
2684            if (out.size() > 0) {
2685                return out;
2686            }
2687            return mPermissionGroups.containsKey(group) ? out : null;
2688        }
2689    }
2690
2691    @Override
2692    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2693        // reader
2694        synchronized (mPackages) {
2695            return PackageParser.generatePermissionGroupInfo(
2696                    mPermissionGroups.get(name), flags);
2697        }
2698    }
2699
2700    @Override
2701    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2702        // reader
2703        synchronized (mPackages) {
2704            final int N = mPermissionGroups.size();
2705            ArrayList<PermissionGroupInfo> out
2706                    = new ArrayList<PermissionGroupInfo>(N);
2707            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2708                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2709            }
2710            return out;
2711        }
2712    }
2713
2714    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2715            int userId) {
2716        if (!sUserManager.exists(userId)) return null;
2717        PackageSetting ps = mSettings.mPackages.get(packageName);
2718        if (ps != null) {
2719            if (ps.pkg == null) {
2720                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2721                        flags, userId);
2722                if (pInfo != null) {
2723                    return pInfo.applicationInfo;
2724                }
2725                return null;
2726            }
2727            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2728                    ps.readUserState(userId), userId);
2729        }
2730        return null;
2731    }
2732
2733    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2734            int userId) {
2735        if (!sUserManager.exists(userId)) return null;
2736        PackageSetting ps = mSettings.mPackages.get(packageName);
2737        if (ps != null) {
2738            PackageParser.Package pkg = ps.pkg;
2739            if (pkg == null) {
2740                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2741                    return null;
2742                }
2743                // Only data remains, so we aren't worried about code paths
2744                pkg = new PackageParser.Package(packageName);
2745                pkg.applicationInfo.packageName = packageName;
2746                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2747                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2748                pkg.applicationInfo.dataDir = PackageManager.getDataDirForUser(ps.volumeUuid,
2749                        packageName, userId).getAbsolutePath();
2750                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2751                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2752            }
2753            return generatePackageInfo(pkg, flags, userId);
2754        }
2755        return null;
2756    }
2757
2758    @Override
2759    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2760        if (!sUserManager.exists(userId)) return null;
2761        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2762        // writer
2763        synchronized (mPackages) {
2764            PackageParser.Package p = mPackages.get(packageName);
2765            if (DEBUG_PACKAGE_INFO) Log.v(
2766                    TAG, "getApplicationInfo " + packageName
2767                    + ": " + p);
2768            if (p != null) {
2769                PackageSetting ps = mSettings.mPackages.get(packageName);
2770                if (ps == null) return null;
2771                // Note: isEnabledLP() does not apply here - always return info
2772                return PackageParser.generateApplicationInfo(
2773                        p, flags, ps.readUserState(userId), userId);
2774            }
2775            if ("android".equals(packageName)||"system".equals(packageName)) {
2776                return mAndroidApplication;
2777            }
2778            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2779                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2780            }
2781        }
2782        return null;
2783    }
2784
2785    @Override
2786    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
2787            final IPackageDataObserver observer) {
2788        mContext.enforceCallingOrSelfPermission(
2789                android.Manifest.permission.CLEAR_APP_CACHE, null);
2790        // Queue up an async operation since clearing cache may take a little while.
2791        mHandler.post(new Runnable() {
2792            public void run() {
2793                mHandler.removeCallbacks(this);
2794                int retCode = -1;
2795                synchronized (mInstallLock) {
2796                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2797                    if (retCode < 0) {
2798                        Slog.w(TAG, "Couldn't clear application caches");
2799                    }
2800                }
2801                if (observer != null) {
2802                    try {
2803                        observer.onRemoveCompleted(null, (retCode >= 0));
2804                    } catch (RemoteException e) {
2805                        Slog.w(TAG, "RemoveException when invoking call back");
2806                    }
2807                }
2808            }
2809        });
2810    }
2811
2812    @Override
2813    public void freeStorage(final String volumeUuid, final long freeStorageSize,
2814            final IntentSender pi) {
2815        mContext.enforceCallingOrSelfPermission(
2816                android.Manifest.permission.CLEAR_APP_CACHE, null);
2817        // Queue up an async operation since clearing cache may take a little while.
2818        mHandler.post(new Runnable() {
2819            public void run() {
2820                mHandler.removeCallbacks(this);
2821                int retCode = -1;
2822                synchronized (mInstallLock) {
2823                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2824                    if (retCode < 0) {
2825                        Slog.w(TAG, "Couldn't clear application caches");
2826                    }
2827                }
2828                if(pi != null) {
2829                    try {
2830                        // Callback via pending intent
2831                        int code = (retCode >= 0) ? 1 : 0;
2832                        pi.sendIntent(null, code, null,
2833                                null, null);
2834                    } catch (SendIntentException e1) {
2835                        Slog.i(TAG, "Failed to send pending intent");
2836                    }
2837                }
2838            }
2839        });
2840    }
2841
2842    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
2843        synchronized (mInstallLock) {
2844            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
2845                throw new IOException("Failed to free enough space");
2846            }
2847        }
2848    }
2849
2850    @Override
2851    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2852        if (!sUserManager.exists(userId)) return null;
2853        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2854        synchronized (mPackages) {
2855            PackageParser.Activity a = mActivities.mActivities.get(component);
2856
2857            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2858            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2859                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2860                if (ps == null) return null;
2861                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2862                        userId);
2863            }
2864            if (mResolveComponentName.equals(component)) {
2865                return PackageParser.generateActivityInfo(mResolveActivity, flags,
2866                        new PackageUserState(), userId);
2867            }
2868        }
2869        return null;
2870    }
2871
2872    @Override
2873    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2874            String resolvedType) {
2875        synchronized (mPackages) {
2876            PackageParser.Activity a = mActivities.mActivities.get(component);
2877            if (a == null) {
2878                return false;
2879            }
2880            for (int i=0; i<a.intents.size(); i++) {
2881                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2882                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2883                    return true;
2884                }
2885            }
2886            return false;
2887        }
2888    }
2889
2890    @Override
2891    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2892        if (!sUserManager.exists(userId)) return null;
2893        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
2894        synchronized (mPackages) {
2895            PackageParser.Activity a = mReceivers.mActivities.get(component);
2896            if (DEBUG_PACKAGE_INFO) Log.v(
2897                TAG, "getReceiverInfo " + component + ": " + a);
2898            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2899                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2900                if (ps == null) return null;
2901                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2902                        userId);
2903            }
2904        }
2905        return null;
2906    }
2907
2908    @Override
2909    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2910        if (!sUserManager.exists(userId)) return null;
2911        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
2912        synchronized (mPackages) {
2913            PackageParser.Service s = mServices.mServices.get(component);
2914            if (DEBUG_PACKAGE_INFO) Log.v(
2915                TAG, "getServiceInfo " + component + ": " + s);
2916            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2917                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2918                if (ps == null) return null;
2919                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2920                        userId);
2921            }
2922        }
2923        return null;
2924    }
2925
2926    @Override
2927    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2928        if (!sUserManager.exists(userId)) return null;
2929        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
2930        synchronized (mPackages) {
2931            PackageParser.Provider p = mProviders.mProviders.get(component);
2932            if (DEBUG_PACKAGE_INFO) Log.v(
2933                TAG, "getProviderInfo " + component + ": " + p);
2934            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2935                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2936                if (ps == null) return null;
2937                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2938                        userId);
2939            }
2940        }
2941        return null;
2942    }
2943
2944    @Override
2945    public String[] getSystemSharedLibraryNames() {
2946        Set<String> libSet;
2947        synchronized (mPackages) {
2948            libSet = mSharedLibraries.keySet();
2949            int size = libSet.size();
2950            if (size > 0) {
2951                String[] libs = new String[size];
2952                libSet.toArray(libs);
2953                return libs;
2954            }
2955        }
2956        return null;
2957    }
2958
2959    /**
2960     * @hide
2961     */
2962    PackageParser.Package findSharedNonSystemLibrary(String libName) {
2963        synchronized (mPackages) {
2964            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
2965            if (lib != null && lib.apk != null) {
2966                return mPackages.get(lib.apk);
2967            }
2968        }
2969        return null;
2970    }
2971
2972    @Override
2973    public FeatureInfo[] getSystemAvailableFeatures() {
2974        Collection<FeatureInfo> featSet;
2975        synchronized (mPackages) {
2976            featSet = mAvailableFeatures.values();
2977            int size = featSet.size();
2978            if (size > 0) {
2979                FeatureInfo[] features = new FeatureInfo[size+1];
2980                featSet.toArray(features);
2981                FeatureInfo fi = new FeatureInfo();
2982                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2983                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2984                features[size] = fi;
2985                return features;
2986            }
2987        }
2988        return null;
2989    }
2990
2991    @Override
2992    public boolean hasSystemFeature(String name) {
2993        synchronized (mPackages) {
2994            return mAvailableFeatures.containsKey(name);
2995        }
2996    }
2997
2998    private void checkValidCaller(int uid, int userId) {
2999        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
3000            return;
3001
3002        throw new SecurityException("Caller uid=" + uid
3003                + " is not privileged to communicate with user=" + userId);
3004    }
3005
3006    @Override
3007    public int checkPermission(String permName, String pkgName, int userId) {
3008        if (!sUserManager.exists(userId)) {
3009            return PackageManager.PERMISSION_DENIED;
3010        }
3011
3012        synchronized (mPackages) {
3013            final PackageParser.Package p = mPackages.get(pkgName);
3014            if (p != null && p.mExtras != null) {
3015                final PackageSetting ps = (PackageSetting) p.mExtras;
3016                if (ps.getPermissionsState().hasPermission(permName, userId)) {
3017                    return PackageManager.PERMISSION_GRANTED;
3018                }
3019            }
3020        }
3021
3022        return PackageManager.PERMISSION_DENIED;
3023    }
3024
3025    @Override
3026    public int checkUidPermission(String permName, int uid) {
3027        final int userId = UserHandle.getUserId(uid);
3028
3029        if (!sUserManager.exists(userId)) {
3030            return PackageManager.PERMISSION_DENIED;
3031        }
3032
3033        synchronized (mPackages) {
3034            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3035            if (obj != null) {
3036                final SettingBase ps = (SettingBase) obj;
3037                if (ps.getPermissionsState().hasPermission(permName, userId)) {
3038                    return PackageManager.PERMISSION_GRANTED;
3039                }
3040            } else {
3041                ArraySet<String> perms = mSystemPermissions.get(uid);
3042                if (perms != null && perms.contains(permName)) {
3043                    return PackageManager.PERMISSION_GRANTED;
3044                }
3045            }
3046        }
3047
3048        return PackageManager.PERMISSION_DENIED;
3049    }
3050
3051    /**
3052     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3053     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3054     * @param checkShell TODO(yamasani):
3055     * @param message the message to log on security exception
3056     */
3057    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3058            boolean checkShell, String message) {
3059        if (userId < 0) {
3060            throw new IllegalArgumentException("Invalid userId " + userId);
3061        }
3062        if (checkShell) {
3063            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3064        }
3065        if (userId == UserHandle.getUserId(callingUid)) return;
3066        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3067            if (requireFullPermission) {
3068                mContext.enforceCallingOrSelfPermission(
3069                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3070            } else {
3071                try {
3072                    mContext.enforceCallingOrSelfPermission(
3073                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3074                } catch (SecurityException se) {
3075                    mContext.enforceCallingOrSelfPermission(
3076                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3077                }
3078            }
3079        }
3080    }
3081
3082    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3083        if (callingUid == Process.SHELL_UID) {
3084            if (userHandle >= 0
3085                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3086                throw new SecurityException("Shell does not have permission to access user "
3087                        + userHandle);
3088            } else if (userHandle < 0) {
3089                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3090                        + Debug.getCallers(3));
3091            }
3092        }
3093    }
3094
3095    private BasePermission findPermissionTreeLP(String permName) {
3096        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3097            if (permName.startsWith(bp.name) &&
3098                    permName.length() > bp.name.length() &&
3099                    permName.charAt(bp.name.length()) == '.') {
3100                return bp;
3101            }
3102        }
3103        return null;
3104    }
3105
3106    private BasePermission checkPermissionTreeLP(String permName) {
3107        if (permName != null) {
3108            BasePermission bp = findPermissionTreeLP(permName);
3109            if (bp != null) {
3110                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3111                    return bp;
3112                }
3113                throw new SecurityException("Calling uid "
3114                        + Binder.getCallingUid()
3115                        + " is not allowed to add to permission tree "
3116                        + bp.name + " owned by uid " + bp.uid);
3117            }
3118        }
3119        throw new SecurityException("No permission tree found for " + permName);
3120    }
3121
3122    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3123        if (s1 == null) {
3124            return s2 == null;
3125        }
3126        if (s2 == null) {
3127            return false;
3128        }
3129        if (s1.getClass() != s2.getClass()) {
3130            return false;
3131        }
3132        return s1.equals(s2);
3133    }
3134
3135    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3136        if (pi1.icon != pi2.icon) return false;
3137        if (pi1.logo != pi2.logo) return false;
3138        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3139        if (!compareStrings(pi1.name, pi2.name)) return false;
3140        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3141        // We'll take care of setting this one.
3142        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3143        // These are not currently stored in settings.
3144        //if (!compareStrings(pi1.group, pi2.group)) return false;
3145        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3146        //if (pi1.labelRes != pi2.labelRes) return false;
3147        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3148        return true;
3149    }
3150
3151    int permissionInfoFootprint(PermissionInfo info) {
3152        int size = info.name.length();
3153        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3154        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3155        return size;
3156    }
3157
3158    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3159        int size = 0;
3160        for (BasePermission perm : mSettings.mPermissions.values()) {
3161            if (perm.uid == tree.uid) {
3162                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3163            }
3164        }
3165        return size;
3166    }
3167
3168    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3169        // We calculate the max size of permissions defined by this uid and throw
3170        // if that plus the size of 'info' would exceed our stated maximum.
3171        if (tree.uid != Process.SYSTEM_UID) {
3172            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3173            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3174                throw new SecurityException("Permission tree size cap exceeded");
3175            }
3176        }
3177    }
3178
3179    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3180        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3181            throw new SecurityException("Label must be specified in permission");
3182        }
3183        BasePermission tree = checkPermissionTreeLP(info.name);
3184        BasePermission bp = mSettings.mPermissions.get(info.name);
3185        boolean added = bp == null;
3186        boolean changed = true;
3187        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3188        if (added) {
3189            enforcePermissionCapLocked(info, tree);
3190            bp = new BasePermission(info.name, tree.sourcePackage,
3191                    BasePermission.TYPE_DYNAMIC);
3192        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3193            throw new SecurityException(
3194                    "Not allowed to modify non-dynamic permission "
3195                    + info.name);
3196        } else {
3197            if (bp.protectionLevel == fixedLevel
3198                    && bp.perm.owner.equals(tree.perm.owner)
3199                    && bp.uid == tree.uid
3200                    && comparePermissionInfos(bp.perm.info, info)) {
3201                changed = false;
3202            }
3203        }
3204        bp.protectionLevel = fixedLevel;
3205        info = new PermissionInfo(info);
3206        info.protectionLevel = fixedLevel;
3207        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3208        bp.perm.info.packageName = tree.perm.info.packageName;
3209        bp.uid = tree.uid;
3210        if (added) {
3211            mSettings.mPermissions.put(info.name, bp);
3212        }
3213        if (changed) {
3214            if (!async) {
3215                mSettings.writeLPr();
3216            } else {
3217                scheduleWriteSettingsLocked();
3218            }
3219        }
3220        return added;
3221    }
3222
3223    @Override
3224    public boolean addPermission(PermissionInfo info) {
3225        synchronized (mPackages) {
3226            return addPermissionLocked(info, false);
3227        }
3228    }
3229
3230    @Override
3231    public boolean addPermissionAsync(PermissionInfo info) {
3232        synchronized (mPackages) {
3233            return addPermissionLocked(info, true);
3234        }
3235    }
3236
3237    @Override
3238    public void removePermission(String name) {
3239        synchronized (mPackages) {
3240            checkPermissionTreeLP(name);
3241            BasePermission bp = mSettings.mPermissions.get(name);
3242            if (bp != null) {
3243                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3244                    throw new SecurityException(
3245                            "Not allowed to modify non-dynamic permission "
3246                            + name);
3247                }
3248                mSettings.mPermissions.remove(name);
3249                mSettings.writeLPr();
3250            }
3251        }
3252    }
3253
3254    private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg,
3255            BasePermission bp) {
3256        int index = pkg.requestedPermissions.indexOf(bp.name);
3257        if (index == -1) {
3258            throw new SecurityException("Package " + pkg.packageName
3259                    + " has not requested permission " + bp.name);
3260        }
3261        if (!bp.isRuntime()) {
3262            throw new SecurityException("Permission " + bp.name
3263                    + " is not a changeable permission type");
3264        }
3265    }
3266
3267    @Override
3268    public void grantRuntimePermission(String packageName, String name, final int userId) {
3269        if (!sUserManager.exists(userId)) {
3270            Log.e(TAG, "No such user:" + userId);
3271            return;
3272        }
3273
3274        mContext.enforceCallingOrSelfPermission(
3275                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3276                "grantRuntimePermission");
3277
3278        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3279                "grantRuntimePermission");
3280
3281        final int uid;
3282        final SettingBase sb;
3283
3284        synchronized (mPackages) {
3285            final PackageParser.Package pkg = mPackages.get(packageName);
3286            if (pkg == null) {
3287                throw new IllegalArgumentException("Unknown package: " + packageName);
3288            }
3289
3290            final BasePermission bp = mSettings.mPermissions.get(name);
3291            if (bp == null) {
3292                throw new IllegalArgumentException("Unknown permission: " + name);
3293            }
3294
3295            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3296
3297            uid = pkg.applicationInfo.uid;
3298            sb = (SettingBase) pkg.mExtras;
3299            if (sb == null) {
3300                throw new IllegalArgumentException("Unknown package: " + packageName);
3301            }
3302
3303            final PermissionsState permissionsState = sb.getPermissionsState();
3304
3305            final int flags = permissionsState.getPermissionFlags(name, userId);
3306            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3307                throw new SecurityException("Cannot grant system fixed permission: "
3308                        + name + " for package: " + packageName);
3309            }
3310
3311            final int result = permissionsState.grantRuntimePermission(bp, userId);
3312            switch (result) {
3313                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3314                    return;
3315                }
3316
3317                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3318                    mHandler.post(new Runnable() {
3319                        @Override
3320                        public void run() {
3321                            killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED);
3322                        }
3323                    });
3324                } break;
3325            }
3326
3327            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3328
3329            // Not critical if that is lost - app has to request again.
3330            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3331        }
3332
3333        if (READ_EXTERNAL_STORAGE.equals(name)
3334                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3335            final long token = Binder.clearCallingIdentity();
3336            try {
3337                final StorageManager storage = mContext.getSystemService(StorageManager.class);
3338                storage.remountUid(uid);
3339            } finally {
3340                Binder.restoreCallingIdentity(token);
3341            }
3342        }
3343    }
3344
3345    @Override
3346    public void revokeRuntimePermission(String packageName, String name, int userId) {
3347        if (!sUserManager.exists(userId)) {
3348            Log.e(TAG, "No such user:" + userId);
3349            return;
3350        }
3351
3352        mContext.enforceCallingOrSelfPermission(
3353                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3354                "revokeRuntimePermission");
3355
3356        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3357                "revokeRuntimePermission");
3358
3359        final SettingBase sb;
3360
3361        synchronized (mPackages) {
3362            final PackageParser.Package pkg = mPackages.get(packageName);
3363            if (pkg == null) {
3364                throw new IllegalArgumentException("Unknown package: " + packageName);
3365            }
3366
3367            final BasePermission bp = mSettings.mPermissions.get(name);
3368            if (bp == null) {
3369                throw new IllegalArgumentException("Unknown permission: " + name);
3370            }
3371
3372            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3373
3374            sb = (SettingBase) pkg.mExtras;
3375            if (sb == null) {
3376                throw new IllegalArgumentException("Unknown package: " + packageName);
3377            }
3378
3379            final PermissionsState permissionsState = sb.getPermissionsState();
3380
3381            final int flags = permissionsState.getPermissionFlags(name, userId);
3382            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3383                throw new SecurityException("Cannot revoke system fixed permission: "
3384                        + name + " for package: " + packageName);
3385            }
3386
3387            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3388                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3389                return;
3390            }
3391
3392            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3393
3394            // Critical, after this call app should never have the permission.
3395            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3396        }
3397
3398        killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3399    }
3400
3401    @Override
3402    public void resetRuntimePermissions() {
3403        mContext.enforceCallingOrSelfPermission(
3404                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3405                "revokeRuntimePermission");
3406
3407        int callingUid = Binder.getCallingUid();
3408        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3409            mContext.enforceCallingOrSelfPermission(
3410                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3411                    "resetRuntimePermissions");
3412        }
3413
3414        final int[] userIds;
3415
3416        synchronized (mPackages) {
3417            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3418            final int userCount = UserManagerService.getInstance().getUserIds().length;
3419            userIds = Arrays.copyOf(UserManagerService.getInstance().getUserIds(), userCount);
3420        }
3421
3422        for (int userId : userIds) {
3423            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
3424        }
3425    }
3426
3427    @Override
3428    public int getPermissionFlags(String name, String packageName, int userId) {
3429        if (!sUserManager.exists(userId)) {
3430            return 0;
3431        }
3432
3433        mContext.enforceCallingOrSelfPermission(
3434                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3435                "getPermissionFlags");
3436
3437        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3438                "getPermissionFlags");
3439
3440        synchronized (mPackages) {
3441            final PackageParser.Package pkg = mPackages.get(packageName);
3442            if (pkg == null) {
3443                throw new IllegalArgumentException("Unknown package: " + packageName);
3444            }
3445
3446            final BasePermission bp = mSettings.mPermissions.get(name);
3447            if (bp == null) {
3448                throw new IllegalArgumentException("Unknown permission: " + name);
3449            }
3450
3451            SettingBase sb = (SettingBase) pkg.mExtras;
3452            if (sb == null) {
3453                throw new IllegalArgumentException("Unknown package: " + packageName);
3454            }
3455
3456            PermissionsState permissionsState = sb.getPermissionsState();
3457            return permissionsState.getPermissionFlags(name, userId);
3458        }
3459    }
3460
3461    @Override
3462    public void updatePermissionFlags(String name, String packageName, int flagMask,
3463            int flagValues, int userId) {
3464        if (!sUserManager.exists(userId)) {
3465            return;
3466        }
3467
3468        mContext.enforceCallingOrSelfPermission(
3469                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3470                "updatePermissionFlags");
3471
3472        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3473                "updatePermissionFlags");
3474
3475        // Only the system can change system fixed flags.
3476        if (getCallingUid() != Process.SYSTEM_UID) {
3477            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3478            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3479        }
3480
3481        synchronized (mPackages) {
3482            final PackageParser.Package pkg = mPackages.get(packageName);
3483            if (pkg == null) {
3484                throw new IllegalArgumentException("Unknown package: " + packageName);
3485            }
3486
3487            final BasePermission bp = mSettings.mPermissions.get(name);
3488            if (bp == null) {
3489                throw new IllegalArgumentException("Unknown permission: " + name);
3490            }
3491
3492            SettingBase sb = (SettingBase) pkg.mExtras;
3493            if (sb == null) {
3494                throw new IllegalArgumentException("Unknown package: " + packageName);
3495            }
3496
3497            PermissionsState permissionsState = sb.getPermissionsState();
3498
3499            // Only the package manager can change flags for system component permissions.
3500            final int flags = permissionsState.getPermissionFlags(bp.name, userId);
3501            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3502                return;
3503            }
3504
3505            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3506
3507            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3508                // Install and runtime permissions are stored in different places,
3509                // so figure out what permission changed and persist the change.
3510                if (permissionsState.getInstallPermissionState(name) != null) {
3511                    scheduleWriteSettingsLocked();
3512                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3513                        || hadState) {
3514                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3515                }
3516            }
3517        }
3518    }
3519
3520    /**
3521     * Update the permission flags for all packages and runtime permissions of a user in order
3522     * to allow device or profile owner to remove POLICY_FIXED.
3523     */
3524    @Override
3525    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3526        if (!sUserManager.exists(userId)) {
3527            return;
3528        }
3529
3530        mContext.enforceCallingOrSelfPermission(
3531                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3532                "updatePermissionFlagsForAllApps");
3533
3534        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3535                "updatePermissionFlagsForAllApps");
3536
3537        // Only the system can change system fixed flags.
3538        if (getCallingUid() != Process.SYSTEM_UID) {
3539            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3540            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3541        }
3542
3543        synchronized (mPackages) {
3544            boolean changed = false;
3545            final int packageCount = mPackages.size();
3546            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
3547                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
3548                SettingBase sb = (SettingBase) pkg.mExtras;
3549                if (sb == null) {
3550                    continue;
3551                }
3552                PermissionsState permissionsState = sb.getPermissionsState();
3553                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
3554                        userId, flagMask, flagValues);
3555            }
3556            if (changed) {
3557                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3558            }
3559        }
3560    }
3561
3562    @Override
3563    public boolean shouldShowRequestPermissionRationale(String permissionName,
3564            String packageName, int userId) {
3565        if (UserHandle.getCallingUserId() != userId) {
3566            mContext.enforceCallingPermission(
3567                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3568                    "canShowRequestPermissionRationale for user " + userId);
3569        }
3570
3571        final int uid = getPackageUid(packageName, userId);
3572        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
3573            return false;
3574        }
3575
3576        if (checkPermission(permissionName, packageName, userId)
3577                == PackageManager.PERMISSION_GRANTED) {
3578            return false;
3579        }
3580
3581        final int flags;
3582
3583        final long identity = Binder.clearCallingIdentity();
3584        try {
3585            flags = getPermissionFlags(permissionName,
3586                    packageName, userId);
3587        } finally {
3588            Binder.restoreCallingIdentity(identity);
3589        }
3590
3591        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
3592                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
3593                | PackageManager.FLAG_PERMISSION_USER_FIXED;
3594
3595        if ((flags & fixedFlags) != 0) {
3596            return false;
3597        }
3598
3599        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
3600    }
3601
3602    void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) {
3603        BasePermission bp = mSettings.mPermissions.get(permission);
3604        if (bp == null) {
3605            throw new SecurityException("Missing " + permission + " permission");
3606        }
3607
3608        SettingBase sb = (SettingBase) pkg.mExtras;
3609        PermissionsState permissionsState = sb.getPermissionsState();
3610
3611        if (permissionsState.grantInstallPermission(bp) !=
3612                PermissionsState.PERMISSION_OPERATION_FAILURE) {
3613            scheduleWriteSettingsLocked();
3614        }
3615    }
3616
3617    @Override
3618    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3619        mContext.enforceCallingOrSelfPermission(
3620                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
3621                "addOnPermissionsChangeListener");
3622
3623        synchronized (mPackages) {
3624            mOnPermissionChangeListeners.addListenerLocked(listener);
3625        }
3626    }
3627
3628    @Override
3629    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3630        synchronized (mPackages) {
3631            mOnPermissionChangeListeners.removeListenerLocked(listener);
3632        }
3633    }
3634
3635    @Override
3636    public boolean isProtectedBroadcast(String actionName) {
3637        synchronized (mPackages) {
3638            return mProtectedBroadcasts.contains(actionName);
3639        }
3640    }
3641
3642    @Override
3643    public int checkSignatures(String pkg1, String pkg2) {
3644        synchronized (mPackages) {
3645            final PackageParser.Package p1 = mPackages.get(pkg1);
3646            final PackageParser.Package p2 = mPackages.get(pkg2);
3647            if (p1 == null || p1.mExtras == null
3648                    || p2 == null || p2.mExtras == null) {
3649                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3650            }
3651            return compareSignatures(p1.mSignatures, p2.mSignatures);
3652        }
3653    }
3654
3655    @Override
3656    public int checkUidSignatures(int uid1, int uid2) {
3657        // Map to base uids.
3658        uid1 = UserHandle.getAppId(uid1);
3659        uid2 = UserHandle.getAppId(uid2);
3660        // reader
3661        synchronized (mPackages) {
3662            Signature[] s1;
3663            Signature[] s2;
3664            Object obj = mSettings.getUserIdLPr(uid1);
3665            if (obj != null) {
3666                if (obj instanceof SharedUserSetting) {
3667                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3668                } else if (obj instanceof PackageSetting) {
3669                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3670                } else {
3671                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3672                }
3673            } else {
3674                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3675            }
3676            obj = mSettings.getUserIdLPr(uid2);
3677            if (obj != null) {
3678                if (obj instanceof SharedUserSetting) {
3679                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3680                } else if (obj instanceof PackageSetting) {
3681                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3682                } else {
3683                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3684                }
3685            } else {
3686                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3687            }
3688            return compareSignatures(s1, s2);
3689        }
3690    }
3691
3692    private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) {
3693        final long identity = Binder.clearCallingIdentity();
3694        try {
3695            if (sb instanceof SharedUserSetting) {
3696                SharedUserSetting sus = (SharedUserSetting) sb;
3697                final int packageCount = sus.packages.size();
3698                for (int i = 0; i < packageCount; i++) {
3699                    PackageSetting susPs = sus.packages.valueAt(i);
3700                    if (userId == UserHandle.USER_ALL) {
3701                        killApplication(susPs.pkg.packageName, susPs.appId, reason);
3702                    } else {
3703                        final int uid = UserHandle.getUid(userId, susPs.appId);
3704                        killUid(uid, reason);
3705                    }
3706                }
3707            } else if (sb instanceof PackageSetting) {
3708                PackageSetting ps = (PackageSetting) sb;
3709                if (userId == UserHandle.USER_ALL) {
3710                    killApplication(ps.pkg.packageName, ps.appId, reason);
3711                } else {
3712                    final int uid = UserHandle.getUid(userId, ps.appId);
3713                    killUid(uid, reason);
3714                }
3715            }
3716        } finally {
3717            Binder.restoreCallingIdentity(identity);
3718        }
3719    }
3720
3721    private static void killUid(int uid, String reason) {
3722        IActivityManager am = ActivityManagerNative.getDefault();
3723        if (am != null) {
3724            try {
3725                am.killUid(uid, reason);
3726            } catch (RemoteException e) {
3727                /* ignore - same process */
3728            }
3729        }
3730    }
3731
3732    /**
3733     * Compares two sets of signatures. Returns:
3734     * <br />
3735     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3736     * <br />
3737     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3738     * <br />
3739     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3740     * <br />
3741     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3742     * <br />
3743     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3744     */
3745    static int compareSignatures(Signature[] s1, Signature[] s2) {
3746        if (s1 == null) {
3747            return s2 == null
3748                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3749                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3750        }
3751
3752        if (s2 == null) {
3753            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3754        }
3755
3756        if (s1.length != s2.length) {
3757            return PackageManager.SIGNATURE_NO_MATCH;
3758        }
3759
3760        // Since both signature sets are of size 1, we can compare without HashSets.
3761        if (s1.length == 1) {
3762            return s1[0].equals(s2[0]) ?
3763                    PackageManager.SIGNATURE_MATCH :
3764                    PackageManager.SIGNATURE_NO_MATCH;
3765        }
3766
3767        ArraySet<Signature> set1 = new ArraySet<Signature>();
3768        for (Signature sig : s1) {
3769            set1.add(sig);
3770        }
3771        ArraySet<Signature> set2 = new ArraySet<Signature>();
3772        for (Signature sig : s2) {
3773            set2.add(sig);
3774        }
3775        // Make sure s2 contains all signatures in s1.
3776        if (set1.equals(set2)) {
3777            return PackageManager.SIGNATURE_MATCH;
3778        }
3779        return PackageManager.SIGNATURE_NO_MATCH;
3780    }
3781
3782    /**
3783     * If the database version for this type of package (internal storage or
3784     * external storage) is less than the version where package signatures
3785     * were updated, return true.
3786     */
3787    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3788        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
3789                DatabaseVersion.SIGNATURE_END_ENTITY))
3790                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
3791                        DatabaseVersion.SIGNATURE_END_ENTITY));
3792    }
3793
3794    /**
3795     * Used for backward compatibility to make sure any packages with
3796     * certificate chains get upgraded to the new style. {@code existingSigs}
3797     * will be in the old format (since they were stored on disk from before the
3798     * system upgrade) and {@code scannedSigs} will be in the newer format.
3799     */
3800    private int compareSignaturesCompat(PackageSignatures existingSigs,
3801            PackageParser.Package scannedPkg) {
3802        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
3803            return PackageManager.SIGNATURE_NO_MATCH;
3804        }
3805
3806        ArraySet<Signature> existingSet = new ArraySet<Signature>();
3807        for (Signature sig : existingSigs.mSignatures) {
3808            existingSet.add(sig);
3809        }
3810        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
3811        for (Signature sig : scannedPkg.mSignatures) {
3812            try {
3813                Signature[] chainSignatures = sig.getChainSignatures();
3814                for (Signature chainSig : chainSignatures) {
3815                    scannedCompatSet.add(chainSig);
3816                }
3817            } catch (CertificateEncodingException e) {
3818                scannedCompatSet.add(sig);
3819            }
3820        }
3821        /*
3822         * Make sure the expanded scanned set contains all signatures in the
3823         * existing one.
3824         */
3825        if (scannedCompatSet.equals(existingSet)) {
3826            // Migrate the old signatures to the new scheme.
3827            existingSigs.assignSignatures(scannedPkg.mSignatures);
3828            // The new KeySets will be re-added later in the scanning process.
3829            synchronized (mPackages) {
3830                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
3831            }
3832            return PackageManager.SIGNATURE_MATCH;
3833        }
3834        return PackageManager.SIGNATURE_NO_MATCH;
3835    }
3836
3837    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3838        if (isExternal(scannedPkg)) {
3839            return mSettings.isExternalDatabaseVersionOlderThan(
3840                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3841        } else {
3842            return mSettings.isInternalDatabaseVersionOlderThan(
3843                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3844        }
3845    }
3846
3847    private int compareSignaturesRecover(PackageSignatures existingSigs,
3848            PackageParser.Package scannedPkg) {
3849        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
3850            return PackageManager.SIGNATURE_NO_MATCH;
3851        }
3852
3853        String msg = null;
3854        try {
3855            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
3856                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
3857                        + scannedPkg.packageName);
3858                return PackageManager.SIGNATURE_MATCH;
3859            }
3860        } catch (CertificateException e) {
3861            msg = e.getMessage();
3862        }
3863
3864        logCriticalInfo(Log.INFO,
3865                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
3866        return PackageManager.SIGNATURE_NO_MATCH;
3867    }
3868
3869    @Override
3870    public String[] getPackagesForUid(int uid) {
3871        uid = UserHandle.getAppId(uid);
3872        // reader
3873        synchronized (mPackages) {
3874            Object obj = mSettings.getUserIdLPr(uid);
3875            if (obj instanceof SharedUserSetting) {
3876                final SharedUserSetting sus = (SharedUserSetting) obj;
3877                final int N = sus.packages.size();
3878                final String[] res = new String[N];
3879                final Iterator<PackageSetting> it = sus.packages.iterator();
3880                int i = 0;
3881                while (it.hasNext()) {
3882                    res[i++] = it.next().name;
3883                }
3884                return res;
3885            } else if (obj instanceof PackageSetting) {
3886                final PackageSetting ps = (PackageSetting) obj;
3887                return new String[] { ps.name };
3888            }
3889        }
3890        return null;
3891    }
3892
3893    @Override
3894    public String getNameForUid(int uid) {
3895        // reader
3896        synchronized (mPackages) {
3897            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3898            if (obj instanceof SharedUserSetting) {
3899                final SharedUserSetting sus = (SharedUserSetting) obj;
3900                return sus.name + ":" + sus.userId;
3901            } else if (obj instanceof PackageSetting) {
3902                final PackageSetting ps = (PackageSetting) obj;
3903                return ps.name;
3904            }
3905        }
3906        return null;
3907    }
3908
3909    @Override
3910    public int getUidForSharedUser(String sharedUserName) {
3911        if(sharedUserName == null) {
3912            return -1;
3913        }
3914        // reader
3915        synchronized (mPackages) {
3916            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
3917            if (suid == null) {
3918                return -1;
3919            }
3920            return suid.userId;
3921        }
3922    }
3923
3924    @Override
3925    public int getFlagsForUid(int uid) {
3926        synchronized (mPackages) {
3927            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3928            if (obj instanceof SharedUserSetting) {
3929                final SharedUserSetting sus = (SharedUserSetting) obj;
3930                return sus.pkgFlags;
3931            } else if (obj instanceof PackageSetting) {
3932                final PackageSetting ps = (PackageSetting) obj;
3933                return ps.pkgFlags;
3934            }
3935        }
3936        return 0;
3937    }
3938
3939    @Override
3940    public int getPrivateFlagsForUid(int uid) {
3941        synchronized (mPackages) {
3942            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3943            if (obj instanceof SharedUserSetting) {
3944                final SharedUserSetting sus = (SharedUserSetting) obj;
3945                return sus.pkgPrivateFlags;
3946            } else if (obj instanceof PackageSetting) {
3947                final PackageSetting ps = (PackageSetting) obj;
3948                return ps.pkgPrivateFlags;
3949            }
3950        }
3951        return 0;
3952    }
3953
3954    @Override
3955    public boolean isUidPrivileged(int uid) {
3956        uid = UserHandle.getAppId(uid);
3957        // reader
3958        synchronized (mPackages) {
3959            Object obj = mSettings.getUserIdLPr(uid);
3960            if (obj instanceof SharedUserSetting) {
3961                final SharedUserSetting sus = (SharedUserSetting) obj;
3962                final Iterator<PackageSetting> it = sus.packages.iterator();
3963                while (it.hasNext()) {
3964                    if (it.next().isPrivileged()) {
3965                        return true;
3966                    }
3967                }
3968            } else if (obj instanceof PackageSetting) {
3969                final PackageSetting ps = (PackageSetting) obj;
3970                return ps.isPrivileged();
3971            }
3972        }
3973        return false;
3974    }
3975
3976    @Override
3977    public String[] getAppOpPermissionPackages(String permissionName) {
3978        synchronized (mPackages) {
3979            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
3980            if (pkgs == null) {
3981                return null;
3982            }
3983            return pkgs.toArray(new String[pkgs.size()]);
3984        }
3985    }
3986
3987    @Override
3988    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
3989            int flags, int userId) {
3990        if (!sUserManager.exists(userId)) return null;
3991        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
3992        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3993        return chooseBestActivity(intent, resolvedType, flags, query, userId);
3994    }
3995
3996    @Override
3997    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
3998            IntentFilter filter, int match, ComponentName activity) {
3999        final int userId = UserHandle.getCallingUserId();
4000        if (DEBUG_PREFERRED) {
4001            Log.v(TAG, "setLastChosenActivity intent=" + intent
4002                + " resolvedType=" + resolvedType
4003                + " flags=" + flags
4004                + " filter=" + filter
4005                + " match=" + match
4006                + " activity=" + activity);
4007            filter.dump(new PrintStreamPrinter(System.out), "    ");
4008        }
4009        intent.setComponent(null);
4010        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4011        // Find any earlier preferred or last chosen entries and nuke them
4012        findPreferredActivity(intent, resolvedType,
4013                flags, query, 0, false, true, false, userId);
4014        // Add the new activity as the last chosen for this filter
4015        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4016                "Setting last chosen");
4017    }
4018
4019    @Override
4020    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4021        final int userId = UserHandle.getCallingUserId();
4022        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4023        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4024        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4025                false, false, false, userId);
4026    }
4027
4028    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4029            int flags, List<ResolveInfo> query, int userId) {
4030        if (query != null) {
4031            final int N = query.size();
4032            if (N == 1) {
4033                return query.get(0);
4034            } else if (N > 1) {
4035                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4036                // If there is more than one activity with the same priority,
4037                // then let the user decide between them.
4038                ResolveInfo r0 = query.get(0);
4039                ResolveInfo r1 = query.get(1);
4040                if (DEBUG_INTENT_MATCHING || debug) {
4041                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4042                            + r1.activityInfo.name + "=" + r1.priority);
4043                }
4044                // If the first activity has a higher priority, or a different
4045                // default, then it is always desireable to pick it.
4046                if (r0.priority != r1.priority
4047                        || r0.preferredOrder != r1.preferredOrder
4048                        || r0.isDefault != r1.isDefault) {
4049                    return query.get(0);
4050                }
4051                // If we have saved a preference for a preferred activity for
4052                // this Intent, use that.
4053                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4054                        flags, query, r0.priority, true, false, debug, userId);
4055                if (ri != null) {
4056                    return ri;
4057                }
4058                if (userId != 0) {
4059                    ri = new ResolveInfo(mResolveInfo);
4060                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
4061                    ri.activityInfo.applicationInfo = new ApplicationInfo(
4062                            ri.activityInfo.applicationInfo);
4063                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4064                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4065                    return ri;
4066                }
4067                return mResolveInfo;
4068            }
4069        }
4070        return null;
4071    }
4072
4073    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4074            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4075        final int N = query.size();
4076        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4077                .get(userId);
4078        // Get the list of persistent preferred activities that handle the intent
4079        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4080        List<PersistentPreferredActivity> pprefs = ppir != null
4081                ? ppir.queryIntent(intent, resolvedType,
4082                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4083                : null;
4084        if (pprefs != null && pprefs.size() > 0) {
4085            final int M = pprefs.size();
4086            for (int i=0; i<M; i++) {
4087                final PersistentPreferredActivity ppa = pprefs.get(i);
4088                if (DEBUG_PREFERRED || debug) {
4089                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4090                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4091                            + "\n  component=" + ppa.mComponent);
4092                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4093                }
4094                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4095                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4096                if (DEBUG_PREFERRED || debug) {
4097                    Slog.v(TAG, "Found persistent preferred activity:");
4098                    if (ai != null) {
4099                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4100                    } else {
4101                        Slog.v(TAG, "  null");
4102                    }
4103                }
4104                if (ai == null) {
4105                    // This previously registered persistent preferred activity
4106                    // component is no longer known. Ignore it and do NOT remove it.
4107                    continue;
4108                }
4109                for (int j=0; j<N; j++) {
4110                    final ResolveInfo ri = query.get(j);
4111                    if (!ri.activityInfo.applicationInfo.packageName
4112                            .equals(ai.applicationInfo.packageName)) {
4113                        continue;
4114                    }
4115                    if (!ri.activityInfo.name.equals(ai.name)) {
4116                        continue;
4117                    }
4118                    //  Found a persistent preference that can handle the intent.
4119                    if (DEBUG_PREFERRED || debug) {
4120                        Slog.v(TAG, "Returning persistent preferred activity: " +
4121                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4122                    }
4123                    return ri;
4124                }
4125            }
4126        }
4127        return null;
4128    }
4129
4130    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4131            List<ResolveInfo> query, int priority, boolean always,
4132            boolean removeMatches, boolean debug, int userId) {
4133        if (!sUserManager.exists(userId)) return null;
4134        // writer
4135        synchronized (mPackages) {
4136            if (intent.getSelector() != null) {
4137                intent = intent.getSelector();
4138            }
4139            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4140
4141            // Try to find a matching persistent preferred activity.
4142            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4143                    debug, userId);
4144
4145            // If a persistent preferred activity matched, use it.
4146            if (pri != null) {
4147                return pri;
4148            }
4149
4150            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4151            // Get the list of preferred activities that handle the intent
4152            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4153            List<PreferredActivity> prefs = pir != null
4154                    ? pir.queryIntent(intent, resolvedType,
4155                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4156                    : null;
4157            if (prefs != null && prefs.size() > 0) {
4158                boolean changed = false;
4159                try {
4160                    // First figure out how good the original match set is.
4161                    // We will only allow preferred activities that came
4162                    // from the same match quality.
4163                    int match = 0;
4164
4165                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4166
4167                    final int N = query.size();
4168                    for (int j=0; j<N; j++) {
4169                        final ResolveInfo ri = query.get(j);
4170                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4171                                + ": 0x" + Integer.toHexString(match));
4172                        if (ri.match > match) {
4173                            match = ri.match;
4174                        }
4175                    }
4176
4177                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4178                            + Integer.toHexString(match));
4179
4180                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4181                    final int M = prefs.size();
4182                    for (int i=0; i<M; i++) {
4183                        final PreferredActivity pa = prefs.get(i);
4184                        if (DEBUG_PREFERRED || debug) {
4185                            Slog.v(TAG, "Checking PreferredActivity ds="
4186                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4187                                    + "\n  component=" + pa.mPref.mComponent);
4188                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4189                        }
4190                        if (pa.mPref.mMatch != match) {
4191                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4192                                    + Integer.toHexString(pa.mPref.mMatch));
4193                            continue;
4194                        }
4195                        // If it's not an "always" type preferred activity and that's what we're
4196                        // looking for, skip it.
4197                        if (always && !pa.mPref.mAlways) {
4198                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4199                            continue;
4200                        }
4201                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4202                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4203                        if (DEBUG_PREFERRED || debug) {
4204                            Slog.v(TAG, "Found preferred activity:");
4205                            if (ai != null) {
4206                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4207                            } else {
4208                                Slog.v(TAG, "  null");
4209                            }
4210                        }
4211                        if (ai == null) {
4212                            // This previously registered preferred activity
4213                            // component is no longer known.  Most likely an update
4214                            // to the app was installed and in the new version this
4215                            // component no longer exists.  Clean it up by removing
4216                            // it from the preferred activities list, and skip it.
4217                            Slog.w(TAG, "Removing dangling preferred activity: "
4218                                    + pa.mPref.mComponent);
4219                            pir.removeFilter(pa);
4220                            changed = true;
4221                            continue;
4222                        }
4223                        for (int j=0; j<N; j++) {
4224                            final ResolveInfo ri = query.get(j);
4225                            if (!ri.activityInfo.applicationInfo.packageName
4226                                    .equals(ai.applicationInfo.packageName)) {
4227                                continue;
4228                            }
4229                            if (!ri.activityInfo.name.equals(ai.name)) {
4230                                continue;
4231                            }
4232
4233                            if (removeMatches) {
4234                                pir.removeFilter(pa);
4235                                changed = true;
4236                                if (DEBUG_PREFERRED) {
4237                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4238                                }
4239                                break;
4240                            }
4241
4242                            // Okay we found a previously set preferred or last chosen app.
4243                            // If the result set is different from when this
4244                            // was created, we need to clear it and re-ask the
4245                            // user their preference, if we're looking for an "always" type entry.
4246                            if (always && !pa.mPref.sameSet(query)) {
4247                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4248                                        + intent + " type " + resolvedType);
4249                                if (DEBUG_PREFERRED) {
4250                                    Slog.v(TAG, "Removing preferred activity since set changed "
4251                                            + pa.mPref.mComponent);
4252                                }
4253                                pir.removeFilter(pa);
4254                                // Re-add the filter as a "last chosen" entry (!always)
4255                                PreferredActivity lastChosen = new PreferredActivity(
4256                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4257                                pir.addFilter(lastChosen);
4258                                changed = true;
4259                                return null;
4260                            }
4261
4262                            // Yay! Either the set matched or we're looking for the last chosen
4263                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4264                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4265                            return ri;
4266                        }
4267                    }
4268                } finally {
4269                    if (changed) {
4270                        if (DEBUG_PREFERRED) {
4271                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4272                        }
4273                        scheduleWritePackageRestrictionsLocked(userId);
4274                    }
4275                }
4276            }
4277        }
4278        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4279        return null;
4280    }
4281
4282    /*
4283     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4284     */
4285    @Override
4286    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4287            int targetUserId) {
4288        mContext.enforceCallingOrSelfPermission(
4289                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4290        List<CrossProfileIntentFilter> matches =
4291                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4292        if (matches != null) {
4293            int size = matches.size();
4294            for (int i = 0; i < size; i++) {
4295                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4296            }
4297        }
4298        if (hasWebURI(intent)) {
4299            // cross-profile app linking works only towards the parent.
4300            final UserInfo parent = getProfileParent(sourceUserId);
4301            synchronized(mPackages) {
4302                return getCrossProfileDomainPreferredLpr(intent, resolvedType, 0, sourceUserId,
4303                        parent.id) != null;
4304            }
4305        }
4306        return false;
4307    }
4308
4309    private UserInfo getProfileParent(int userId) {
4310        final long identity = Binder.clearCallingIdentity();
4311        try {
4312            return sUserManager.getProfileParent(userId);
4313        } finally {
4314            Binder.restoreCallingIdentity(identity);
4315        }
4316    }
4317
4318    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4319            String resolvedType, int userId) {
4320        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4321        if (resolver != null) {
4322            return resolver.queryIntent(intent, resolvedType, false, userId);
4323        }
4324        return null;
4325    }
4326
4327    @Override
4328    public List<ResolveInfo> queryIntentActivities(Intent intent,
4329            String resolvedType, int flags, int userId) {
4330        if (!sUserManager.exists(userId)) return Collections.emptyList();
4331        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4332        ComponentName comp = intent.getComponent();
4333        if (comp == null) {
4334            if (intent.getSelector() != null) {
4335                intent = intent.getSelector();
4336                comp = intent.getComponent();
4337            }
4338        }
4339
4340        if (comp != null) {
4341            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4342            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4343            if (ai != null) {
4344                final ResolveInfo ri = new ResolveInfo();
4345                ri.activityInfo = ai;
4346                list.add(ri);
4347            }
4348            return list;
4349        }
4350
4351        // reader
4352        synchronized (mPackages) {
4353            final String pkgName = intent.getPackage();
4354            if (pkgName == null) {
4355                List<CrossProfileIntentFilter> matchingFilters =
4356                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4357                // Check for results that need to skip the current profile.
4358                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4359                        resolvedType, flags, userId);
4360                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4361                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4362                    result.add(xpResolveInfo);
4363                    return filterIfNotPrimaryUser(result, userId);
4364                }
4365
4366                // Check for results in the current profile.
4367                List<ResolveInfo> result = mActivities.queryIntent(
4368                        intent, resolvedType, flags, userId);
4369
4370                // Check for cross profile results.
4371                xpResolveInfo = queryCrossProfileIntents(
4372                        matchingFilters, intent, resolvedType, flags, userId);
4373                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4374                    result.add(xpResolveInfo);
4375                    Collections.sort(result, mResolvePrioritySorter);
4376                }
4377                result = filterIfNotPrimaryUser(result, userId);
4378                if (hasWebURI(intent)) {
4379                    CrossProfileDomainInfo xpDomainInfo = null;
4380                    final UserInfo parent = getProfileParent(userId);
4381                    if (parent != null) {
4382                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4383                                flags, userId, parent.id);
4384                    }
4385                    if (xpDomainInfo != null) {
4386                        if (xpResolveInfo != null) {
4387                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4388                            // in the result.
4389                            result.remove(xpResolveInfo);
4390                        }
4391                        if (result.size() == 0) {
4392                            result.add(xpDomainInfo.resolveInfo);
4393                            return result;
4394                        }
4395                    } else if (result.size() <= 1) {
4396                        return result;
4397                    }
4398                    result = filterCandidatesWithDomainPreferredActivitiesLPr(flags, result,
4399                            xpDomainInfo);
4400                    Collections.sort(result, mResolvePrioritySorter);
4401                }
4402                return result;
4403            }
4404            final PackageParser.Package pkg = mPackages.get(pkgName);
4405            if (pkg != null) {
4406                return filterIfNotPrimaryUser(
4407                        mActivities.queryIntentForPackage(
4408                                intent, resolvedType, flags, pkg.activities, userId),
4409                        userId);
4410            }
4411            return new ArrayList<ResolveInfo>();
4412        }
4413    }
4414
4415    private static class CrossProfileDomainInfo {
4416        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4417        ResolveInfo resolveInfo;
4418        /* Best domain verification status of the activities found in the other profile */
4419        int bestDomainVerificationStatus;
4420    }
4421
4422    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4423            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4424        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
4425                sourceUserId)) {
4426            return null;
4427        }
4428        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4429                resolvedType, flags, parentUserId);
4430
4431        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4432            return null;
4433        }
4434        CrossProfileDomainInfo result = null;
4435        int size = resultTargetUser.size();
4436        for (int i = 0; i < size; i++) {
4437            ResolveInfo riTargetUser = resultTargetUser.get(i);
4438            // Intent filter verification is only for filters that specify a host. So don't return
4439            // those that handle all web uris.
4440            if (riTargetUser.handleAllWebDataURI) {
4441                continue;
4442            }
4443            String packageName = riTargetUser.activityInfo.packageName;
4444            PackageSetting ps = mSettings.mPackages.get(packageName);
4445            if (ps == null) {
4446                continue;
4447            }
4448            int status = getDomainVerificationStatusLPr(ps, parentUserId);
4449            if (result == null) {
4450                result = new CrossProfileDomainInfo();
4451                result.resolveInfo =
4452                        createForwardingResolveInfo(null, sourceUserId, parentUserId);
4453                result.bestDomainVerificationStatus = status;
4454            } else {
4455                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
4456                        result.bestDomainVerificationStatus);
4457            }
4458        }
4459        return result;
4460    }
4461
4462    /**
4463     * Verification statuses are ordered from the worse to the best, except for
4464     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
4465     */
4466    private int bestDomainVerificationStatus(int status1, int status2) {
4467        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4468            return status2;
4469        }
4470        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4471            return status1;
4472        }
4473        return (int) MathUtils.max(status1, status2);
4474    }
4475
4476    private boolean isUserEnabled(int userId) {
4477        long callingId = Binder.clearCallingIdentity();
4478        try {
4479            UserInfo userInfo = sUserManager.getUserInfo(userId);
4480            return userInfo != null && userInfo.isEnabled();
4481        } finally {
4482            Binder.restoreCallingIdentity(callingId);
4483        }
4484    }
4485
4486    /**
4487     * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
4488     *
4489     * @return filtered list
4490     */
4491    private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
4492        if (userId == UserHandle.USER_OWNER) {
4493            return resolveInfos;
4494        }
4495        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4496            ResolveInfo info = resolveInfos.get(i);
4497            if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
4498                resolveInfos.remove(i);
4499            }
4500        }
4501        return resolveInfos;
4502    }
4503
4504    private static boolean hasWebURI(Intent intent) {
4505        if (intent.getData() == null) {
4506            return false;
4507        }
4508        final String scheme = intent.getScheme();
4509        if (TextUtils.isEmpty(scheme)) {
4510            return false;
4511        }
4512        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4513    }
4514
4515    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(
4516            int flags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo) {
4517        if (DEBUG_PREFERRED) {
4518            Slog.v("TAG", "Filtering results with prefered activities. Candidates count: " +
4519                    candidates.size());
4520        }
4521
4522        final int userId = UserHandle.getCallingUserId();
4523        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4524        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
4525        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4526        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4527        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4528
4529        synchronized (mPackages) {
4530            final int count = candidates.size();
4531            // First, try to use the domain preferred app. Partition the candidates into four lists:
4532            // one for the final results, one for the "do not use ever", one for "undefined status"
4533            // and finally one for "Browser App type".
4534            for (int n=0; n<count; n++) {
4535                ResolveInfo info = candidates.get(n);
4536                String packageName = info.activityInfo.packageName;
4537                PackageSetting ps = mSettings.mPackages.get(packageName);
4538                if (ps != null) {
4539                    // Add to the special match all list (Browser use case)
4540                    if (info.handleAllWebDataURI) {
4541                        matchAllList.add(info);
4542                        continue;
4543                    }
4544                    // Try to get the status from User settings first
4545                    int status = getDomainVerificationStatusLPr(ps, userId);
4546                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4547                        alwaysList.add(info);
4548                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4549                        neverList.add(info);
4550                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
4551                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
4552                        undefinedList.add(info);
4553                    }
4554                }
4555            }
4556            // First try to add the "always" resolution for the current user if there is any
4557            if (alwaysList.size() > 0) {
4558                result.addAll(alwaysList);
4559            // if there is an "always" for the parent user, add it.
4560            } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus
4561                    == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4562                result.add(xpDomainInfo.resolveInfo);
4563            } else {
4564                // Add all undefined Apps as we want them to appear in the Disambiguation dialog.
4565                result.addAll(undefinedList);
4566                if (xpDomainInfo != null && (
4567                        xpDomainInfo.bestDomainVerificationStatus
4568                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
4569                        || xpDomainInfo.bestDomainVerificationStatus
4570                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) {
4571                    result.add(xpDomainInfo.resolveInfo);
4572                }
4573                // Also add Browsers (all of them or only the default one)
4574                if ((flags & MATCH_ALL) != 0) {
4575                    result.addAll(matchAllList);
4576                } else {
4577                    // Try to add the Default Browser if we can
4578                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(
4579                            UserHandle.myUserId());
4580                    if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
4581                        boolean defaultBrowserFound = false;
4582                        final int browserCount = matchAllList.size();
4583                        for (int n=0; n<browserCount; n++) {
4584                            ResolveInfo browser = matchAllList.get(n);
4585                            if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) {
4586                                result.add(browser);
4587                                defaultBrowserFound = true;
4588                                break;
4589                            }
4590                        }
4591                        if (!defaultBrowserFound) {
4592                            result.addAll(matchAllList);
4593                        }
4594                    } else {
4595                        result.addAll(matchAllList);
4596                    }
4597                }
4598
4599                // If there is nothing selected, add all candidates and remove the ones that the User
4600                // has explicitely put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
4601                if (result.size() == 0) {
4602                    result.addAll(candidates);
4603                    result.removeAll(neverList);
4604                }
4605            }
4606        }
4607        if (DEBUG_PREFERRED) {
4608            Slog.v("TAG", "Filtered results with prefered activities. New candidates count: " +
4609                    result.size());
4610        }
4611        return result;
4612    }
4613
4614    private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4615        int status = ps.getDomainVerificationStatusForUser(userId);
4616        // if none available, get the master status
4617        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4618            if (ps.getIntentFilterVerificationInfo() != null) {
4619                status = ps.getIntentFilterVerificationInfo().getStatus();
4620            }
4621        }
4622        return status;
4623    }
4624
4625    private ResolveInfo querySkipCurrentProfileIntents(
4626            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4627            int flags, int sourceUserId) {
4628        if (matchingFilters != null) {
4629            int size = matchingFilters.size();
4630            for (int i = 0; i < size; i ++) {
4631                CrossProfileIntentFilter filter = matchingFilters.get(i);
4632                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4633                    // Checking if there are activities in the target user that can handle the
4634                    // intent.
4635                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4636                            flags, sourceUserId);
4637                    if (resolveInfo != null) {
4638                        return resolveInfo;
4639                    }
4640                }
4641            }
4642        }
4643        return null;
4644    }
4645
4646    // Return matching ResolveInfo if any for skip current profile intent filters.
4647    private ResolveInfo queryCrossProfileIntents(
4648            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4649            int flags, int sourceUserId) {
4650        if (matchingFilters != null) {
4651            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4652            // match the same intent. For performance reasons, it is better not to
4653            // run queryIntent twice for the same userId
4654            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4655            int size = matchingFilters.size();
4656            for (int i = 0; i < size; i++) {
4657                CrossProfileIntentFilter filter = matchingFilters.get(i);
4658                int targetUserId = filter.getTargetUserId();
4659                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4660                        && !alreadyTriedUserIds.get(targetUserId)) {
4661                    // Checking if there are activities in the target user that can handle the
4662                    // intent.
4663                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4664                            flags, sourceUserId);
4665                    if (resolveInfo != null) return resolveInfo;
4666                    alreadyTriedUserIds.put(targetUserId, true);
4667                }
4668            }
4669        }
4670        return null;
4671    }
4672
4673    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
4674            String resolvedType, int flags, int sourceUserId) {
4675        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4676                resolvedType, flags, filter.getTargetUserId());
4677        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
4678            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
4679        }
4680        return null;
4681    }
4682
4683    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
4684            int sourceUserId, int targetUserId) {
4685        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4686        String className;
4687        if (targetUserId == UserHandle.USER_OWNER) {
4688            className = FORWARD_INTENT_TO_USER_OWNER;
4689        } else {
4690            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4691        }
4692        ComponentName forwardingActivityComponentName = new ComponentName(
4693                mAndroidApplication.packageName, className);
4694        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
4695                sourceUserId);
4696        if (targetUserId == UserHandle.USER_OWNER) {
4697            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
4698            forwardingResolveInfo.noResourceId = true;
4699        }
4700        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
4701        forwardingResolveInfo.priority = 0;
4702        forwardingResolveInfo.preferredOrder = 0;
4703        forwardingResolveInfo.match = 0;
4704        forwardingResolveInfo.isDefault = true;
4705        forwardingResolveInfo.filter = filter;
4706        forwardingResolveInfo.targetUserId = targetUserId;
4707        return forwardingResolveInfo;
4708    }
4709
4710    @Override
4711    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
4712            Intent[] specifics, String[] specificTypes, Intent intent,
4713            String resolvedType, int flags, int userId) {
4714        if (!sUserManager.exists(userId)) return Collections.emptyList();
4715        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
4716                false, "query intent activity options");
4717        final String resultsAction = intent.getAction();
4718
4719        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
4720                | PackageManager.GET_RESOLVED_FILTER, userId);
4721
4722        if (DEBUG_INTENT_MATCHING) {
4723            Log.v(TAG, "Query " + intent + ": " + results);
4724        }
4725
4726        int specificsPos = 0;
4727        int N;
4728
4729        // todo: note that the algorithm used here is O(N^2).  This
4730        // isn't a problem in our current environment, but if we start running
4731        // into situations where we have more than 5 or 10 matches then this
4732        // should probably be changed to something smarter...
4733
4734        // First we go through and resolve each of the specific items
4735        // that were supplied, taking care of removing any corresponding
4736        // duplicate items in the generic resolve list.
4737        if (specifics != null) {
4738            for (int i=0; i<specifics.length; i++) {
4739                final Intent sintent = specifics[i];
4740                if (sintent == null) {
4741                    continue;
4742                }
4743
4744                if (DEBUG_INTENT_MATCHING) {
4745                    Log.v(TAG, "Specific #" + i + ": " + sintent);
4746                }
4747
4748                String action = sintent.getAction();
4749                if (resultsAction != null && resultsAction.equals(action)) {
4750                    // If this action was explicitly requested, then don't
4751                    // remove things that have it.
4752                    action = null;
4753                }
4754
4755                ResolveInfo ri = null;
4756                ActivityInfo ai = null;
4757
4758                ComponentName comp = sintent.getComponent();
4759                if (comp == null) {
4760                    ri = resolveIntent(
4761                        sintent,
4762                        specificTypes != null ? specificTypes[i] : null,
4763                            flags, userId);
4764                    if (ri == null) {
4765                        continue;
4766                    }
4767                    if (ri == mResolveInfo) {
4768                        // ACK!  Must do something better with this.
4769                    }
4770                    ai = ri.activityInfo;
4771                    comp = new ComponentName(ai.applicationInfo.packageName,
4772                            ai.name);
4773                } else {
4774                    ai = getActivityInfo(comp, flags, userId);
4775                    if (ai == null) {
4776                        continue;
4777                    }
4778                }
4779
4780                // Look for any generic query activities that are duplicates
4781                // of this specific one, and remove them from the results.
4782                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
4783                N = results.size();
4784                int j;
4785                for (j=specificsPos; j<N; j++) {
4786                    ResolveInfo sri = results.get(j);
4787                    if ((sri.activityInfo.name.equals(comp.getClassName())
4788                            && sri.activityInfo.applicationInfo.packageName.equals(
4789                                    comp.getPackageName()))
4790                        || (action != null && sri.filter.matchAction(action))) {
4791                        results.remove(j);
4792                        if (DEBUG_INTENT_MATCHING) Log.v(
4793                            TAG, "Removing duplicate item from " + j
4794                            + " due to specific " + specificsPos);
4795                        if (ri == null) {
4796                            ri = sri;
4797                        }
4798                        j--;
4799                        N--;
4800                    }
4801                }
4802
4803                // Add this specific item to its proper place.
4804                if (ri == null) {
4805                    ri = new ResolveInfo();
4806                    ri.activityInfo = ai;
4807                }
4808                results.add(specificsPos, ri);
4809                ri.specificIndex = i;
4810                specificsPos++;
4811            }
4812        }
4813
4814        // Now we go through the remaining generic results and remove any
4815        // duplicate actions that are found here.
4816        N = results.size();
4817        for (int i=specificsPos; i<N-1; i++) {
4818            final ResolveInfo rii = results.get(i);
4819            if (rii.filter == null) {
4820                continue;
4821            }
4822
4823            // Iterate over all of the actions of this result's intent
4824            // filter...  typically this should be just one.
4825            final Iterator<String> it = rii.filter.actionsIterator();
4826            if (it == null) {
4827                continue;
4828            }
4829            while (it.hasNext()) {
4830                final String action = it.next();
4831                if (resultsAction != null && resultsAction.equals(action)) {
4832                    // If this action was explicitly requested, then don't
4833                    // remove things that have it.
4834                    continue;
4835                }
4836                for (int j=i+1; j<N; j++) {
4837                    final ResolveInfo rij = results.get(j);
4838                    if (rij.filter != null && rij.filter.hasAction(action)) {
4839                        results.remove(j);
4840                        if (DEBUG_INTENT_MATCHING) Log.v(
4841                            TAG, "Removing duplicate item from " + j
4842                            + " due to action " + action + " at " + i);
4843                        j--;
4844                        N--;
4845                    }
4846                }
4847            }
4848
4849            // If the caller didn't request filter information, drop it now
4850            // so we don't have to marshall/unmarshall it.
4851            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4852                rii.filter = null;
4853            }
4854        }
4855
4856        // Filter out the caller activity if so requested.
4857        if (caller != null) {
4858            N = results.size();
4859            for (int i=0; i<N; i++) {
4860                ActivityInfo ainfo = results.get(i).activityInfo;
4861                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
4862                        && caller.getClassName().equals(ainfo.name)) {
4863                    results.remove(i);
4864                    break;
4865                }
4866            }
4867        }
4868
4869        // If the caller didn't request filter information,
4870        // drop them now so we don't have to
4871        // marshall/unmarshall it.
4872        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4873            N = results.size();
4874            for (int i=0; i<N; i++) {
4875                results.get(i).filter = null;
4876            }
4877        }
4878
4879        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
4880        return results;
4881    }
4882
4883    @Override
4884    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
4885            int userId) {
4886        if (!sUserManager.exists(userId)) return Collections.emptyList();
4887        ComponentName comp = intent.getComponent();
4888        if (comp == null) {
4889            if (intent.getSelector() != null) {
4890                intent = intent.getSelector();
4891                comp = intent.getComponent();
4892            }
4893        }
4894        if (comp != null) {
4895            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4896            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
4897            if (ai != null) {
4898                ResolveInfo ri = new ResolveInfo();
4899                ri.activityInfo = ai;
4900                list.add(ri);
4901            }
4902            return list;
4903        }
4904
4905        // reader
4906        synchronized (mPackages) {
4907            String pkgName = intent.getPackage();
4908            if (pkgName == null) {
4909                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
4910            }
4911            final PackageParser.Package pkg = mPackages.get(pkgName);
4912            if (pkg != null) {
4913                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
4914                        userId);
4915            }
4916            return null;
4917        }
4918    }
4919
4920    @Override
4921    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
4922        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
4923        if (!sUserManager.exists(userId)) return null;
4924        if (query != null) {
4925            if (query.size() >= 1) {
4926                // If there is more than one service with the same priority,
4927                // just arbitrarily pick the first one.
4928                return query.get(0);
4929            }
4930        }
4931        return null;
4932    }
4933
4934    @Override
4935    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
4936            int userId) {
4937        if (!sUserManager.exists(userId)) return Collections.emptyList();
4938        ComponentName comp = intent.getComponent();
4939        if (comp == null) {
4940            if (intent.getSelector() != null) {
4941                intent = intent.getSelector();
4942                comp = intent.getComponent();
4943            }
4944        }
4945        if (comp != null) {
4946            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4947            final ServiceInfo si = getServiceInfo(comp, flags, userId);
4948            if (si != null) {
4949                final ResolveInfo ri = new ResolveInfo();
4950                ri.serviceInfo = si;
4951                list.add(ri);
4952            }
4953            return list;
4954        }
4955
4956        // reader
4957        synchronized (mPackages) {
4958            String pkgName = intent.getPackage();
4959            if (pkgName == null) {
4960                return mServices.queryIntent(intent, resolvedType, flags, userId);
4961            }
4962            final PackageParser.Package pkg = mPackages.get(pkgName);
4963            if (pkg != null) {
4964                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
4965                        userId);
4966            }
4967            return null;
4968        }
4969    }
4970
4971    @Override
4972    public List<ResolveInfo> queryIntentContentProviders(
4973            Intent intent, String resolvedType, int flags, int userId) {
4974        if (!sUserManager.exists(userId)) return Collections.emptyList();
4975        ComponentName comp = intent.getComponent();
4976        if (comp == null) {
4977            if (intent.getSelector() != null) {
4978                intent = intent.getSelector();
4979                comp = intent.getComponent();
4980            }
4981        }
4982        if (comp != null) {
4983            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4984            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
4985            if (pi != null) {
4986                final ResolveInfo ri = new ResolveInfo();
4987                ri.providerInfo = pi;
4988                list.add(ri);
4989            }
4990            return list;
4991        }
4992
4993        // reader
4994        synchronized (mPackages) {
4995            String pkgName = intent.getPackage();
4996            if (pkgName == null) {
4997                return mProviders.queryIntent(intent, resolvedType, flags, userId);
4998            }
4999            final PackageParser.Package pkg = mPackages.get(pkgName);
5000            if (pkg != null) {
5001                return mProviders.queryIntentForPackage(
5002                        intent, resolvedType, flags, pkg.providers, userId);
5003            }
5004            return null;
5005        }
5006    }
5007
5008    @Override
5009    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5010        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5011
5012        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5013
5014        // writer
5015        synchronized (mPackages) {
5016            ArrayList<PackageInfo> list;
5017            if (listUninstalled) {
5018                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5019                for (PackageSetting ps : mSettings.mPackages.values()) {
5020                    PackageInfo pi;
5021                    if (ps.pkg != null) {
5022                        pi = generatePackageInfo(ps.pkg, flags, userId);
5023                    } else {
5024                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5025                    }
5026                    if (pi != null) {
5027                        list.add(pi);
5028                    }
5029                }
5030            } else {
5031                list = new ArrayList<PackageInfo>(mPackages.size());
5032                for (PackageParser.Package p : mPackages.values()) {
5033                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5034                    if (pi != null) {
5035                        list.add(pi);
5036                    }
5037                }
5038            }
5039
5040            return new ParceledListSlice<PackageInfo>(list);
5041        }
5042    }
5043
5044    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5045            String[] permissions, boolean[] tmp, int flags, int userId) {
5046        int numMatch = 0;
5047        final PermissionsState permissionsState = ps.getPermissionsState();
5048        for (int i=0; i<permissions.length; i++) {
5049            final String permission = permissions[i];
5050            if (permissionsState.hasPermission(permission, userId)) {
5051                tmp[i] = true;
5052                numMatch++;
5053            } else {
5054                tmp[i] = false;
5055            }
5056        }
5057        if (numMatch == 0) {
5058            return;
5059        }
5060        PackageInfo pi;
5061        if (ps.pkg != null) {
5062            pi = generatePackageInfo(ps.pkg, flags, userId);
5063        } else {
5064            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5065        }
5066        // The above might return null in cases of uninstalled apps or install-state
5067        // skew across users/profiles.
5068        if (pi != null) {
5069            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5070                if (numMatch == permissions.length) {
5071                    pi.requestedPermissions = permissions;
5072                } else {
5073                    pi.requestedPermissions = new String[numMatch];
5074                    numMatch = 0;
5075                    for (int i=0; i<permissions.length; i++) {
5076                        if (tmp[i]) {
5077                            pi.requestedPermissions[numMatch] = permissions[i];
5078                            numMatch++;
5079                        }
5080                    }
5081                }
5082            }
5083            list.add(pi);
5084        }
5085    }
5086
5087    @Override
5088    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5089            String[] permissions, int flags, int userId) {
5090        if (!sUserManager.exists(userId)) return null;
5091        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5092
5093        // writer
5094        synchronized (mPackages) {
5095            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5096            boolean[] tmpBools = new boolean[permissions.length];
5097            if (listUninstalled) {
5098                for (PackageSetting ps : mSettings.mPackages.values()) {
5099                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5100                }
5101            } else {
5102                for (PackageParser.Package pkg : mPackages.values()) {
5103                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5104                    if (ps != null) {
5105                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5106                                userId);
5107                    }
5108                }
5109            }
5110
5111            return new ParceledListSlice<PackageInfo>(list);
5112        }
5113    }
5114
5115    @Override
5116    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5117        if (!sUserManager.exists(userId)) return null;
5118        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5119
5120        // writer
5121        synchronized (mPackages) {
5122            ArrayList<ApplicationInfo> list;
5123            if (listUninstalled) {
5124                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5125                for (PackageSetting ps : mSettings.mPackages.values()) {
5126                    ApplicationInfo ai;
5127                    if (ps.pkg != null) {
5128                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5129                                ps.readUserState(userId), userId);
5130                    } else {
5131                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5132                    }
5133                    if (ai != null) {
5134                        list.add(ai);
5135                    }
5136                }
5137            } else {
5138                list = new ArrayList<ApplicationInfo>(mPackages.size());
5139                for (PackageParser.Package p : mPackages.values()) {
5140                    if (p.mExtras != null) {
5141                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5142                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5143                        if (ai != null) {
5144                            list.add(ai);
5145                        }
5146                    }
5147                }
5148            }
5149
5150            return new ParceledListSlice<ApplicationInfo>(list);
5151        }
5152    }
5153
5154    public List<ApplicationInfo> getPersistentApplications(int flags) {
5155        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5156
5157        // reader
5158        synchronized (mPackages) {
5159            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5160            final int userId = UserHandle.getCallingUserId();
5161            while (i.hasNext()) {
5162                final PackageParser.Package p = i.next();
5163                if (p.applicationInfo != null
5164                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5165                        && (!mSafeMode || isSystemApp(p))) {
5166                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5167                    if (ps != null) {
5168                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5169                                ps.readUserState(userId), userId);
5170                        if (ai != null) {
5171                            finalList.add(ai);
5172                        }
5173                    }
5174                }
5175            }
5176        }
5177
5178        return finalList;
5179    }
5180
5181    @Override
5182    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5183        if (!sUserManager.exists(userId)) return null;
5184        // reader
5185        synchronized (mPackages) {
5186            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5187            PackageSetting ps = provider != null
5188                    ? mSettings.mPackages.get(provider.owner.packageName)
5189                    : null;
5190            return ps != null
5191                    && mSettings.isEnabledLPr(provider.info, flags, userId)
5192                    && (!mSafeMode || (provider.info.applicationInfo.flags
5193                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5194                    ? PackageParser.generateProviderInfo(provider, flags,
5195                            ps.readUserState(userId), userId)
5196                    : null;
5197        }
5198    }
5199
5200    /**
5201     * @deprecated
5202     */
5203    @Deprecated
5204    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5205        // reader
5206        synchronized (mPackages) {
5207            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5208                    .entrySet().iterator();
5209            final int userId = UserHandle.getCallingUserId();
5210            while (i.hasNext()) {
5211                Map.Entry<String, PackageParser.Provider> entry = i.next();
5212                PackageParser.Provider p = entry.getValue();
5213                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5214
5215                if (ps != null && p.syncable
5216                        && (!mSafeMode || (p.info.applicationInfo.flags
5217                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5218                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5219                            ps.readUserState(userId), userId);
5220                    if (info != null) {
5221                        outNames.add(entry.getKey());
5222                        outInfo.add(info);
5223                    }
5224                }
5225            }
5226        }
5227    }
5228
5229    @Override
5230    public List<ProviderInfo> queryContentProviders(String processName,
5231            int uid, int flags) {
5232        ArrayList<ProviderInfo> finalList = null;
5233        // reader
5234        synchronized (mPackages) {
5235            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5236            final int userId = processName != null ?
5237                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
5238            while (i.hasNext()) {
5239                final PackageParser.Provider p = i.next();
5240                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5241                if (ps != null && p.info.authority != null
5242                        && (processName == null
5243                                || (p.info.processName.equals(processName)
5244                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5245                        && mSettings.isEnabledLPr(p.info, flags, userId)
5246                        && (!mSafeMode
5247                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5248                    if (finalList == null) {
5249                        finalList = new ArrayList<ProviderInfo>(3);
5250                    }
5251                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5252                            ps.readUserState(userId), userId);
5253                    if (info != null) {
5254                        finalList.add(info);
5255                    }
5256                }
5257            }
5258        }
5259
5260        if (finalList != null) {
5261            Collections.sort(finalList, mProviderInitOrderSorter);
5262        }
5263
5264        return finalList;
5265    }
5266
5267    @Override
5268    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
5269            int flags) {
5270        // reader
5271        synchronized (mPackages) {
5272            final PackageParser.Instrumentation i = mInstrumentation.get(name);
5273            return PackageParser.generateInstrumentationInfo(i, flags);
5274        }
5275    }
5276
5277    @Override
5278    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
5279            int flags) {
5280        ArrayList<InstrumentationInfo> finalList =
5281            new ArrayList<InstrumentationInfo>();
5282
5283        // reader
5284        synchronized (mPackages) {
5285            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
5286            while (i.hasNext()) {
5287                final PackageParser.Instrumentation p = i.next();
5288                if (targetPackage == null
5289                        || targetPackage.equals(p.info.targetPackage)) {
5290                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
5291                            flags);
5292                    if (ii != null) {
5293                        finalList.add(ii);
5294                    }
5295                }
5296            }
5297        }
5298
5299        return finalList;
5300    }
5301
5302    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
5303        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
5304        if (overlays == null) {
5305            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
5306            return;
5307        }
5308        for (PackageParser.Package opkg : overlays.values()) {
5309            // Not much to do if idmap fails: we already logged the error
5310            // and we certainly don't want to abort installation of pkg simply
5311            // because an overlay didn't fit properly. For these reasons,
5312            // ignore the return value of createIdmapForPackagePairLI.
5313            createIdmapForPackagePairLI(pkg, opkg);
5314        }
5315    }
5316
5317    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
5318            PackageParser.Package opkg) {
5319        if (!opkg.mTrustedOverlay) {
5320            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
5321                    opkg.baseCodePath + ": overlay not trusted");
5322            return false;
5323        }
5324        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
5325        if (overlaySet == null) {
5326            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
5327                    opkg.baseCodePath + " but target package has no known overlays");
5328            return false;
5329        }
5330        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
5331        // TODO: generate idmap for split APKs
5332        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
5333            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
5334                    + opkg.baseCodePath);
5335            return false;
5336        }
5337        PackageParser.Package[] overlayArray =
5338            overlaySet.values().toArray(new PackageParser.Package[0]);
5339        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
5340            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
5341                return p1.mOverlayPriority - p2.mOverlayPriority;
5342            }
5343        };
5344        Arrays.sort(overlayArray, cmp);
5345
5346        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5347        int i = 0;
5348        for (PackageParser.Package p : overlayArray) {
5349            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5350        }
5351        return true;
5352    }
5353
5354    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5355        final File[] files = dir.listFiles();
5356        if (ArrayUtils.isEmpty(files)) {
5357            Log.d(TAG, "No files in app dir " + dir);
5358            return;
5359        }
5360
5361        if (DEBUG_PACKAGE_SCANNING) {
5362            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
5363                    + " flags=0x" + Integer.toHexString(parseFlags));
5364        }
5365
5366        for (File file : files) {
5367            final boolean isPackage = (isApkFile(file) || file.isDirectory())
5368                    && !PackageInstallerService.isStageName(file.getName());
5369            if (!isPackage) {
5370                // Ignore entries which are not packages
5371                continue;
5372            }
5373            try {
5374                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
5375                        scanFlags, currentTime, null);
5376            } catch (PackageManagerException e) {
5377                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
5378
5379                // Delete invalid userdata apps
5380                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
5381                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
5382                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
5383                    if (file.isDirectory()) {
5384                        mInstaller.rmPackageDir(file.getAbsolutePath());
5385                    } else {
5386                        file.delete();
5387                    }
5388                }
5389            }
5390        }
5391    }
5392
5393    private static File getSettingsProblemFile() {
5394        File dataDir = Environment.getDataDirectory();
5395        File systemDir = new File(dataDir, "system");
5396        File fname = new File(systemDir, "uiderrors.txt");
5397        return fname;
5398    }
5399
5400    static void reportSettingsProblem(int priority, String msg) {
5401        logCriticalInfo(priority, msg);
5402    }
5403
5404    static void logCriticalInfo(int priority, String msg) {
5405        Slog.println(priority, TAG, msg);
5406        EventLogTags.writePmCriticalInfo(msg);
5407        try {
5408            File fname = getSettingsProblemFile();
5409            FileOutputStream out = new FileOutputStream(fname, true);
5410            PrintWriter pw = new FastPrintWriter(out);
5411            SimpleDateFormat formatter = new SimpleDateFormat();
5412            String dateString = formatter.format(new Date(System.currentTimeMillis()));
5413            pw.println(dateString + ": " + msg);
5414            pw.close();
5415            FileUtils.setPermissions(
5416                    fname.toString(),
5417                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5418                    -1, -1);
5419        } catch (java.io.IOException e) {
5420        }
5421    }
5422
5423    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5424            PackageParser.Package pkg, File srcFile, int parseFlags)
5425            throws PackageManagerException {
5426        if (ps != null
5427                && ps.codePath.equals(srcFile)
5428                && ps.timeStamp == srcFile.lastModified()
5429                && !isCompatSignatureUpdateNeeded(pkg)
5430                && !isRecoverSignatureUpdateNeeded(pkg)) {
5431            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5432            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5433            ArraySet<PublicKey> signingKs;
5434            synchronized (mPackages) {
5435                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
5436            }
5437            if (ps.signatures.mSignatures != null
5438                    && ps.signatures.mSignatures.length != 0
5439                    && signingKs != null) {
5440                // Optimization: reuse the existing cached certificates
5441                // if the package appears to be unchanged.
5442                pkg.mSignatures = ps.signatures.mSignatures;
5443                pkg.mSigningKeys = signingKs;
5444                return;
5445            }
5446
5447            Slog.w(TAG, "PackageSetting for " + ps.name
5448                    + " is missing signatures.  Collecting certs again to recover them.");
5449        } else {
5450            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
5451        }
5452
5453        try {
5454            pp.collectCertificates(pkg, parseFlags);
5455            pp.collectManifestDigest(pkg);
5456        } catch (PackageParserException e) {
5457            throw PackageManagerException.from(e);
5458        }
5459    }
5460
5461    /*
5462     *  Scan a package and return the newly parsed package.
5463     *  Returns null in case of errors and the error code is stored in mLastScanError
5464     */
5465    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
5466            long currentTime, UserHandle user) throws PackageManagerException {
5467        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
5468        parseFlags |= mDefParseFlags;
5469        PackageParser pp = new PackageParser();
5470        pp.setSeparateProcesses(mSeparateProcesses);
5471        pp.setOnlyCoreApps(mOnlyCore);
5472        pp.setDisplayMetrics(mMetrics);
5473
5474        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
5475            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
5476        }
5477
5478        final PackageParser.Package pkg;
5479        try {
5480            pkg = pp.parsePackage(scanFile, parseFlags);
5481        } catch (PackageParserException e) {
5482            throw PackageManagerException.from(e);
5483        }
5484
5485        PackageSetting ps = null;
5486        PackageSetting updatedPkg;
5487        // reader
5488        synchronized (mPackages) {
5489            // Look to see if we already know about this package.
5490            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
5491            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
5492                // This package has been renamed to its original name.  Let's
5493                // use that.
5494                ps = mSettings.peekPackageLPr(oldName);
5495            }
5496            // If there was no original package, see one for the real package name.
5497            if (ps == null) {
5498                ps = mSettings.peekPackageLPr(pkg.packageName);
5499            }
5500            // Check to see if this package could be hiding/updating a system
5501            // package.  Must look for it either under the original or real
5502            // package name depending on our state.
5503            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
5504            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
5505        }
5506        boolean updatedPkgBetter = false;
5507        // First check if this is a system package that may involve an update
5508        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5509            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
5510            // it needs to drop FLAG_PRIVILEGED.
5511            if (locationIsPrivileged(scanFile)) {
5512                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5513            } else {
5514                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5515            }
5516
5517            if (ps != null && !ps.codePath.equals(scanFile)) {
5518                // The path has changed from what was last scanned...  check the
5519                // version of the new path against what we have stored to determine
5520                // what to do.
5521                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
5522                if (pkg.mVersionCode <= ps.versionCode) {
5523                    // The system package has been updated and the code path does not match
5524                    // Ignore entry. Skip it.
5525                    Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5526                            + " ignored: updated version " + ps.versionCode
5527                            + " better than this " + pkg.mVersionCode);
5528                    if (!updatedPkg.codePath.equals(scanFile)) {
5529                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5530                                + ps.name + " changing from " + updatedPkg.codePathString
5531                                + " to " + scanFile);
5532                        updatedPkg.codePath = scanFile;
5533                        updatedPkg.codePathString = scanFile.toString();
5534                        updatedPkg.resourcePath = scanFile;
5535                        updatedPkg.resourcePathString = scanFile.toString();
5536                    }
5537                    updatedPkg.pkg = pkg;
5538                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null);
5539                } else {
5540                    // The current app on the system partition is better than
5541                    // what we have updated to on the data partition; switch
5542                    // back to the system partition version.
5543                    // At this point, its safely assumed that package installation for
5544                    // apps in system partition will go through. If not there won't be a working
5545                    // version of the app
5546                    // writer
5547                    synchronized (mPackages) {
5548                        // Just remove the loaded entries from package lists.
5549                        mPackages.remove(ps.name);
5550                    }
5551
5552                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5553                            + " reverting from " + ps.codePathString
5554                            + ": new version " + pkg.mVersionCode
5555                            + " better than installed " + ps.versionCode);
5556
5557                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5558                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5559                    synchronized (mInstallLock) {
5560                        args.cleanUpResourcesLI();
5561                    }
5562                    synchronized (mPackages) {
5563                        mSettings.enableSystemPackageLPw(ps.name);
5564                    }
5565                    updatedPkgBetter = true;
5566                }
5567            }
5568        }
5569
5570        if (updatedPkg != null) {
5571            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5572            // initially
5573            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5574
5575            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5576            // flag set initially
5577            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5578                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5579            }
5580        }
5581
5582        // Verify certificates against what was last scanned
5583        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5584
5585        /*
5586         * A new system app appeared, but we already had a non-system one of the
5587         * same name installed earlier.
5588         */
5589        boolean shouldHideSystemApp = false;
5590        if (updatedPkg == null && ps != null
5591                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5592            /*
5593             * Check to make sure the signatures match first. If they don't,
5594             * wipe the installed application and its data.
5595             */
5596            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5597                    != PackageManager.SIGNATURE_MATCH) {
5598                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5599                        + " signatures don't match existing userdata copy; removing");
5600                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5601                ps = null;
5602            } else {
5603                /*
5604                 * If the newly-added system app is an older version than the
5605                 * already installed version, hide it. It will be scanned later
5606                 * and re-added like an update.
5607                 */
5608                if (pkg.mVersionCode <= ps.versionCode) {
5609                    shouldHideSystemApp = true;
5610                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5611                            + " but new version " + pkg.mVersionCode + " better than installed "
5612                            + ps.versionCode + "; hiding system");
5613                } else {
5614                    /*
5615                     * The newly found system app is a newer version that the
5616                     * one previously installed. Simply remove the
5617                     * already-installed application and replace it with our own
5618                     * while keeping the application data.
5619                     */
5620                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5621                            + " reverting from " + ps.codePathString + ": new version "
5622                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5623                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5624                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5625                    synchronized (mInstallLock) {
5626                        args.cleanUpResourcesLI();
5627                    }
5628                }
5629            }
5630        }
5631
5632        // The apk is forward locked (not public) if its code and resources
5633        // are kept in different files. (except for app in either system or
5634        // vendor path).
5635        // TODO grab this value from PackageSettings
5636        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5637            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5638                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5639            }
5640        }
5641
5642        // TODO: extend to support forward-locked splits
5643        String resourcePath = null;
5644        String baseResourcePath = null;
5645        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5646            if (ps != null && ps.resourcePathString != null) {
5647                resourcePath = ps.resourcePathString;
5648                baseResourcePath = ps.resourcePathString;
5649            } else {
5650                // Should not happen at all. Just log an error.
5651                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5652            }
5653        } else {
5654            resourcePath = pkg.codePath;
5655            baseResourcePath = pkg.baseCodePath;
5656        }
5657
5658        // Set application objects path explicitly.
5659        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
5660        pkg.applicationInfo.setCodePath(pkg.codePath);
5661        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5662        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5663        pkg.applicationInfo.setResourcePath(resourcePath);
5664        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5665        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5666
5667        // Note that we invoke the following method only if we are about to unpack an application
5668        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5669                | SCAN_UPDATE_SIGNATURE, currentTime, user);
5670
5671        /*
5672         * If the system app should be overridden by a previously installed
5673         * data, hide the system app now and let the /data/app scan pick it up
5674         * again.
5675         */
5676        if (shouldHideSystemApp) {
5677            synchronized (mPackages) {
5678                /*
5679                 * We have to grant systems permissions before we hide, because
5680                 * grantPermissions will assume the package update is trying to
5681                 * expand its permissions.
5682                 */
5683                grantPermissionsLPw(pkg, true, pkg.packageName);
5684                mSettings.disableSystemPackageLPw(pkg.packageName);
5685            }
5686        }
5687
5688        return scannedPkg;
5689    }
5690
5691    private static String fixProcessName(String defProcessName,
5692            String processName, int uid) {
5693        if (processName == null) {
5694            return defProcessName;
5695        }
5696        return processName;
5697    }
5698
5699    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
5700            throws PackageManagerException {
5701        if (pkgSetting.signatures.mSignatures != null) {
5702            // Already existing package. Make sure signatures match
5703            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
5704                    == PackageManager.SIGNATURE_MATCH;
5705            if (!match) {
5706                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
5707                        == PackageManager.SIGNATURE_MATCH;
5708            }
5709            if (!match) {
5710                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
5711                        == PackageManager.SIGNATURE_MATCH;
5712            }
5713            if (!match) {
5714                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5715                        + pkg.packageName + " signatures do not match the "
5716                        + "previously installed version; ignoring!");
5717            }
5718        }
5719
5720        // Check for shared user signatures
5721        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
5722            // Already existing package. Make sure signatures match
5723            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5724                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
5725            if (!match) {
5726                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
5727                        == PackageManager.SIGNATURE_MATCH;
5728            }
5729            if (!match) {
5730                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
5731                        == PackageManager.SIGNATURE_MATCH;
5732            }
5733            if (!match) {
5734                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
5735                        "Package " + pkg.packageName
5736                        + " has no signatures that match those in shared user "
5737                        + pkgSetting.sharedUser.name + "; ignoring!");
5738            }
5739        }
5740    }
5741
5742    /**
5743     * Enforces that only the system UID or root's UID can call a method exposed
5744     * via Binder.
5745     *
5746     * @param message used as message if SecurityException is thrown
5747     * @throws SecurityException if the caller is not system or root
5748     */
5749    private static final void enforceSystemOrRoot(String message) {
5750        final int uid = Binder.getCallingUid();
5751        if (uid != Process.SYSTEM_UID && uid != 0) {
5752            throw new SecurityException(message);
5753        }
5754    }
5755
5756    @Override
5757    public void performBootDexOpt() {
5758        enforceSystemOrRoot("Only the system can request dexopt be performed");
5759
5760        // Before everything else, see whether we need to fstrim.
5761        try {
5762            IMountService ms = PackageHelper.getMountService();
5763            if (ms != null) {
5764                final boolean isUpgrade = isUpgrade();
5765                boolean doTrim = isUpgrade;
5766                if (doTrim) {
5767                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
5768                } else {
5769                    final long interval = android.provider.Settings.Global.getLong(
5770                            mContext.getContentResolver(),
5771                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
5772                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
5773                    if (interval > 0) {
5774                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
5775                        if (timeSinceLast > interval) {
5776                            doTrim = true;
5777                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
5778                                    + "; running immediately");
5779                        }
5780                    }
5781                }
5782                if (doTrim) {
5783                    if (!isFirstBoot()) {
5784                        try {
5785                            ActivityManagerNative.getDefault().showBootMessage(
5786                                    mContext.getResources().getString(
5787                                            R.string.android_upgrading_fstrim), true);
5788                        } catch (RemoteException e) {
5789                        }
5790                    }
5791                    ms.runMaintenance();
5792                }
5793            } else {
5794                Slog.e(TAG, "Mount service unavailable!");
5795            }
5796        } catch (RemoteException e) {
5797            // Can't happen; MountService is local
5798        }
5799
5800        final ArraySet<PackageParser.Package> pkgs;
5801        synchronized (mPackages) {
5802            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
5803        }
5804
5805        if (pkgs != null) {
5806            // Sort apps by importance for dexopt ordering. Important apps are given more priority
5807            // in case the device runs out of space.
5808            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
5809            // Give priority to core apps.
5810            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5811                PackageParser.Package pkg = it.next();
5812                if (pkg.coreApp) {
5813                    if (DEBUG_DEXOPT) {
5814                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
5815                    }
5816                    sortedPkgs.add(pkg);
5817                    it.remove();
5818                }
5819            }
5820            // Give priority to system apps that listen for pre boot complete.
5821            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
5822            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
5823            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5824                PackageParser.Package pkg = it.next();
5825                if (pkgNames.contains(pkg.packageName)) {
5826                    if (DEBUG_DEXOPT) {
5827                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
5828                    }
5829                    sortedPkgs.add(pkg);
5830                    it.remove();
5831                }
5832            }
5833            // Give priority to system apps.
5834            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5835                PackageParser.Package pkg = it.next();
5836                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
5837                    if (DEBUG_DEXOPT) {
5838                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
5839                    }
5840                    sortedPkgs.add(pkg);
5841                    it.remove();
5842                }
5843            }
5844            // Give priority to updated system apps.
5845            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5846                PackageParser.Package pkg = it.next();
5847                if (pkg.isUpdatedSystemApp()) {
5848                    if (DEBUG_DEXOPT) {
5849                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
5850                    }
5851                    sortedPkgs.add(pkg);
5852                    it.remove();
5853                }
5854            }
5855            // Give priority to apps that listen for boot complete.
5856            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
5857            pkgNames = getPackageNamesForIntent(intent);
5858            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5859                PackageParser.Package pkg = it.next();
5860                if (pkgNames.contains(pkg.packageName)) {
5861                    if (DEBUG_DEXOPT) {
5862                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
5863                    }
5864                    sortedPkgs.add(pkg);
5865                    it.remove();
5866                }
5867            }
5868            // Filter out packages that aren't recently used.
5869            filterRecentlyUsedApps(pkgs);
5870            // Add all remaining apps.
5871            for (PackageParser.Package pkg : pkgs) {
5872                if (DEBUG_DEXOPT) {
5873                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
5874                }
5875                sortedPkgs.add(pkg);
5876            }
5877
5878            // If we want to be lazy, filter everything that wasn't recently used.
5879            if (mLazyDexOpt) {
5880                filterRecentlyUsedApps(sortedPkgs);
5881            }
5882
5883            int i = 0;
5884            int total = sortedPkgs.size();
5885            File dataDir = Environment.getDataDirectory();
5886            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
5887            if (lowThreshold == 0) {
5888                throw new IllegalStateException("Invalid low memory threshold");
5889            }
5890            for (PackageParser.Package pkg : sortedPkgs) {
5891                long usableSpace = dataDir.getUsableSpace();
5892                if (usableSpace < lowThreshold) {
5893                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
5894                    break;
5895                }
5896                performBootDexOpt(pkg, ++i, total);
5897            }
5898        }
5899    }
5900
5901    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
5902        // Filter out packages that aren't recently used.
5903        //
5904        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
5905        // should do a full dexopt.
5906        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
5907            int total = pkgs.size();
5908            int skipped = 0;
5909            long now = System.currentTimeMillis();
5910            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
5911                PackageParser.Package pkg = i.next();
5912                long then = pkg.mLastPackageUsageTimeInMills;
5913                if (then + mDexOptLRUThresholdInMills < now) {
5914                    if (DEBUG_DEXOPT) {
5915                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
5916                              ((then == 0) ? "never" : new Date(then)));
5917                    }
5918                    i.remove();
5919                    skipped++;
5920                }
5921            }
5922            if (DEBUG_DEXOPT) {
5923                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
5924            }
5925        }
5926    }
5927
5928    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
5929        List<ResolveInfo> ris = null;
5930        try {
5931            ris = AppGlobals.getPackageManager().queryIntentReceivers(
5932                    intent, null, 0, UserHandle.USER_OWNER);
5933        } catch (RemoteException e) {
5934        }
5935        ArraySet<String> pkgNames = new ArraySet<String>();
5936        if (ris != null) {
5937            for (ResolveInfo ri : ris) {
5938                pkgNames.add(ri.activityInfo.packageName);
5939            }
5940        }
5941        return pkgNames;
5942    }
5943
5944    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
5945        if (DEBUG_DEXOPT) {
5946            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
5947        }
5948        if (!isFirstBoot()) {
5949            try {
5950                ActivityManagerNative.getDefault().showBootMessage(
5951                        mContext.getResources().getString(R.string.android_upgrading_apk,
5952                                curr, total), true);
5953            } catch (RemoteException e) {
5954            }
5955        }
5956        PackageParser.Package p = pkg;
5957        synchronized (mInstallLock) {
5958            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
5959                    false /* force dex */, false /* defer */, true /* include dependencies */);
5960        }
5961    }
5962
5963    @Override
5964    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
5965        return performDexOpt(packageName, instructionSet, false);
5966    }
5967
5968    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
5969        boolean dexopt = mLazyDexOpt || backgroundDexopt;
5970        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
5971        if (!dexopt && !updateUsage) {
5972            // We aren't going to dexopt or update usage, so bail early.
5973            return false;
5974        }
5975        PackageParser.Package p;
5976        final String targetInstructionSet;
5977        synchronized (mPackages) {
5978            p = mPackages.get(packageName);
5979            if (p == null) {
5980                return false;
5981            }
5982            if (updateUsage) {
5983                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
5984            }
5985            mPackageUsage.write(false);
5986            if (!dexopt) {
5987                // We aren't going to dexopt, so bail early.
5988                return false;
5989            }
5990
5991            targetInstructionSet = instructionSet != null ? instructionSet :
5992                    getPrimaryInstructionSet(p.applicationInfo);
5993            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
5994                return false;
5995            }
5996        }
5997
5998        synchronized (mInstallLock) {
5999            final String[] instructionSets = new String[] { targetInstructionSet };
6000            int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6001                    false /* forceDex */, false /* defer */, true /* inclDependencies */);
6002            return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6003        }
6004    }
6005
6006    public ArraySet<String> getPackagesThatNeedDexOpt() {
6007        ArraySet<String> pkgs = null;
6008        synchronized (mPackages) {
6009            for (PackageParser.Package p : mPackages.values()) {
6010                if (DEBUG_DEXOPT) {
6011                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6012                }
6013                if (!p.mDexOptPerformed.isEmpty()) {
6014                    continue;
6015                }
6016                if (pkgs == null) {
6017                    pkgs = new ArraySet<String>();
6018                }
6019                pkgs.add(p.packageName);
6020            }
6021        }
6022        return pkgs;
6023    }
6024
6025    public void shutdown() {
6026        mPackageUsage.write(true);
6027    }
6028
6029    @Override
6030    public void forceDexOpt(String packageName) {
6031        enforceSystemOrRoot("forceDexOpt");
6032
6033        PackageParser.Package pkg;
6034        synchronized (mPackages) {
6035            pkg = mPackages.get(packageName);
6036            if (pkg == null) {
6037                throw new IllegalArgumentException("Missing package: " + packageName);
6038            }
6039        }
6040
6041        synchronized (mInstallLock) {
6042            final String[] instructionSets = new String[] {
6043                    getPrimaryInstructionSet(pkg.applicationInfo) };
6044            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6045                    true /*forceDex*/, false /* defer */, true /* inclDependencies */);
6046            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6047                throw new IllegalStateException("Failed to dexopt: " + res);
6048            }
6049        }
6050    }
6051
6052    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6053        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6054            Slog.w(TAG, "Unable to update from " + oldPkg.name
6055                    + " to " + newPkg.packageName
6056                    + ": old package not in system partition");
6057            return false;
6058        } else if (mPackages.get(oldPkg.name) != null) {
6059            Slog.w(TAG, "Unable to update from " + oldPkg.name
6060                    + " to " + newPkg.packageName
6061                    + ": old package still exists");
6062            return false;
6063        }
6064        return true;
6065    }
6066
6067    private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
6068        int[] users = sUserManager.getUserIds();
6069        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
6070        if (res < 0) {
6071            return res;
6072        }
6073        for (int user : users) {
6074            if (user != 0) {
6075                res = mInstaller.createUserData(volumeUuid, packageName,
6076                        UserHandle.getUid(user, uid), user, seinfo);
6077                if (res < 0) {
6078                    return res;
6079                }
6080            }
6081        }
6082        return res;
6083    }
6084
6085    private int removeDataDirsLI(String volumeUuid, String packageName) {
6086        int[] users = sUserManager.getUserIds();
6087        int res = 0;
6088        for (int user : users) {
6089            int resInner = mInstaller.remove(volumeUuid, packageName, user);
6090            if (resInner < 0) {
6091                res = resInner;
6092            }
6093        }
6094
6095        return res;
6096    }
6097
6098    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6099        int[] users = sUserManager.getUserIds();
6100        int res = 0;
6101        for (int user : users) {
6102            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
6103            if (resInner < 0) {
6104                res = resInner;
6105            }
6106        }
6107        return res;
6108    }
6109
6110    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6111            PackageParser.Package changingLib) {
6112        if (file.path != null) {
6113            usesLibraryFiles.add(file.path);
6114            return;
6115        }
6116        PackageParser.Package p = mPackages.get(file.apk);
6117        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6118            // If we are doing this while in the middle of updating a library apk,
6119            // then we need to make sure to use that new apk for determining the
6120            // dependencies here.  (We haven't yet finished committing the new apk
6121            // to the package manager state.)
6122            if (p == null || p.packageName.equals(changingLib.packageName)) {
6123                p = changingLib;
6124            }
6125        }
6126        if (p != null) {
6127            usesLibraryFiles.addAll(p.getAllCodePaths());
6128        }
6129    }
6130
6131    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6132            PackageParser.Package changingLib) throws PackageManagerException {
6133        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6134            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6135            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6136            for (int i=0; i<N; i++) {
6137                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6138                if (file == null) {
6139                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6140                            "Package " + pkg.packageName + " requires unavailable shared library "
6141                            + pkg.usesLibraries.get(i) + "; failing!");
6142                }
6143                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6144            }
6145            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6146            for (int i=0; i<N; i++) {
6147                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6148                if (file == null) {
6149                    Slog.w(TAG, "Package " + pkg.packageName
6150                            + " desires unavailable shared library "
6151                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6152                } else {
6153                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6154                }
6155            }
6156            N = usesLibraryFiles.size();
6157            if (N > 0) {
6158                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6159            } else {
6160                pkg.usesLibraryFiles = null;
6161            }
6162        }
6163    }
6164
6165    private static boolean hasString(List<String> list, List<String> which) {
6166        if (list == null) {
6167            return false;
6168        }
6169        for (int i=list.size()-1; i>=0; i--) {
6170            for (int j=which.size()-1; j>=0; j--) {
6171                if (which.get(j).equals(list.get(i))) {
6172                    return true;
6173                }
6174            }
6175        }
6176        return false;
6177    }
6178
6179    private void updateAllSharedLibrariesLPw() {
6180        for (PackageParser.Package pkg : mPackages.values()) {
6181            try {
6182                updateSharedLibrariesLPw(pkg, null);
6183            } catch (PackageManagerException e) {
6184                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6185            }
6186        }
6187    }
6188
6189    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6190            PackageParser.Package changingPkg) {
6191        ArrayList<PackageParser.Package> res = null;
6192        for (PackageParser.Package pkg : mPackages.values()) {
6193            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6194                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6195                if (res == null) {
6196                    res = new ArrayList<PackageParser.Package>();
6197                }
6198                res.add(pkg);
6199                try {
6200                    updateSharedLibrariesLPw(pkg, changingPkg);
6201                } catch (PackageManagerException e) {
6202                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6203                }
6204            }
6205        }
6206        return res;
6207    }
6208
6209    /**
6210     * Derive the value of the {@code cpuAbiOverride} based on the provided
6211     * value and an optional stored value from the package settings.
6212     */
6213    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6214        String cpuAbiOverride = null;
6215
6216        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6217            cpuAbiOverride = null;
6218        } else if (abiOverride != null) {
6219            cpuAbiOverride = abiOverride;
6220        } else if (settings != null) {
6221            cpuAbiOverride = settings.cpuAbiOverrideString;
6222        }
6223
6224        return cpuAbiOverride;
6225    }
6226
6227    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6228            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6229        boolean success = false;
6230        try {
6231            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6232                    currentTime, user);
6233            success = true;
6234            return res;
6235        } finally {
6236            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6237                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6238            }
6239        }
6240    }
6241
6242    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6243            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6244        final File scanFile = new File(pkg.codePath);
6245        if (pkg.applicationInfo.getCodePath() == null ||
6246                pkg.applicationInfo.getResourcePath() == null) {
6247            // Bail out. The resource and code paths haven't been set.
6248            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6249                    "Code and resource paths haven't been set correctly");
6250        }
6251
6252        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6253            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6254        } else {
6255            // Only allow system apps to be flagged as core apps.
6256            pkg.coreApp = false;
6257        }
6258
6259        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6260            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6261        }
6262
6263        if (mCustomResolverComponentName != null &&
6264                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6265            setUpCustomResolverActivity(pkg);
6266        }
6267
6268        if (pkg.packageName.equals("android")) {
6269            synchronized (mPackages) {
6270                if (mAndroidApplication != null) {
6271                    Slog.w(TAG, "*************************************************");
6272                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6273                    Slog.w(TAG, " file=" + scanFile);
6274                    Slog.w(TAG, "*************************************************");
6275                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6276                            "Core android package being redefined.  Skipping.");
6277                }
6278
6279                // Set up information for our fall-back user intent resolution activity.
6280                mPlatformPackage = pkg;
6281                pkg.mVersionCode = mSdkVersion;
6282                mAndroidApplication = pkg.applicationInfo;
6283
6284                if (!mResolverReplaced) {
6285                    mResolveActivity.applicationInfo = mAndroidApplication;
6286                    mResolveActivity.name = ResolverActivity.class.getName();
6287                    mResolveActivity.packageName = mAndroidApplication.packageName;
6288                    mResolveActivity.processName = "system:ui";
6289                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6290                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6291                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6292                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6293                    mResolveActivity.exported = true;
6294                    mResolveActivity.enabled = true;
6295                    mResolveInfo.activityInfo = mResolveActivity;
6296                    mResolveInfo.priority = 0;
6297                    mResolveInfo.preferredOrder = 0;
6298                    mResolveInfo.match = 0;
6299                    mResolveComponentName = new ComponentName(
6300                            mAndroidApplication.packageName, mResolveActivity.name);
6301                }
6302            }
6303        }
6304
6305        if (DEBUG_PACKAGE_SCANNING) {
6306            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6307                Log.d(TAG, "Scanning package " + pkg.packageName);
6308        }
6309
6310        if (mPackages.containsKey(pkg.packageName)
6311                || mSharedLibraries.containsKey(pkg.packageName)) {
6312            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6313                    "Application package " + pkg.packageName
6314                    + " already installed.  Skipping duplicate.");
6315        }
6316
6317        // If we're only installing presumed-existing packages, require that the
6318        // scanned APK is both already known and at the path previously established
6319        // for it.  Previously unknown packages we pick up normally, but if we have an
6320        // a priori expectation about this package's install presence, enforce it.
6321        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6322            PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6323            if (known != null) {
6324                if (DEBUG_PACKAGE_SCANNING) {
6325                    Log.d(TAG, "Examining " + pkg.codePath
6326                            + " and requiring known paths " + known.codePathString
6327                            + " & " + known.resourcePathString);
6328                }
6329                if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6330                        || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6331                    throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6332                            "Application package " + pkg.packageName
6333                            + " found at " + pkg.applicationInfo.getCodePath()
6334                            + " but expected at " + known.codePathString + "; ignoring.");
6335                }
6336            }
6337        }
6338
6339        // Initialize package source and resource directories
6340        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6341        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6342
6343        SharedUserSetting suid = null;
6344        PackageSetting pkgSetting = null;
6345
6346        if (!isSystemApp(pkg)) {
6347            // Only system apps can use these features.
6348            pkg.mOriginalPackages = null;
6349            pkg.mRealPackage = null;
6350            pkg.mAdoptPermissions = null;
6351        }
6352
6353        // writer
6354        synchronized (mPackages) {
6355            if (pkg.mSharedUserId != null) {
6356                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6357                if (suid == null) {
6358                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6359                            "Creating application package " + pkg.packageName
6360                            + " for shared user failed");
6361                }
6362                if (DEBUG_PACKAGE_SCANNING) {
6363                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6364                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6365                                + "): packages=" + suid.packages);
6366                }
6367            }
6368
6369            // Check if we are renaming from an original package name.
6370            PackageSetting origPackage = null;
6371            String realName = null;
6372            if (pkg.mOriginalPackages != null) {
6373                // This package may need to be renamed to a previously
6374                // installed name.  Let's check on that...
6375                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
6376                if (pkg.mOriginalPackages.contains(renamed)) {
6377                    // This package had originally been installed as the
6378                    // original name, and we have already taken care of
6379                    // transitioning to the new one.  Just update the new
6380                    // one to continue using the old name.
6381                    realName = pkg.mRealPackage;
6382                    if (!pkg.packageName.equals(renamed)) {
6383                        // Callers into this function may have already taken
6384                        // care of renaming the package; only do it here if
6385                        // it is not already done.
6386                        pkg.setPackageName(renamed);
6387                    }
6388
6389                } else {
6390                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
6391                        if ((origPackage = mSettings.peekPackageLPr(
6392                                pkg.mOriginalPackages.get(i))) != null) {
6393                            // We do have the package already installed under its
6394                            // original name...  should we use it?
6395                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
6396                                // New package is not compatible with original.
6397                                origPackage = null;
6398                                continue;
6399                            } else if (origPackage.sharedUser != null) {
6400                                // Make sure uid is compatible between packages.
6401                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6402                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6403                                            + " to " + pkg.packageName + ": old uid "
6404                                            + origPackage.sharedUser.name
6405                                            + " differs from " + pkg.mSharedUserId);
6406                                    origPackage = null;
6407                                    continue;
6408                                }
6409                            } else {
6410                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6411                                        + pkg.packageName + " to old name " + origPackage.name);
6412                            }
6413                            break;
6414                        }
6415                    }
6416                }
6417            }
6418
6419            if (mTransferedPackages.contains(pkg.packageName)) {
6420                Slog.w(TAG, "Package " + pkg.packageName
6421                        + " was transferred to another, but its .apk remains");
6422            }
6423
6424            // Just create the setting, don't add it yet. For already existing packages
6425            // the PkgSetting exists already and doesn't have to be created.
6426            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6427                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6428                    pkg.applicationInfo.primaryCpuAbi,
6429                    pkg.applicationInfo.secondaryCpuAbi,
6430                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6431                    user, false);
6432            if (pkgSetting == null) {
6433                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6434                        "Creating application package " + pkg.packageName + " failed");
6435            }
6436
6437            if (pkgSetting.origPackage != null) {
6438                // If we are first transitioning from an original package,
6439                // fix up the new package's name now.  We need to do this after
6440                // looking up the package under its new name, so getPackageLP
6441                // can take care of fiddling things correctly.
6442                pkg.setPackageName(origPackage.name);
6443
6444                // File a report about this.
6445                String msg = "New package " + pkgSetting.realName
6446                        + " renamed to replace old package " + pkgSetting.name;
6447                reportSettingsProblem(Log.WARN, msg);
6448
6449                // Make a note of it.
6450                mTransferedPackages.add(origPackage.name);
6451
6452                // No longer need to retain this.
6453                pkgSetting.origPackage = null;
6454            }
6455
6456            if (realName != null) {
6457                // Make a note of it.
6458                mTransferedPackages.add(pkg.packageName);
6459            }
6460
6461            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6462                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6463            }
6464
6465            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6466                // Check all shared libraries and map to their actual file path.
6467                // We only do this here for apps not on a system dir, because those
6468                // are the only ones that can fail an install due to this.  We
6469                // will take care of the system apps by updating all of their
6470                // library paths after the scan is done.
6471                updateSharedLibrariesLPw(pkg, null);
6472            }
6473
6474            if (mFoundPolicyFile) {
6475                SELinuxMMAC.assignSeinfoValue(pkg);
6476            }
6477
6478            pkg.applicationInfo.uid = pkgSetting.appId;
6479            pkg.mExtras = pkgSetting;
6480            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
6481                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
6482                    // We just determined the app is signed correctly, so bring
6483                    // over the latest parsed certs.
6484                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6485                } else {
6486                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6487                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6488                                "Package " + pkg.packageName + " upgrade keys do not match the "
6489                                + "previously installed version");
6490                    } else {
6491                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
6492                        String msg = "System package " + pkg.packageName
6493                            + " signature changed; retaining data.";
6494                        reportSettingsProblem(Log.WARN, msg);
6495                    }
6496                }
6497            } else {
6498                try {
6499                    verifySignaturesLP(pkgSetting, pkg);
6500                    // We just determined the app is signed correctly, so bring
6501                    // over the latest parsed certs.
6502                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6503                } catch (PackageManagerException e) {
6504                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6505                        throw e;
6506                    }
6507                    // The signature has changed, but this package is in the system
6508                    // image...  let's recover!
6509                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6510                    // However...  if this package is part of a shared user, but it
6511                    // doesn't match the signature of the shared user, let's fail.
6512                    // What this means is that you can't change the signatures
6513                    // associated with an overall shared user, which doesn't seem all
6514                    // that unreasonable.
6515                    if (pkgSetting.sharedUser != null) {
6516                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6517                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
6518                            throw new PackageManagerException(
6519                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
6520                                            "Signature mismatch for shared user : "
6521                                            + pkgSetting.sharedUser);
6522                        }
6523                    }
6524                    // File a report about this.
6525                    String msg = "System package " + pkg.packageName
6526                        + " signature changed; retaining data.";
6527                    reportSettingsProblem(Log.WARN, msg);
6528                }
6529            }
6530            // Verify that this new package doesn't have any content providers
6531            // that conflict with existing packages.  Only do this if the
6532            // package isn't already installed, since we don't want to break
6533            // things that are installed.
6534            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6535                final int N = pkg.providers.size();
6536                int i;
6537                for (i=0; i<N; i++) {
6538                    PackageParser.Provider p = pkg.providers.get(i);
6539                    if (p.info.authority != null) {
6540                        String names[] = p.info.authority.split(";");
6541                        for (int j = 0; j < names.length; j++) {
6542                            if (mProvidersByAuthority.containsKey(names[j])) {
6543                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6544                                final String otherPackageName =
6545                                        ((other != null && other.getComponentName() != null) ?
6546                                                other.getComponentName().getPackageName() : "?");
6547                                throw new PackageManagerException(
6548                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
6549                                                "Can't install because provider name " + names[j]
6550                                                + " (in package " + pkg.applicationInfo.packageName
6551                                                + ") is already used by " + otherPackageName);
6552                            }
6553                        }
6554                    }
6555                }
6556            }
6557
6558            if (pkg.mAdoptPermissions != null) {
6559                // This package wants to adopt ownership of permissions from
6560                // another package.
6561                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6562                    final String origName = pkg.mAdoptPermissions.get(i);
6563                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
6564                    if (orig != null) {
6565                        if (verifyPackageUpdateLPr(orig, pkg)) {
6566                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
6567                                    + pkg.packageName);
6568                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
6569                        }
6570                    }
6571                }
6572            }
6573        }
6574
6575        final String pkgName = pkg.packageName;
6576
6577        final long scanFileTime = scanFile.lastModified();
6578        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6579        pkg.applicationInfo.processName = fixProcessName(
6580                pkg.applicationInfo.packageName,
6581                pkg.applicationInfo.processName,
6582                pkg.applicationInfo.uid);
6583
6584        File dataPath;
6585        if (mPlatformPackage == pkg) {
6586            // The system package is special.
6587            dataPath = new File(Environment.getDataDirectory(), "system");
6588
6589            pkg.applicationInfo.dataDir = dataPath.getPath();
6590
6591        } else {
6592            // This is a normal package, need to make its data directory.
6593            dataPath = PackageManager.getDataDirForUser(pkg.volumeUuid, pkg.packageName,
6594                    UserHandle.USER_OWNER);
6595
6596            boolean uidError = false;
6597            if (dataPath.exists()) {
6598                int currentUid = 0;
6599                try {
6600                    StructStat stat = Os.stat(dataPath.getPath());
6601                    currentUid = stat.st_uid;
6602                } catch (ErrnoException e) {
6603                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6604                }
6605
6606                // If we have mismatched owners for the data path, we have a problem.
6607                if (currentUid != pkg.applicationInfo.uid) {
6608                    boolean recovered = false;
6609                    if (currentUid == 0) {
6610                        // The directory somehow became owned by root.  Wow.
6611                        // This is probably because the system was stopped while
6612                        // installd was in the middle of messing with its libs
6613                        // directory.  Ask installd to fix that.
6614                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
6615                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
6616                        if (ret >= 0) {
6617                            recovered = true;
6618                            String msg = "Package " + pkg.packageName
6619                                    + " unexpectedly changed to uid 0; recovered to " +
6620                                    + pkg.applicationInfo.uid;
6621                            reportSettingsProblem(Log.WARN, msg);
6622                        }
6623                    }
6624                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6625                            || (scanFlags&SCAN_BOOTING) != 0)) {
6626                        // If this is a system app, we can at least delete its
6627                        // current data so the application will still work.
6628                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
6629                        if (ret >= 0) {
6630                            // TODO: Kill the processes first
6631                            // Old data gone!
6632                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6633                                    ? "System package " : "Third party package ";
6634                            String msg = prefix + pkg.packageName
6635                                    + " has changed from uid: "
6636                                    + currentUid + " to "
6637                                    + pkg.applicationInfo.uid + "; old data erased";
6638                            reportSettingsProblem(Log.WARN, msg);
6639                            recovered = true;
6640
6641                            // And now re-install the app.
6642                            ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6643                                    pkg.applicationInfo.seinfo);
6644                            if (ret == -1) {
6645                                // Ack should not happen!
6646                                msg = prefix + pkg.packageName
6647                                        + " could not have data directory re-created after delete.";
6648                                reportSettingsProblem(Log.WARN, msg);
6649                                throw new PackageManagerException(
6650                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6651                            }
6652                        }
6653                        if (!recovered) {
6654                            mHasSystemUidErrors = true;
6655                        }
6656                    } else if (!recovered) {
6657                        // If we allow this install to proceed, we will be broken.
6658                        // Abort, abort!
6659                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
6660                                "scanPackageLI");
6661                    }
6662                    if (!recovered) {
6663                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
6664                            + pkg.applicationInfo.uid + "/fs_"
6665                            + currentUid;
6666                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
6667                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
6668                        String msg = "Package " + pkg.packageName
6669                                + " has mismatched uid: "
6670                                + currentUid + " on disk, "
6671                                + pkg.applicationInfo.uid + " in settings";
6672                        // writer
6673                        synchronized (mPackages) {
6674                            mSettings.mReadMessages.append(msg);
6675                            mSettings.mReadMessages.append('\n');
6676                            uidError = true;
6677                            if (!pkgSetting.uidError) {
6678                                reportSettingsProblem(Log.ERROR, msg);
6679                            }
6680                        }
6681                    }
6682                }
6683                pkg.applicationInfo.dataDir = dataPath.getPath();
6684                if (mShouldRestoreconData) {
6685                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
6686                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
6687                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
6688                }
6689            } else {
6690                if (DEBUG_PACKAGE_SCANNING) {
6691                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6692                        Log.v(TAG, "Want this data dir: " + dataPath);
6693                }
6694                //invoke installer to do the actual installation
6695                int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6696                        pkg.applicationInfo.seinfo);
6697                if (ret < 0) {
6698                    // Error from installer
6699                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6700                            "Unable to create data dirs [errorCode=" + ret + "]");
6701                }
6702
6703                if (dataPath.exists()) {
6704                    pkg.applicationInfo.dataDir = dataPath.getPath();
6705                } else {
6706                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
6707                    pkg.applicationInfo.dataDir = null;
6708                }
6709            }
6710
6711            pkgSetting.uidError = uidError;
6712        }
6713
6714        final String path = scanFile.getPath();
6715        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
6716
6717        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
6718            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
6719
6720            // Some system apps still use directory structure for native libraries
6721            // in which case we might end up not detecting abi solely based on apk
6722            // structure. Try to detect abi based on directory structure.
6723            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
6724                    pkg.applicationInfo.primaryCpuAbi == null) {
6725                setBundledAppAbisAndRoots(pkg, pkgSetting);
6726                setNativeLibraryPaths(pkg);
6727            }
6728
6729        } else {
6730            if ((scanFlags & SCAN_MOVE) != 0) {
6731                // We haven't run dex-opt for this move (since we've moved the compiled output too)
6732                // but we already have this packages package info in the PackageSetting. We just
6733                // use that and derive the native library path based on the new codepath.
6734                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
6735                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
6736            }
6737
6738            // Set native library paths again. For moves, the path will be updated based on the
6739            // ABIs we've determined above. For non-moves, the path will be updated based on the
6740            // ABIs we determined during compilation, but the path will depend on the final
6741            // package path (after the rename away from the stage path).
6742            setNativeLibraryPaths(pkg);
6743        }
6744
6745        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
6746        final int[] userIds = sUserManager.getUserIds();
6747        synchronized (mInstallLock) {
6748            // Create a native library symlink only if we have native libraries
6749            // and if the native libraries are 32 bit libraries. We do not provide
6750            // this symlink for 64 bit libraries.
6751            if (pkg.applicationInfo.primaryCpuAbi != null &&
6752                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
6753                final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
6754                for (int userId : userIds) {
6755                    if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
6756                            nativeLibPath, userId) < 0) {
6757                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
6758                                "Failed linking native library dir (user=" + userId + ")");
6759                    }
6760                }
6761            }
6762        }
6763
6764        // This is a special case for the "system" package, where the ABI is
6765        // dictated by the zygote configuration (and init.rc). We should keep track
6766        // of this ABI so that we can deal with "normal" applications that run under
6767        // the same UID correctly.
6768        if (mPlatformPackage == pkg) {
6769            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
6770                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
6771        }
6772
6773        // If there's a mismatch between the abi-override in the package setting
6774        // and the abiOverride specified for the install. Warn about this because we
6775        // would've already compiled the app without taking the package setting into
6776        // account.
6777        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
6778            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
6779                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
6780                        " for package: " + pkg.packageName);
6781            }
6782        }
6783
6784        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6785        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6786        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
6787
6788        // Copy the derived override back to the parsed package, so that we can
6789        // update the package settings accordingly.
6790        pkg.cpuAbiOverride = cpuAbiOverride;
6791
6792        if (DEBUG_ABI_SELECTION) {
6793            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
6794                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
6795                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
6796        }
6797
6798        // Push the derived path down into PackageSettings so we know what to
6799        // clean up at uninstall time.
6800        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
6801
6802        if (DEBUG_ABI_SELECTION) {
6803            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
6804                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
6805                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
6806        }
6807
6808        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
6809            // We don't do this here during boot because we can do it all
6810            // at once after scanning all existing packages.
6811            //
6812            // We also do this *before* we perform dexopt on this package, so that
6813            // we can avoid redundant dexopts, and also to make sure we've got the
6814            // code and package path correct.
6815            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
6816                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
6817        }
6818
6819        if ((scanFlags & SCAN_NO_DEX) == 0) {
6820            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
6821                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */);
6822            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6823                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
6824            }
6825        }
6826        if (mFactoryTest && pkg.requestedPermissions.contains(
6827                android.Manifest.permission.FACTORY_TEST)) {
6828            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
6829        }
6830
6831        ArrayList<PackageParser.Package> clientLibPkgs = null;
6832
6833        // writer
6834        synchronized (mPackages) {
6835            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6836                // Only system apps can add new shared libraries.
6837                if (pkg.libraryNames != null) {
6838                    for (int i=0; i<pkg.libraryNames.size(); i++) {
6839                        String name = pkg.libraryNames.get(i);
6840                        boolean allowed = false;
6841                        if (pkg.isUpdatedSystemApp()) {
6842                            // New library entries can only be added through the
6843                            // system image.  This is important to get rid of a lot
6844                            // of nasty edge cases: for example if we allowed a non-
6845                            // system update of the app to add a library, then uninstalling
6846                            // the update would make the library go away, and assumptions
6847                            // we made such as through app install filtering would now
6848                            // have allowed apps on the device which aren't compatible
6849                            // with it.  Better to just have the restriction here, be
6850                            // conservative, and create many fewer cases that can negatively
6851                            // impact the user experience.
6852                            final PackageSetting sysPs = mSettings
6853                                    .getDisabledSystemPkgLPr(pkg.packageName);
6854                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
6855                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
6856                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
6857                                        allowed = true;
6858                                        allowed = true;
6859                                        break;
6860                                    }
6861                                }
6862                            }
6863                        } else {
6864                            allowed = true;
6865                        }
6866                        if (allowed) {
6867                            if (!mSharedLibraries.containsKey(name)) {
6868                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
6869                            } else if (!name.equals(pkg.packageName)) {
6870                                Slog.w(TAG, "Package " + pkg.packageName + " library "
6871                                        + name + " already exists; skipping");
6872                            }
6873                        } else {
6874                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
6875                                    + name + " that is not declared on system image; skipping");
6876                        }
6877                    }
6878                    if ((scanFlags&SCAN_BOOTING) == 0) {
6879                        // If we are not booting, we need to update any applications
6880                        // that are clients of our shared library.  If we are booting,
6881                        // this will all be done once the scan is complete.
6882                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
6883                    }
6884                }
6885            }
6886        }
6887
6888        // We also need to dexopt any apps that are dependent on this library.  Note that
6889        // if these fail, we should abort the install since installing the library will
6890        // result in some apps being broken.
6891        if (clientLibPkgs != null) {
6892            if ((scanFlags & SCAN_NO_DEX) == 0) {
6893                for (int i = 0; i < clientLibPkgs.size(); i++) {
6894                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
6895                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
6896                            null /* instruction sets */, forceDex,
6897                            (scanFlags & SCAN_DEFER_DEX) != 0, false);
6898                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6899                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
6900                                "scanPackageLI failed to dexopt clientLibPkgs");
6901                    }
6902                }
6903            }
6904        }
6905
6906        // Also need to kill any apps that are dependent on the library.
6907        if (clientLibPkgs != null) {
6908            for (int i=0; i<clientLibPkgs.size(); i++) {
6909                PackageParser.Package clientPkg = clientLibPkgs.get(i);
6910                killApplication(clientPkg.applicationInfo.packageName,
6911                        clientPkg.applicationInfo.uid, "update lib");
6912            }
6913        }
6914
6915        // Make sure we're not adding any bogus keyset info
6916        KeySetManagerService ksms = mSettings.mKeySetManagerService;
6917        ksms.assertScannedPackageValid(pkg);
6918
6919        // writer
6920        synchronized (mPackages) {
6921            // We don't expect installation to fail beyond this point
6922
6923            // Add the new setting to mSettings
6924            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
6925            // Add the new setting to mPackages
6926            mPackages.put(pkg.applicationInfo.packageName, pkg);
6927            // Make sure we don't accidentally delete its data.
6928            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
6929            while (iter.hasNext()) {
6930                PackageCleanItem item = iter.next();
6931                if (pkgName.equals(item.packageName)) {
6932                    iter.remove();
6933                }
6934            }
6935
6936            // Take care of first install / last update times.
6937            if (currentTime != 0) {
6938                if (pkgSetting.firstInstallTime == 0) {
6939                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
6940                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
6941                    pkgSetting.lastUpdateTime = currentTime;
6942                }
6943            } else if (pkgSetting.firstInstallTime == 0) {
6944                // We need *something*.  Take time time stamp of the file.
6945                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
6946            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
6947                if (scanFileTime != pkgSetting.timeStamp) {
6948                    // A package on the system image has changed; consider this
6949                    // to be an update.
6950                    pkgSetting.lastUpdateTime = scanFileTime;
6951                }
6952            }
6953
6954            // Add the package's KeySets to the global KeySetManagerService
6955            ksms.addScannedPackageLPw(pkg);
6956
6957            int N = pkg.providers.size();
6958            StringBuilder r = null;
6959            int i;
6960            for (i=0; i<N; i++) {
6961                PackageParser.Provider p = pkg.providers.get(i);
6962                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
6963                        p.info.processName, pkg.applicationInfo.uid);
6964                mProviders.addProvider(p);
6965                p.syncable = p.info.isSyncable;
6966                if (p.info.authority != null) {
6967                    String names[] = p.info.authority.split(";");
6968                    p.info.authority = null;
6969                    for (int j = 0; j < names.length; j++) {
6970                        if (j == 1 && p.syncable) {
6971                            // We only want the first authority for a provider to possibly be
6972                            // syncable, so if we already added this provider using a different
6973                            // authority clear the syncable flag. We copy the provider before
6974                            // changing it because the mProviders object contains a reference
6975                            // to a provider that we don't want to change.
6976                            // Only do this for the second authority since the resulting provider
6977                            // object can be the same for all future authorities for this provider.
6978                            p = new PackageParser.Provider(p);
6979                            p.syncable = false;
6980                        }
6981                        if (!mProvidersByAuthority.containsKey(names[j])) {
6982                            mProvidersByAuthority.put(names[j], p);
6983                            if (p.info.authority == null) {
6984                                p.info.authority = names[j];
6985                            } else {
6986                                p.info.authority = p.info.authority + ";" + names[j];
6987                            }
6988                            if (DEBUG_PACKAGE_SCANNING) {
6989                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6990                                    Log.d(TAG, "Registered content provider: " + names[j]
6991                                            + ", className = " + p.info.name + ", isSyncable = "
6992                                            + p.info.isSyncable);
6993                            }
6994                        } else {
6995                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6996                            Slog.w(TAG, "Skipping provider name " + names[j] +
6997                                    " (in package " + pkg.applicationInfo.packageName +
6998                                    "): name already used by "
6999                                    + ((other != null && other.getComponentName() != null)
7000                                            ? other.getComponentName().getPackageName() : "?"));
7001                        }
7002                    }
7003                }
7004                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7005                    if (r == null) {
7006                        r = new StringBuilder(256);
7007                    } else {
7008                        r.append(' ');
7009                    }
7010                    r.append(p.info.name);
7011                }
7012            }
7013            if (r != null) {
7014                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7015            }
7016
7017            N = pkg.services.size();
7018            r = null;
7019            for (i=0; i<N; i++) {
7020                PackageParser.Service s = pkg.services.get(i);
7021                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7022                        s.info.processName, pkg.applicationInfo.uid);
7023                mServices.addService(s);
7024                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7025                    if (r == null) {
7026                        r = new StringBuilder(256);
7027                    } else {
7028                        r.append(' ');
7029                    }
7030                    r.append(s.info.name);
7031                }
7032            }
7033            if (r != null) {
7034                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7035            }
7036
7037            N = pkg.receivers.size();
7038            r = null;
7039            for (i=0; i<N; i++) {
7040                PackageParser.Activity a = pkg.receivers.get(i);
7041                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7042                        a.info.processName, pkg.applicationInfo.uid);
7043                mReceivers.addActivity(a, "receiver");
7044                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7045                    if (r == null) {
7046                        r = new StringBuilder(256);
7047                    } else {
7048                        r.append(' ');
7049                    }
7050                    r.append(a.info.name);
7051                }
7052            }
7053            if (r != null) {
7054                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7055            }
7056
7057            N = pkg.activities.size();
7058            r = null;
7059            for (i=0; i<N; i++) {
7060                PackageParser.Activity a = pkg.activities.get(i);
7061                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7062                        a.info.processName, pkg.applicationInfo.uid);
7063                mActivities.addActivity(a, "activity");
7064                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7065                    if (r == null) {
7066                        r = new StringBuilder(256);
7067                    } else {
7068                        r.append(' ');
7069                    }
7070                    r.append(a.info.name);
7071                }
7072            }
7073            if (r != null) {
7074                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7075            }
7076
7077            N = pkg.permissionGroups.size();
7078            r = null;
7079            for (i=0; i<N; i++) {
7080                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7081                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7082                if (cur == null) {
7083                    mPermissionGroups.put(pg.info.name, pg);
7084                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7085                        if (r == null) {
7086                            r = new StringBuilder(256);
7087                        } else {
7088                            r.append(' ');
7089                        }
7090                        r.append(pg.info.name);
7091                    }
7092                } else {
7093                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7094                            + pg.info.packageName + " ignored: original from "
7095                            + cur.info.packageName);
7096                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7097                        if (r == null) {
7098                            r = new StringBuilder(256);
7099                        } else {
7100                            r.append(' ');
7101                        }
7102                        r.append("DUP:");
7103                        r.append(pg.info.name);
7104                    }
7105                }
7106            }
7107            if (r != null) {
7108                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7109            }
7110
7111            N = pkg.permissions.size();
7112            r = null;
7113            for (i=0; i<N; i++) {
7114                PackageParser.Permission p = pkg.permissions.get(i);
7115
7116                // Now that permission groups have a special meaning, we ignore permission
7117                // groups for legacy apps to prevent unexpected behavior. In particular,
7118                // permissions for one app being granted to someone just becuase they happen
7119                // to be in a group defined by another app (before this had no implications).
7120                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7121                    p.group = mPermissionGroups.get(p.info.group);
7122                    // Warn for a permission in an unknown group.
7123                    if (p.info.group != null && p.group == null) {
7124                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7125                                + p.info.packageName + " in an unknown group " + p.info.group);
7126                    }
7127                }
7128
7129                ArrayMap<String, BasePermission> permissionMap =
7130                        p.tree ? mSettings.mPermissionTrees
7131                                : mSettings.mPermissions;
7132                BasePermission bp = permissionMap.get(p.info.name);
7133
7134                // Allow system apps to redefine non-system permissions
7135                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7136                    final boolean currentOwnerIsSystem = (bp.perm != null
7137                            && isSystemApp(bp.perm.owner));
7138                    if (isSystemApp(p.owner)) {
7139                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7140                            // It's a built-in permission and no owner, take ownership now
7141                            bp.packageSetting = pkgSetting;
7142                            bp.perm = p;
7143                            bp.uid = pkg.applicationInfo.uid;
7144                            bp.sourcePackage = p.info.packageName;
7145                        } else if (!currentOwnerIsSystem) {
7146                            String msg = "New decl " + p.owner + " of permission  "
7147                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7148                            reportSettingsProblem(Log.WARN, msg);
7149                            bp = null;
7150                        }
7151                    }
7152                }
7153
7154                if (bp == null) {
7155                    bp = new BasePermission(p.info.name, p.info.packageName,
7156                            BasePermission.TYPE_NORMAL);
7157                    permissionMap.put(p.info.name, bp);
7158                }
7159
7160                if (bp.perm == null) {
7161                    if (bp.sourcePackage == null
7162                            || bp.sourcePackage.equals(p.info.packageName)) {
7163                        BasePermission tree = findPermissionTreeLP(p.info.name);
7164                        if (tree == null
7165                                || tree.sourcePackage.equals(p.info.packageName)) {
7166                            bp.packageSetting = pkgSetting;
7167                            bp.perm = p;
7168                            bp.uid = pkg.applicationInfo.uid;
7169                            bp.sourcePackage = p.info.packageName;
7170                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7171                                if (r == null) {
7172                                    r = new StringBuilder(256);
7173                                } else {
7174                                    r.append(' ');
7175                                }
7176                                r.append(p.info.name);
7177                            }
7178                        } else {
7179                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7180                                    + p.info.packageName + " ignored: base tree "
7181                                    + tree.name + " is from package "
7182                                    + tree.sourcePackage);
7183                        }
7184                    } else {
7185                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7186                                + p.info.packageName + " ignored: original from "
7187                                + bp.sourcePackage);
7188                    }
7189                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7190                    if (r == null) {
7191                        r = new StringBuilder(256);
7192                    } else {
7193                        r.append(' ');
7194                    }
7195                    r.append("DUP:");
7196                    r.append(p.info.name);
7197                }
7198                if (bp.perm == p) {
7199                    bp.protectionLevel = p.info.protectionLevel;
7200                }
7201            }
7202
7203            if (r != null) {
7204                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7205            }
7206
7207            N = pkg.instrumentation.size();
7208            r = null;
7209            for (i=0; i<N; i++) {
7210                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7211                a.info.packageName = pkg.applicationInfo.packageName;
7212                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7213                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7214                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7215                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7216                a.info.dataDir = pkg.applicationInfo.dataDir;
7217
7218                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7219                // need other information about the application, like the ABI and what not ?
7220                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7221                mInstrumentation.put(a.getComponentName(), a);
7222                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7223                    if (r == null) {
7224                        r = new StringBuilder(256);
7225                    } else {
7226                        r.append(' ');
7227                    }
7228                    r.append(a.info.name);
7229                }
7230            }
7231            if (r != null) {
7232                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7233            }
7234
7235            if (pkg.protectedBroadcasts != null) {
7236                N = pkg.protectedBroadcasts.size();
7237                for (i=0; i<N; i++) {
7238                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7239                }
7240            }
7241
7242            pkgSetting.setTimeStamp(scanFileTime);
7243
7244            // Create idmap files for pairs of (packages, overlay packages).
7245            // Note: "android", ie framework-res.apk, is handled by native layers.
7246            if (pkg.mOverlayTarget != null) {
7247                // This is an overlay package.
7248                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7249                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7250                        mOverlays.put(pkg.mOverlayTarget,
7251                                new ArrayMap<String, PackageParser.Package>());
7252                    }
7253                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7254                    map.put(pkg.packageName, pkg);
7255                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7256                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7257                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7258                                "scanPackageLI failed to createIdmap");
7259                    }
7260                }
7261            } else if (mOverlays.containsKey(pkg.packageName) &&
7262                    !pkg.packageName.equals("android")) {
7263                // This is a regular package, with one or more known overlay packages.
7264                createIdmapsForPackageLI(pkg);
7265            }
7266        }
7267
7268        return pkg;
7269    }
7270
7271    /**
7272     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7273     * is derived purely on the basis of the contents of {@code scanFile} and
7274     * {@code cpuAbiOverride}.
7275     *
7276     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7277     */
7278    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7279                                 String cpuAbiOverride, boolean extractLibs)
7280            throws PackageManagerException {
7281        // TODO: We can probably be smarter about this stuff. For installed apps,
7282        // we can calculate this information at install time once and for all. For
7283        // system apps, we can probably assume that this information doesn't change
7284        // after the first boot scan. As things stand, we do lots of unnecessary work.
7285
7286        // Give ourselves some initial paths; we'll come back for another
7287        // pass once we've determined ABI below.
7288        setNativeLibraryPaths(pkg);
7289
7290        // We would never need to extract libs for forward-locked and external packages,
7291        // since the container service will do it for us. We shouldn't attempt to
7292        // extract libs from system app when it was not updated.
7293        if (pkg.isForwardLocked() || isExternal(pkg) ||
7294            (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) {
7295            extractLibs = false;
7296        }
7297
7298        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7299        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7300
7301        NativeLibraryHelper.Handle handle = null;
7302        try {
7303            handle = NativeLibraryHelper.Handle.create(scanFile);
7304            // TODO(multiArch): This can be null for apps that didn't go through the
7305            // usual installation process. We can calculate it again, like we
7306            // do during install time.
7307            //
7308            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7309            // unnecessary.
7310            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7311
7312            // Null out the abis so that they can be recalculated.
7313            pkg.applicationInfo.primaryCpuAbi = null;
7314            pkg.applicationInfo.secondaryCpuAbi = null;
7315            if (isMultiArch(pkg.applicationInfo)) {
7316                // Warn if we've set an abiOverride for multi-lib packages..
7317                // By definition, we need to copy both 32 and 64 bit libraries for
7318                // such packages.
7319                if (pkg.cpuAbiOverride != null
7320                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7321                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7322                }
7323
7324                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7325                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7326                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7327                    if (extractLibs) {
7328                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7329                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7330                                useIsaSpecificSubdirs);
7331                    } else {
7332                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7333                    }
7334                }
7335
7336                maybeThrowExceptionForMultiArchCopy(
7337                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7338
7339                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7340                    if (extractLibs) {
7341                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7342                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7343                                useIsaSpecificSubdirs);
7344                    } else {
7345                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7346                    }
7347                }
7348
7349                maybeThrowExceptionForMultiArchCopy(
7350                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7351
7352                if (abi64 >= 0) {
7353                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7354                }
7355
7356                if (abi32 >= 0) {
7357                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7358                    if (abi64 >= 0) {
7359                        pkg.applicationInfo.secondaryCpuAbi = abi;
7360                    } else {
7361                        pkg.applicationInfo.primaryCpuAbi = abi;
7362                    }
7363                }
7364            } else {
7365                String[] abiList = (cpuAbiOverride != null) ?
7366                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7367
7368                // Enable gross and lame hacks for apps that are built with old
7369                // SDK tools. We must scan their APKs for renderscript bitcode and
7370                // not launch them if it's present. Don't bother checking on devices
7371                // that don't have 64 bit support.
7372                boolean needsRenderScriptOverride = false;
7373                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7374                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7375                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7376                    needsRenderScriptOverride = true;
7377                }
7378
7379                final int copyRet;
7380                if (extractLibs) {
7381                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7382                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7383                } else {
7384                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7385                }
7386
7387                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7388                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7389                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7390                }
7391
7392                if (copyRet >= 0) {
7393                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7394                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7395                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7396                } else if (needsRenderScriptOverride) {
7397                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7398                }
7399            }
7400        } catch (IOException ioe) {
7401            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7402        } finally {
7403            IoUtils.closeQuietly(handle);
7404        }
7405
7406        // Now that we've calculated the ABIs and determined if it's an internal app,
7407        // we will go ahead and populate the nativeLibraryPath.
7408        setNativeLibraryPaths(pkg);
7409    }
7410
7411    /**
7412     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7413     * i.e, so that all packages can be run inside a single process if required.
7414     *
7415     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7416     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7417     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7418     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7419     * updating a package that belongs to a shared user.
7420     *
7421     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7422     * adds unnecessary complexity.
7423     */
7424    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7425            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
7426        String requiredInstructionSet = null;
7427        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7428            requiredInstructionSet = VMRuntime.getInstructionSet(
7429                     scannedPackage.applicationInfo.primaryCpuAbi);
7430        }
7431
7432        PackageSetting requirer = null;
7433        for (PackageSetting ps : packagesForUser) {
7434            // If packagesForUser contains scannedPackage, we skip it. This will happen
7435            // when scannedPackage is an update of an existing package. Without this check,
7436            // we will never be able to change the ABI of any package belonging to a shared
7437            // user, even if it's compatible with other packages.
7438            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7439                if (ps.primaryCpuAbiString == null) {
7440                    continue;
7441                }
7442
7443                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7444                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7445                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7446                    // this but there's not much we can do.
7447                    String errorMessage = "Instruction set mismatch, "
7448                            + ((requirer == null) ? "[caller]" : requirer)
7449                            + " requires " + requiredInstructionSet + " whereas " + ps
7450                            + " requires " + instructionSet;
7451                    Slog.w(TAG, errorMessage);
7452                }
7453
7454                if (requiredInstructionSet == null) {
7455                    requiredInstructionSet = instructionSet;
7456                    requirer = ps;
7457                }
7458            }
7459        }
7460
7461        if (requiredInstructionSet != null) {
7462            String adjustedAbi;
7463            if (requirer != null) {
7464                // requirer != null implies that either scannedPackage was null or that scannedPackage
7465                // did not require an ABI, in which case we have to adjust scannedPackage to match
7466                // the ABI of the set (which is the same as requirer's ABI)
7467                adjustedAbi = requirer.primaryCpuAbiString;
7468                if (scannedPackage != null) {
7469                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7470                }
7471            } else {
7472                // requirer == null implies that we're updating all ABIs in the set to
7473                // match scannedPackage.
7474                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7475            }
7476
7477            for (PackageSetting ps : packagesForUser) {
7478                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7479                    if (ps.primaryCpuAbiString != null) {
7480                        continue;
7481                    }
7482
7483                    ps.primaryCpuAbiString = adjustedAbi;
7484                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7485                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7486                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7487
7488                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
7489                                null /* instruction sets */, forceDexOpt, deferDexOpt, true);
7490                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7491                            ps.primaryCpuAbiString = null;
7492                            ps.pkg.applicationInfo.primaryCpuAbi = null;
7493                            return;
7494                        } else {
7495                            mInstaller.rmdex(ps.codePathString,
7496                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
7497                        }
7498                    }
7499                }
7500            }
7501        }
7502    }
7503
7504    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7505        synchronized (mPackages) {
7506            mResolverReplaced = true;
7507            // Set up information for custom user intent resolution activity.
7508            mResolveActivity.applicationInfo = pkg.applicationInfo;
7509            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7510            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7511            mResolveActivity.processName = pkg.applicationInfo.packageName;
7512            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7513            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7514                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7515            mResolveActivity.theme = 0;
7516            mResolveActivity.exported = true;
7517            mResolveActivity.enabled = true;
7518            mResolveInfo.activityInfo = mResolveActivity;
7519            mResolveInfo.priority = 0;
7520            mResolveInfo.preferredOrder = 0;
7521            mResolveInfo.match = 0;
7522            mResolveComponentName = mCustomResolverComponentName;
7523            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7524                    mResolveComponentName);
7525        }
7526    }
7527
7528    private static String calculateBundledApkRoot(final String codePathString) {
7529        final File codePath = new File(codePathString);
7530        final File codeRoot;
7531        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7532            codeRoot = Environment.getRootDirectory();
7533        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7534            codeRoot = Environment.getOemDirectory();
7535        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7536            codeRoot = Environment.getVendorDirectory();
7537        } else {
7538            // Unrecognized code path; take its top real segment as the apk root:
7539            // e.g. /something/app/blah.apk => /something
7540            try {
7541                File f = codePath.getCanonicalFile();
7542                File parent = f.getParentFile();    // non-null because codePath is a file
7543                File tmp;
7544                while ((tmp = parent.getParentFile()) != null) {
7545                    f = parent;
7546                    parent = tmp;
7547                }
7548                codeRoot = f;
7549                Slog.w(TAG, "Unrecognized code path "
7550                        + codePath + " - using " + codeRoot);
7551            } catch (IOException e) {
7552                // Can't canonicalize the code path -- shenanigans?
7553                Slog.w(TAG, "Can't canonicalize code path " + codePath);
7554                return Environment.getRootDirectory().getPath();
7555            }
7556        }
7557        return codeRoot.getPath();
7558    }
7559
7560    /**
7561     * Derive and set the location of native libraries for the given package,
7562     * which varies depending on where and how the package was installed.
7563     */
7564    private void setNativeLibraryPaths(PackageParser.Package pkg) {
7565        final ApplicationInfo info = pkg.applicationInfo;
7566        final String codePath = pkg.codePath;
7567        final File codeFile = new File(codePath);
7568        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7569        final boolean asecApp = info.isForwardLocked() || isExternal(info);
7570
7571        info.nativeLibraryRootDir = null;
7572        info.nativeLibraryRootRequiresIsa = false;
7573        info.nativeLibraryDir = null;
7574        info.secondaryNativeLibraryDir = null;
7575
7576        if (isApkFile(codeFile)) {
7577            // Monolithic install
7578            if (bundledApp) {
7579                // If "/system/lib64/apkname" exists, assume that is the per-package
7580                // native library directory to use; otherwise use "/system/lib/apkname".
7581                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
7582                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
7583                        getPrimaryInstructionSet(info));
7584
7585                // This is a bundled system app so choose the path based on the ABI.
7586                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
7587                // is just the default path.
7588                final String apkName = deriveCodePathName(codePath);
7589                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
7590                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
7591                        apkName).getAbsolutePath();
7592
7593                if (info.secondaryCpuAbi != null) {
7594                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7595                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7596                            secondaryLibDir, apkName).getAbsolutePath();
7597                }
7598            } else if (asecApp) {
7599                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
7600                        .getAbsolutePath();
7601            } else {
7602                final String apkName = deriveCodePathName(codePath);
7603                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
7604                        .getAbsolutePath();
7605            }
7606
7607            info.nativeLibraryRootRequiresIsa = false;
7608            info.nativeLibraryDir = info.nativeLibraryRootDir;
7609        } else {
7610            // Cluster install
7611            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7612            info.nativeLibraryRootRequiresIsa = true;
7613
7614            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7615                    getPrimaryInstructionSet(info)).getAbsolutePath();
7616
7617            if (info.secondaryCpuAbi != null) {
7618                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7619                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7620            }
7621        }
7622    }
7623
7624    /**
7625     * Calculate the abis and roots for a bundled app. These can uniquely
7626     * be determined from the contents of the system partition, i.e whether
7627     * it contains 64 or 32 bit shared libraries etc. We do not validate any
7628     * of this information, and instead assume that the system was built
7629     * sensibly.
7630     */
7631    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
7632                                           PackageSetting pkgSetting) {
7633        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
7634
7635        // If "/system/lib64/apkname" exists, assume that is the per-package
7636        // native library directory to use; otherwise use "/system/lib/apkname".
7637        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
7638        setBundledAppAbi(pkg, apkRoot, apkName);
7639        // pkgSetting might be null during rescan following uninstall of updates
7640        // to a bundled app, so accommodate that possibility.  The settings in
7641        // that case will be established later from the parsed package.
7642        //
7643        // If the settings aren't null, sync them up with what we've just derived.
7644        // note that apkRoot isn't stored in the package settings.
7645        if (pkgSetting != null) {
7646            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7647            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7648        }
7649    }
7650
7651    /**
7652     * Deduces the ABI of a bundled app and sets the relevant fields on the
7653     * parsed pkg object.
7654     *
7655     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
7656     *        under which system libraries are installed.
7657     * @param apkName the name of the installed package.
7658     */
7659    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7660        final File codeFile = new File(pkg.codePath);
7661
7662        final boolean has64BitLibs;
7663        final boolean has32BitLibs;
7664        if (isApkFile(codeFile)) {
7665            // Monolithic install
7666            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7667            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7668        } else {
7669            // Cluster install
7670            final File rootDir = new File(codeFile, LIB_DIR_NAME);
7671            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7672                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7673                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7674                has64BitLibs = (new File(rootDir, isa)).exists();
7675            } else {
7676                has64BitLibs = false;
7677            }
7678            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7679                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7680                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7681                has32BitLibs = (new File(rootDir, isa)).exists();
7682            } else {
7683                has32BitLibs = false;
7684            }
7685        }
7686
7687        if (has64BitLibs && !has32BitLibs) {
7688            // The package has 64 bit libs, but not 32 bit libs. Its primary
7689            // ABI should be 64 bit. We can safely assume here that the bundled
7690            // native libraries correspond to the most preferred ABI in the list.
7691
7692            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7693            pkg.applicationInfo.secondaryCpuAbi = null;
7694        } else if (has32BitLibs && !has64BitLibs) {
7695            // The package has 32 bit libs but not 64 bit libs. Its primary
7696            // ABI should be 32 bit.
7697
7698            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7699            pkg.applicationInfo.secondaryCpuAbi = null;
7700        } else if (has32BitLibs && has64BitLibs) {
7701            // The application has both 64 and 32 bit bundled libraries. We check
7702            // here that the app declares multiArch support, and warn if it doesn't.
7703            //
7704            // We will be lenient here and record both ABIs. The primary will be the
7705            // ABI that's higher on the list, i.e, a device that's configured to prefer
7706            // 64 bit apps will see a 64 bit primary ABI,
7707
7708            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
7709                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
7710            }
7711
7712            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
7713                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7714                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7715            } else {
7716                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7717                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7718            }
7719        } else {
7720            pkg.applicationInfo.primaryCpuAbi = null;
7721            pkg.applicationInfo.secondaryCpuAbi = null;
7722        }
7723    }
7724
7725    private void killApplication(String pkgName, int appId, String reason) {
7726        // Request the ActivityManager to kill the process(only for existing packages)
7727        // so that we do not end up in a confused state while the user is still using the older
7728        // version of the application while the new one gets installed.
7729        IActivityManager am = ActivityManagerNative.getDefault();
7730        if (am != null) {
7731            try {
7732                am.killApplicationWithAppId(pkgName, appId, reason);
7733            } catch (RemoteException e) {
7734            }
7735        }
7736    }
7737
7738    void removePackageLI(PackageSetting ps, boolean chatty) {
7739        if (DEBUG_INSTALL) {
7740            if (chatty)
7741                Log.d(TAG, "Removing package " + ps.name);
7742        }
7743
7744        // writer
7745        synchronized (mPackages) {
7746            mPackages.remove(ps.name);
7747            final PackageParser.Package pkg = ps.pkg;
7748            if (pkg != null) {
7749                cleanPackageDataStructuresLILPw(pkg, chatty);
7750            }
7751        }
7752    }
7753
7754    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
7755        if (DEBUG_INSTALL) {
7756            if (chatty)
7757                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
7758        }
7759
7760        // writer
7761        synchronized (mPackages) {
7762            mPackages.remove(pkg.applicationInfo.packageName);
7763            cleanPackageDataStructuresLILPw(pkg, chatty);
7764        }
7765    }
7766
7767    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
7768        int N = pkg.providers.size();
7769        StringBuilder r = null;
7770        int i;
7771        for (i=0; i<N; i++) {
7772            PackageParser.Provider p = pkg.providers.get(i);
7773            mProviders.removeProvider(p);
7774            if (p.info.authority == null) {
7775
7776                /* There was another ContentProvider with this authority when
7777                 * this app was installed so this authority is null,
7778                 * Ignore it as we don't have to unregister the provider.
7779                 */
7780                continue;
7781            }
7782            String names[] = p.info.authority.split(";");
7783            for (int j = 0; j < names.length; j++) {
7784                if (mProvidersByAuthority.get(names[j]) == p) {
7785                    mProvidersByAuthority.remove(names[j]);
7786                    if (DEBUG_REMOVE) {
7787                        if (chatty)
7788                            Log.d(TAG, "Unregistered content provider: " + names[j]
7789                                    + ", className = " + p.info.name + ", isSyncable = "
7790                                    + p.info.isSyncable);
7791                    }
7792                }
7793            }
7794            if (DEBUG_REMOVE && chatty) {
7795                if (r == null) {
7796                    r = new StringBuilder(256);
7797                } else {
7798                    r.append(' ');
7799                }
7800                r.append(p.info.name);
7801            }
7802        }
7803        if (r != null) {
7804            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
7805        }
7806
7807        N = pkg.services.size();
7808        r = null;
7809        for (i=0; i<N; i++) {
7810            PackageParser.Service s = pkg.services.get(i);
7811            mServices.removeService(s);
7812            if (chatty) {
7813                if (r == null) {
7814                    r = new StringBuilder(256);
7815                } else {
7816                    r.append(' ');
7817                }
7818                r.append(s.info.name);
7819            }
7820        }
7821        if (r != null) {
7822            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
7823        }
7824
7825        N = pkg.receivers.size();
7826        r = null;
7827        for (i=0; i<N; i++) {
7828            PackageParser.Activity a = pkg.receivers.get(i);
7829            mReceivers.removeActivity(a, "receiver");
7830            if (DEBUG_REMOVE && chatty) {
7831                if (r == null) {
7832                    r = new StringBuilder(256);
7833                } else {
7834                    r.append(' ');
7835                }
7836                r.append(a.info.name);
7837            }
7838        }
7839        if (r != null) {
7840            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
7841        }
7842
7843        N = pkg.activities.size();
7844        r = null;
7845        for (i=0; i<N; i++) {
7846            PackageParser.Activity a = pkg.activities.get(i);
7847            mActivities.removeActivity(a, "activity");
7848            if (DEBUG_REMOVE && chatty) {
7849                if (r == null) {
7850                    r = new StringBuilder(256);
7851                } else {
7852                    r.append(' ');
7853                }
7854                r.append(a.info.name);
7855            }
7856        }
7857        if (r != null) {
7858            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
7859        }
7860
7861        N = pkg.permissions.size();
7862        r = null;
7863        for (i=0; i<N; i++) {
7864            PackageParser.Permission p = pkg.permissions.get(i);
7865            BasePermission bp = mSettings.mPermissions.get(p.info.name);
7866            if (bp == null) {
7867                bp = mSettings.mPermissionTrees.get(p.info.name);
7868            }
7869            if (bp != null && bp.perm == p) {
7870                bp.perm = null;
7871                if (DEBUG_REMOVE && chatty) {
7872                    if (r == null) {
7873                        r = new StringBuilder(256);
7874                    } else {
7875                        r.append(' ');
7876                    }
7877                    r.append(p.info.name);
7878                }
7879            }
7880            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7881                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
7882                if (appOpPerms != null) {
7883                    appOpPerms.remove(pkg.packageName);
7884                }
7885            }
7886        }
7887        if (r != null) {
7888            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
7889        }
7890
7891        N = pkg.requestedPermissions.size();
7892        r = null;
7893        for (i=0; i<N; i++) {
7894            String perm = pkg.requestedPermissions.get(i);
7895            BasePermission bp = mSettings.mPermissions.get(perm);
7896            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7897                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
7898                if (appOpPerms != null) {
7899                    appOpPerms.remove(pkg.packageName);
7900                    if (appOpPerms.isEmpty()) {
7901                        mAppOpPermissionPackages.remove(perm);
7902                    }
7903                }
7904            }
7905        }
7906        if (r != null) {
7907            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
7908        }
7909
7910        N = pkg.instrumentation.size();
7911        r = null;
7912        for (i=0; i<N; i++) {
7913            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7914            mInstrumentation.remove(a.getComponentName());
7915            if (DEBUG_REMOVE && chatty) {
7916                if (r == null) {
7917                    r = new StringBuilder(256);
7918                } else {
7919                    r.append(' ');
7920                }
7921                r.append(a.info.name);
7922            }
7923        }
7924        if (r != null) {
7925            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
7926        }
7927
7928        r = null;
7929        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7930            // Only system apps can hold shared libraries.
7931            if (pkg.libraryNames != null) {
7932                for (i=0; i<pkg.libraryNames.size(); i++) {
7933                    String name = pkg.libraryNames.get(i);
7934                    SharedLibraryEntry cur = mSharedLibraries.get(name);
7935                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
7936                        mSharedLibraries.remove(name);
7937                        if (DEBUG_REMOVE && chatty) {
7938                            if (r == null) {
7939                                r = new StringBuilder(256);
7940                            } else {
7941                                r.append(' ');
7942                            }
7943                            r.append(name);
7944                        }
7945                    }
7946                }
7947            }
7948        }
7949        if (r != null) {
7950            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
7951        }
7952    }
7953
7954    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
7955        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
7956            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
7957                return true;
7958            }
7959        }
7960        return false;
7961    }
7962
7963    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
7964    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
7965    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
7966
7967    private void updatePermissionsLPw(String changingPkg,
7968            PackageParser.Package pkgInfo, int flags) {
7969        // Make sure there are no dangling permission trees.
7970        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
7971        while (it.hasNext()) {
7972            final BasePermission bp = it.next();
7973            if (bp.packageSetting == null) {
7974                // We may not yet have parsed the package, so just see if
7975                // we still know about its settings.
7976                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
7977            }
7978            if (bp.packageSetting == null) {
7979                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
7980                        + " from package " + bp.sourcePackage);
7981                it.remove();
7982            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
7983                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
7984                    Slog.i(TAG, "Removing old permission tree: " + bp.name
7985                            + " from package " + bp.sourcePackage);
7986                    flags |= UPDATE_PERMISSIONS_ALL;
7987                    it.remove();
7988                }
7989            }
7990        }
7991
7992        // Make sure all dynamic permissions have been assigned to a package,
7993        // and make sure there are no dangling permissions.
7994        it = mSettings.mPermissions.values().iterator();
7995        while (it.hasNext()) {
7996            final BasePermission bp = it.next();
7997            if (bp.type == BasePermission.TYPE_DYNAMIC) {
7998                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
7999                        + bp.name + " pkg=" + bp.sourcePackage
8000                        + " info=" + bp.pendingInfo);
8001                if (bp.packageSetting == null && bp.pendingInfo != null) {
8002                    final BasePermission tree = findPermissionTreeLP(bp.name);
8003                    if (tree != null && tree.perm != null) {
8004                        bp.packageSetting = tree.packageSetting;
8005                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8006                                new PermissionInfo(bp.pendingInfo));
8007                        bp.perm.info.packageName = tree.perm.info.packageName;
8008                        bp.perm.info.name = bp.name;
8009                        bp.uid = tree.uid;
8010                    }
8011                }
8012            }
8013            if (bp.packageSetting == null) {
8014                // We may not yet have parsed the package, so just see if
8015                // we still know about its settings.
8016                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8017            }
8018            if (bp.packageSetting == null) {
8019                Slog.w(TAG, "Removing dangling permission: " + bp.name
8020                        + " from package " + bp.sourcePackage);
8021                it.remove();
8022            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8023                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8024                    Slog.i(TAG, "Removing old permission: " + bp.name
8025                            + " from package " + bp.sourcePackage);
8026                    flags |= UPDATE_PERMISSIONS_ALL;
8027                    it.remove();
8028                }
8029            }
8030        }
8031
8032        // Now update the permissions for all packages, in particular
8033        // replace the granted permissions of the system packages.
8034        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8035            for (PackageParser.Package pkg : mPackages.values()) {
8036                if (pkg != pkgInfo) {
8037                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
8038                            changingPkg);
8039                }
8040            }
8041        }
8042
8043        if (pkgInfo != null) {
8044            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
8045        }
8046    }
8047
8048    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8049            String packageOfInterest) {
8050        // IMPORTANT: There are two types of permissions: install and runtime.
8051        // Install time permissions are granted when the app is installed to
8052        // all device users and users added in the future. Runtime permissions
8053        // are granted at runtime explicitly to specific users. Normal and signature
8054        // protected permissions are install time permissions. Dangerous permissions
8055        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8056        // otherwise they are runtime permissions. This function does not manage
8057        // runtime permissions except for the case an app targeting Lollipop MR1
8058        // being upgraded to target a newer SDK, in which case dangerous permissions
8059        // are transformed from install time to runtime ones.
8060
8061        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8062        if (ps == null) {
8063            return;
8064        }
8065
8066        PermissionsState permissionsState = ps.getPermissionsState();
8067        PermissionsState origPermissions = permissionsState;
8068
8069        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8070
8071        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8072
8073        boolean changedInstallPermission = false;
8074
8075        if (replace) {
8076            ps.installPermissionsFixed = false;
8077            if (!ps.isSharedUser()) {
8078                origPermissions = new PermissionsState(permissionsState);
8079                permissionsState.reset();
8080            }
8081        }
8082
8083        permissionsState.setGlobalGids(mGlobalGids);
8084
8085        final int N = pkg.requestedPermissions.size();
8086        for (int i=0; i<N; i++) {
8087            final String name = pkg.requestedPermissions.get(i);
8088            final BasePermission bp = mSettings.mPermissions.get(name);
8089
8090            if (DEBUG_INSTALL) {
8091                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8092            }
8093
8094            if (bp == null || bp.packageSetting == null) {
8095                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8096                    Slog.w(TAG, "Unknown permission " + name
8097                            + " in package " + pkg.packageName);
8098                }
8099                continue;
8100            }
8101
8102            final String perm = bp.name;
8103            boolean allowedSig = false;
8104            int grant = GRANT_DENIED;
8105
8106            // Keep track of app op permissions.
8107            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8108                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8109                if (pkgs == null) {
8110                    pkgs = new ArraySet<>();
8111                    mAppOpPermissionPackages.put(bp.name, pkgs);
8112                }
8113                pkgs.add(pkg.packageName);
8114            }
8115
8116            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8117            switch (level) {
8118                case PermissionInfo.PROTECTION_NORMAL: {
8119                    // For all apps normal permissions are install time ones.
8120                    grant = GRANT_INSTALL;
8121                } break;
8122
8123                case PermissionInfo.PROTECTION_DANGEROUS: {
8124                    if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
8125                        // For legacy apps dangerous permissions are install time ones.
8126                        grant = GRANT_INSTALL_LEGACY;
8127                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8128                        // For legacy apps that became modern, install becomes runtime.
8129                        grant = GRANT_UPGRADE;
8130                    } else {
8131                        // For modern apps keep runtime permissions unchanged.
8132                        grant = GRANT_RUNTIME;
8133                    }
8134                } break;
8135
8136                case PermissionInfo.PROTECTION_SIGNATURE: {
8137                    // For all apps signature permissions are install time ones.
8138                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8139                    if (allowedSig) {
8140                        grant = GRANT_INSTALL;
8141                    }
8142                } break;
8143            }
8144
8145            if (DEBUG_INSTALL) {
8146                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8147            }
8148
8149            if (grant != GRANT_DENIED) {
8150                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8151                    // If this is an existing, non-system package, then
8152                    // we can't add any new permissions to it.
8153                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8154                        // Except...  if this is a permission that was added
8155                        // to the platform (note: need to only do this when
8156                        // updating the platform).
8157                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8158                            grant = GRANT_DENIED;
8159                        }
8160                    }
8161                }
8162
8163                switch (grant) {
8164                    case GRANT_INSTALL: {
8165                        // Revoke this as runtime permission to handle the case of
8166                        // a runtime permission being downgraded to an install one.
8167                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8168                            if (origPermissions.getRuntimePermissionState(
8169                                    bp.name, userId) != null) {
8170                                // Revoke the runtime permission and clear the flags.
8171                                origPermissions.revokeRuntimePermission(bp, userId);
8172                                origPermissions.updatePermissionFlags(bp, userId,
8173                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8174                                // If we revoked a permission permission, we have to write.
8175                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8176                                        changedRuntimePermissionUserIds, userId);
8177                            }
8178                        }
8179                        // Grant an install permission.
8180                        if (permissionsState.grantInstallPermission(bp) !=
8181                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8182                            changedInstallPermission = true;
8183                        }
8184                    } break;
8185
8186                    case GRANT_INSTALL_LEGACY: {
8187                        // Grant an install permission.
8188                        if (permissionsState.grantInstallPermission(bp) !=
8189                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8190                            changedInstallPermission = true;
8191                        }
8192                    } break;
8193
8194                    case GRANT_RUNTIME: {
8195                        // Grant previously granted runtime permissions.
8196                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8197                            PermissionState permissionState = origPermissions
8198                                    .getRuntimePermissionState(bp.name, userId);
8199                            final int flags = permissionState != null
8200                                    ? permissionState.getFlags() : 0;
8201                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8202                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8203                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8204                                    // If we cannot put the permission as it was, we have to write.
8205                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8206                                            changedRuntimePermissionUserIds, userId);
8207                                }
8208                            }
8209                            // Propagate the permission flags.
8210                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8211                        }
8212                    } break;
8213
8214                    case GRANT_UPGRADE: {
8215                        // Grant runtime permissions for a previously held install permission.
8216                        PermissionState permissionState = origPermissions
8217                                .getInstallPermissionState(bp.name);
8218                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8219
8220                        if (origPermissions.revokeInstallPermission(bp)
8221                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8222                            // We will be transferring the permission flags, so clear them.
8223                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8224                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8225                            changedInstallPermission = true;
8226                        }
8227
8228                        // If the permission is not to be promoted to runtime we ignore it and
8229                        // also its other flags as they are not applicable to install permissions.
8230                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8231                            for (int userId : currentUserIds) {
8232                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8233                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8234                                    // Transfer the permission flags.
8235                                    permissionsState.updatePermissionFlags(bp, userId,
8236                                            flags, flags);
8237                                    // If we granted the permission, we have to write.
8238                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8239                                            changedRuntimePermissionUserIds, userId);
8240                                }
8241                            }
8242                        }
8243                    } break;
8244
8245                    default: {
8246                        if (packageOfInterest == null
8247                                || packageOfInterest.equals(pkg.packageName)) {
8248                            Slog.w(TAG, "Not granting permission " + perm
8249                                    + " to package " + pkg.packageName
8250                                    + " because it was previously installed without");
8251                        }
8252                    } break;
8253                }
8254            } else {
8255                if (permissionsState.revokeInstallPermission(bp) !=
8256                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8257                    // Also drop the permission flags.
8258                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8259                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8260                    changedInstallPermission = true;
8261                    Slog.i(TAG, "Un-granting permission " + perm
8262                            + " from package " + pkg.packageName
8263                            + " (protectionLevel=" + bp.protectionLevel
8264                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8265                            + ")");
8266                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8267                    // Don't print warning for app op permissions, since it is fine for them
8268                    // not to be granted, there is a UI for the user to decide.
8269                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8270                        Slog.w(TAG, "Not granting permission " + perm
8271                                + " to package " + pkg.packageName
8272                                + " (protectionLevel=" + bp.protectionLevel
8273                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8274                                + ")");
8275                    }
8276                }
8277            }
8278        }
8279
8280        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8281                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8282            // This is the first that we have heard about this package, so the
8283            // permissions we have now selected are fixed until explicitly
8284            // changed.
8285            ps.installPermissionsFixed = true;
8286        }
8287
8288        // Persist the runtime permissions state for users with changes.
8289        for (int userId : changedRuntimePermissionUserIds) {
8290            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
8291        }
8292    }
8293
8294    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8295        boolean allowed = false;
8296        final int NP = PackageParser.NEW_PERMISSIONS.length;
8297        for (int ip=0; ip<NP; ip++) {
8298            final PackageParser.NewPermissionInfo npi
8299                    = PackageParser.NEW_PERMISSIONS[ip];
8300            if (npi.name.equals(perm)
8301                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8302                allowed = true;
8303                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8304                        + pkg.packageName);
8305                break;
8306            }
8307        }
8308        return allowed;
8309    }
8310
8311    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8312            BasePermission bp, PermissionsState origPermissions) {
8313        boolean allowed;
8314        allowed = (compareSignatures(
8315                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8316                        == PackageManager.SIGNATURE_MATCH)
8317                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8318                        == PackageManager.SIGNATURE_MATCH);
8319        if (!allowed && (bp.protectionLevel
8320                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
8321            if (isSystemApp(pkg)) {
8322                // For updated system applications, a system permission
8323                // is granted only if it had been defined by the original application.
8324                if (pkg.isUpdatedSystemApp()) {
8325                    final PackageSetting sysPs = mSettings
8326                            .getDisabledSystemPkgLPr(pkg.packageName);
8327                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8328                        // If the original was granted this permission, we take
8329                        // that grant decision as read and propagate it to the
8330                        // update.
8331                        if (sysPs.isPrivileged()) {
8332                            allowed = true;
8333                        }
8334                    } else {
8335                        // The system apk may have been updated with an older
8336                        // version of the one on the data partition, but which
8337                        // granted a new system permission that it didn't have
8338                        // before.  In this case we do want to allow the app to
8339                        // now get the new permission if the ancestral apk is
8340                        // privileged to get it.
8341                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
8342                            for (int j=0;
8343                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
8344                                if (perm.equals(
8345                                        sysPs.pkg.requestedPermissions.get(j))) {
8346                                    allowed = true;
8347                                    break;
8348                                }
8349                            }
8350                        }
8351                    }
8352                } else {
8353                    allowed = isPrivilegedApp(pkg);
8354                }
8355            }
8356        }
8357        if (!allowed && (bp.protectionLevel
8358                & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
8359                && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.MNC) {
8360            // If this was a previously normal/dangerous permission that got moved
8361            // to a system permission as part of the runtime permission redesign, then
8362            // we still want to blindly grant it to old apps.
8363            allowed = true;
8364        }
8365        if (!allowed && (bp.protectionLevel
8366                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8367            // For development permissions, a development permission
8368            // is granted only if it was already granted.
8369            allowed = origPermissions.hasInstallPermission(perm);
8370        }
8371        return allowed;
8372    }
8373
8374    final class ActivityIntentResolver
8375            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8376        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8377                boolean defaultOnly, int userId) {
8378            if (!sUserManager.exists(userId)) return null;
8379            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8380            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8381        }
8382
8383        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8384                int userId) {
8385            if (!sUserManager.exists(userId)) return null;
8386            mFlags = flags;
8387            return super.queryIntent(intent, resolvedType,
8388                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8389        }
8390
8391        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8392                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8393            if (!sUserManager.exists(userId)) return null;
8394            if (packageActivities == null) {
8395                return null;
8396            }
8397            mFlags = flags;
8398            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8399            final int N = packageActivities.size();
8400            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8401                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8402
8403            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8404            for (int i = 0; i < N; ++i) {
8405                intentFilters = packageActivities.get(i).intents;
8406                if (intentFilters != null && intentFilters.size() > 0) {
8407                    PackageParser.ActivityIntentInfo[] array =
8408                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
8409                    intentFilters.toArray(array);
8410                    listCut.add(array);
8411                }
8412            }
8413            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8414        }
8415
8416        public final void addActivity(PackageParser.Activity a, String type) {
8417            final boolean systemApp = a.info.applicationInfo.isSystemApp();
8418            mActivities.put(a.getComponentName(), a);
8419            if (DEBUG_SHOW_INFO)
8420                Log.v(
8421                TAG, "  " + type + " " +
8422                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8423            if (DEBUG_SHOW_INFO)
8424                Log.v(TAG, "    Class=" + a.info.name);
8425            final int NI = a.intents.size();
8426            for (int j=0; j<NI; j++) {
8427                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8428                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
8429                    intent.setPriority(0);
8430                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
8431                            + a.className + " with priority > 0, forcing to 0");
8432                }
8433                if (DEBUG_SHOW_INFO) {
8434                    Log.v(TAG, "    IntentFilter:");
8435                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8436                }
8437                if (!intent.debugCheck()) {
8438                    Log.w(TAG, "==> For Activity " + a.info.name);
8439                }
8440                addFilter(intent);
8441            }
8442        }
8443
8444        public final void removeActivity(PackageParser.Activity a, String type) {
8445            mActivities.remove(a.getComponentName());
8446            if (DEBUG_SHOW_INFO) {
8447                Log.v(TAG, "  " + type + " "
8448                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
8449                                : a.info.name) + ":");
8450                Log.v(TAG, "    Class=" + a.info.name);
8451            }
8452            final int NI = a.intents.size();
8453            for (int j=0; j<NI; j++) {
8454                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8455                if (DEBUG_SHOW_INFO) {
8456                    Log.v(TAG, "    IntentFilter:");
8457                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8458                }
8459                removeFilter(intent);
8460            }
8461        }
8462
8463        @Override
8464        protected boolean allowFilterResult(
8465                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
8466            ActivityInfo filterAi = filter.activity.info;
8467            for (int i=dest.size()-1; i>=0; i--) {
8468                ActivityInfo destAi = dest.get(i).activityInfo;
8469                if (destAi.name == filterAi.name
8470                        && destAi.packageName == filterAi.packageName) {
8471                    return false;
8472                }
8473            }
8474            return true;
8475        }
8476
8477        @Override
8478        protected ActivityIntentInfo[] newArray(int size) {
8479            return new ActivityIntentInfo[size];
8480        }
8481
8482        @Override
8483        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
8484            if (!sUserManager.exists(userId)) return true;
8485            PackageParser.Package p = filter.activity.owner;
8486            if (p != null) {
8487                PackageSetting ps = (PackageSetting)p.mExtras;
8488                if (ps != null) {
8489                    // System apps are never considered stopped for purposes of
8490                    // filtering, because there may be no way for the user to
8491                    // actually re-launch them.
8492                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
8493                            && ps.getStopped(userId);
8494                }
8495            }
8496            return false;
8497        }
8498
8499        @Override
8500        protected boolean isPackageForFilter(String packageName,
8501                PackageParser.ActivityIntentInfo info) {
8502            return packageName.equals(info.activity.owner.packageName);
8503        }
8504
8505        @Override
8506        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
8507                int match, int userId) {
8508            if (!sUserManager.exists(userId)) return null;
8509            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
8510                return null;
8511            }
8512            final PackageParser.Activity activity = info.activity;
8513            if (mSafeMode && (activity.info.applicationInfo.flags
8514                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8515                return null;
8516            }
8517            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
8518            if (ps == null) {
8519                return null;
8520            }
8521            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
8522                    ps.readUserState(userId), userId);
8523            if (ai == null) {
8524                return null;
8525            }
8526            final ResolveInfo res = new ResolveInfo();
8527            res.activityInfo = ai;
8528            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8529                res.filter = info;
8530            }
8531            if (info != null) {
8532                res.handleAllWebDataURI = info.handleAllWebDataURI();
8533            }
8534            res.priority = info.getPriority();
8535            res.preferredOrder = activity.owner.mPreferredOrder;
8536            //System.out.println("Result: " + res.activityInfo.className +
8537            //                   " = " + res.priority);
8538            res.match = match;
8539            res.isDefault = info.hasDefault;
8540            res.labelRes = info.labelRes;
8541            res.nonLocalizedLabel = info.nonLocalizedLabel;
8542            if (userNeedsBadging(userId)) {
8543                res.noResourceId = true;
8544            } else {
8545                res.icon = info.icon;
8546            }
8547            res.iconResourceId = info.icon;
8548            res.system = res.activityInfo.applicationInfo.isSystemApp();
8549            return res;
8550        }
8551
8552        @Override
8553        protected void sortResults(List<ResolveInfo> results) {
8554            Collections.sort(results, mResolvePrioritySorter);
8555        }
8556
8557        @Override
8558        protected void dumpFilter(PrintWriter out, String prefix,
8559                PackageParser.ActivityIntentInfo filter) {
8560            out.print(prefix); out.print(
8561                    Integer.toHexString(System.identityHashCode(filter.activity)));
8562                    out.print(' ');
8563                    filter.activity.printComponentShortName(out);
8564                    out.print(" filter ");
8565                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8566        }
8567
8568        @Override
8569        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
8570            return filter.activity;
8571        }
8572
8573        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8574            PackageParser.Activity activity = (PackageParser.Activity)label;
8575            out.print(prefix); out.print(
8576                    Integer.toHexString(System.identityHashCode(activity)));
8577                    out.print(' ');
8578                    activity.printComponentShortName(out);
8579            if (count > 1) {
8580                out.print(" ("); out.print(count); out.print(" filters)");
8581            }
8582            out.println();
8583        }
8584
8585//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8586//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8587//            final List<ResolveInfo> retList = Lists.newArrayList();
8588//            while (i.hasNext()) {
8589//                final ResolveInfo resolveInfo = i.next();
8590//                if (isEnabledLP(resolveInfo.activityInfo)) {
8591//                    retList.add(resolveInfo);
8592//                }
8593//            }
8594//            return retList;
8595//        }
8596
8597        // Keys are String (activity class name), values are Activity.
8598        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
8599                = new ArrayMap<ComponentName, PackageParser.Activity>();
8600        private int mFlags;
8601    }
8602
8603    private final class ServiceIntentResolver
8604            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
8605        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8606                boolean defaultOnly, int userId) {
8607            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8608            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8609        }
8610
8611        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8612                int userId) {
8613            if (!sUserManager.exists(userId)) return null;
8614            mFlags = flags;
8615            return super.queryIntent(intent, resolvedType,
8616                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8617        }
8618
8619        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8620                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
8621            if (!sUserManager.exists(userId)) return null;
8622            if (packageServices == null) {
8623                return null;
8624            }
8625            mFlags = flags;
8626            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8627            final int N = packageServices.size();
8628            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
8629                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
8630
8631            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
8632            for (int i = 0; i < N; ++i) {
8633                intentFilters = packageServices.get(i).intents;
8634                if (intentFilters != null && intentFilters.size() > 0) {
8635                    PackageParser.ServiceIntentInfo[] array =
8636                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
8637                    intentFilters.toArray(array);
8638                    listCut.add(array);
8639                }
8640            }
8641            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8642        }
8643
8644        public final void addService(PackageParser.Service s) {
8645            mServices.put(s.getComponentName(), s);
8646            if (DEBUG_SHOW_INFO) {
8647                Log.v(TAG, "  "
8648                        + (s.info.nonLocalizedLabel != null
8649                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8650                Log.v(TAG, "    Class=" + s.info.name);
8651            }
8652            final int NI = s.intents.size();
8653            int j;
8654            for (j=0; j<NI; j++) {
8655                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8656                if (DEBUG_SHOW_INFO) {
8657                    Log.v(TAG, "    IntentFilter:");
8658                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8659                }
8660                if (!intent.debugCheck()) {
8661                    Log.w(TAG, "==> For Service " + s.info.name);
8662                }
8663                addFilter(intent);
8664            }
8665        }
8666
8667        public final void removeService(PackageParser.Service s) {
8668            mServices.remove(s.getComponentName());
8669            if (DEBUG_SHOW_INFO) {
8670                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
8671                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8672                Log.v(TAG, "    Class=" + s.info.name);
8673            }
8674            final int NI = s.intents.size();
8675            int j;
8676            for (j=0; j<NI; j++) {
8677                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8678                if (DEBUG_SHOW_INFO) {
8679                    Log.v(TAG, "    IntentFilter:");
8680                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8681                }
8682                removeFilter(intent);
8683            }
8684        }
8685
8686        @Override
8687        protected boolean allowFilterResult(
8688                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
8689            ServiceInfo filterSi = filter.service.info;
8690            for (int i=dest.size()-1; i>=0; i--) {
8691                ServiceInfo destAi = dest.get(i).serviceInfo;
8692                if (destAi.name == filterSi.name
8693                        && destAi.packageName == filterSi.packageName) {
8694                    return false;
8695                }
8696            }
8697            return true;
8698        }
8699
8700        @Override
8701        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
8702            return new PackageParser.ServiceIntentInfo[size];
8703        }
8704
8705        @Override
8706        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
8707            if (!sUserManager.exists(userId)) return true;
8708            PackageParser.Package p = filter.service.owner;
8709            if (p != null) {
8710                PackageSetting ps = (PackageSetting)p.mExtras;
8711                if (ps != null) {
8712                    // System apps are never considered stopped for purposes of
8713                    // filtering, because there may be no way for the user to
8714                    // actually re-launch them.
8715                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8716                            && ps.getStopped(userId);
8717                }
8718            }
8719            return false;
8720        }
8721
8722        @Override
8723        protected boolean isPackageForFilter(String packageName,
8724                PackageParser.ServiceIntentInfo info) {
8725            return packageName.equals(info.service.owner.packageName);
8726        }
8727
8728        @Override
8729        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
8730                int match, int userId) {
8731            if (!sUserManager.exists(userId)) return null;
8732            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
8733            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
8734                return null;
8735            }
8736            final PackageParser.Service service = info.service;
8737            if (mSafeMode && (service.info.applicationInfo.flags
8738                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8739                return null;
8740            }
8741            PackageSetting ps = (PackageSetting) service.owner.mExtras;
8742            if (ps == null) {
8743                return null;
8744            }
8745            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
8746                    ps.readUserState(userId), userId);
8747            if (si == null) {
8748                return null;
8749            }
8750            final ResolveInfo res = new ResolveInfo();
8751            res.serviceInfo = si;
8752            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8753                res.filter = filter;
8754            }
8755            res.priority = info.getPriority();
8756            res.preferredOrder = service.owner.mPreferredOrder;
8757            res.match = match;
8758            res.isDefault = info.hasDefault;
8759            res.labelRes = info.labelRes;
8760            res.nonLocalizedLabel = info.nonLocalizedLabel;
8761            res.icon = info.icon;
8762            res.system = res.serviceInfo.applicationInfo.isSystemApp();
8763            return res;
8764        }
8765
8766        @Override
8767        protected void sortResults(List<ResolveInfo> results) {
8768            Collections.sort(results, mResolvePrioritySorter);
8769        }
8770
8771        @Override
8772        protected void dumpFilter(PrintWriter out, String prefix,
8773                PackageParser.ServiceIntentInfo filter) {
8774            out.print(prefix); out.print(
8775                    Integer.toHexString(System.identityHashCode(filter.service)));
8776                    out.print(' ');
8777                    filter.service.printComponentShortName(out);
8778                    out.print(" filter ");
8779                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8780        }
8781
8782        @Override
8783        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
8784            return filter.service;
8785        }
8786
8787        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8788            PackageParser.Service service = (PackageParser.Service)label;
8789            out.print(prefix); out.print(
8790                    Integer.toHexString(System.identityHashCode(service)));
8791                    out.print(' ');
8792                    service.printComponentShortName(out);
8793            if (count > 1) {
8794                out.print(" ("); out.print(count); out.print(" filters)");
8795            }
8796            out.println();
8797        }
8798
8799//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8800//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8801//            final List<ResolveInfo> retList = Lists.newArrayList();
8802//            while (i.hasNext()) {
8803//                final ResolveInfo resolveInfo = (ResolveInfo) i;
8804//                if (isEnabledLP(resolveInfo.serviceInfo)) {
8805//                    retList.add(resolveInfo);
8806//                }
8807//            }
8808//            return retList;
8809//        }
8810
8811        // Keys are String (activity class name), values are Activity.
8812        private final ArrayMap<ComponentName, PackageParser.Service> mServices
8813                = new ArrayMap<ComponentName, PackageParser.Service>();
8814        private int mFlags;
8815    };
8816
8817    private final class ProviderIntentResolver
8818            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
8819        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8820                boolean defaultOnly, int userId) {
8821            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8822            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8823        }
8824
8825        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8826                int userId) {
8827            if (!sUserManager.exists(userId))
8828                return null;
8829            mFlags = flags;
8830            return super.queryIntent(intent, resolvedType,
8831                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8832        }
8833
8834        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8835                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
8836            if (!sUserManager.exists(userId))
8837                return null;
8838            if (packageProviders == null) {
8839                return null;
8840            }
8841            mFlags = flags;
8842            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
8843            final int N = packageProviders.size();
8844            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
8845                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
8846
8847            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
8848            for (int i = 0; i < N; ++i) {
8849                intentFilters = packageProviders.get(i).intents;
8850                if (intentFilters != null && intentFilters.size() > 0) {
8851                    PackageParser.ProviderIntentInfo[] array =
8852                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
8853                    intentFilters.toArray(array);
8854                    listCut.add(array);
8855                }
8856            }
8857            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8858        }
8859
8860        public final void addProvider(PackageParser.Provider p) {
8861            if (mProviders.containsKey(p.getComponentName())) {
8862                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
8863                return;
8864            }
8865
8866            mProviders.put(p.getComponentName(), p);
8867            if (DEBUG_SHOW_INFO) {
8868                Log.v(TAG, "  "
8869                        + (p.info.nonLocalizedLabel != null
8870                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
8871                Log.v(TAG, "    Class=" + p.info.name);
8872            }
8873            final int NI = p.intents.size();
8874            int j;
8875            for (j = 0; j < NI; j++) {
8876                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
8877                if (DEBUG_SHOW_INFO) {
8878                    Log.v(TAG, "    IntentFilter:");
8879                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8880                }
8881                if (!intent.debugCheck()) {
8882                    Log.w(TAG, "==> For Provider " + p.info.name);
8883                }
8884                addFilter(intent);
8885            }
8886        }
8887
8888        public final void removeProvider(PackageParser.Provider p) {
8889            mProviders.remove(p.getComponentName());
8890            if (DEBUG_SHOW_INFO) {
8891                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
8892                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
8893                Log.v(TAG, "    Class=" + p.info.name);
8894            }
8895            final int NI = p.intents.size();
8896            int j;
8897            for (j = 0; j < NI; j++) {
8898                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
8899                if (DEBUG_SHOW_INFO) {
8900                    Log.v(TAG, "    IntentFilter:");
8901                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8902                }
8903                removeFilter(intent);
8904            }
8905        }
8906
8907        @Override
8908        protected boolean allowFilterResult(
8909                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
8910            ProviderInfo filterPi = filter.provider.info;
8911            for (int i = dest.size() - 1; i >= 0; i--) {
8912                ProviderInfo destPi = dest.get(i).providerInfo;
8913                if (destPi.name == filterPi.name
8914                        && destPi.packageName == filterPi.packageName) {
8915                    return false;
8916                }
8917            }
8918            return true;
8919        }
8920
8921        @Override
8922        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
8923            return new PackageParser.ProviderIntentInfo[size];
8924        }
8925
8926        @Override
8927        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
8928            if (!sUserManager.exists(userId))
8929                return true;
8930            PackageParser.Package p = filter.provider.owner;
8931            if (p != null) {
8932                PackageSetting ps = (PackageSetting) p.mExtras;
8933                if (ps != null) {
8934                    // System apps are never considered stopped for purposes of
8935                    // filtering, because there may be no way for the user to
8936                    // actually re-launch them.
8937                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8938                            && ps.getStopped(userId);
8939                }
8940            }
8941            return false;
8942        }
8943
8944        @Override
8945        protected boolean isPackageForFilter(String packageName,
8946                PackageParser.ProviderIntentInfo info) {
8947            return packageName.equals(info.provider.owner.packageName);
8948        }
8949
8950        @Override
8951        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
8952                int match, int userId) {
8953            if (!sUserManager.exists(userId))
8954                return null;
8955            final PackageParser.ProviderIntentInfo info = filter;
8956            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
8957                return null;
8958            }
8959            final PackageParser.Provider provider = info.provider;
8960            if (mSafeMode && (provider.info.applicationInfo.flags
8961                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
8962                return null;
8963            }
8964            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
8965            if (ps == null) {
8966                return null;
8967            }
8968            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
8969                    ps.readUserState(userId), userId);
8970            if (pi == null) {
8971                return null;
8972            }
8973            final ResolveInfo res = new ResolveInfo();
8974            res.providerInfo = pi;
8975            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
8976                res.filter = filter;
8977            }
8978            res.priority = info.getPriority();
8979            res.preferredOrder = provider.owner.mPreferredOrder;
8980            res.match = match;
8981            res.isDefault = info.hasDefault;
8982            res.labelRes = info.labelRes;
8983            res.nonLocalizedLabel = info.nonLocalizedLabel;
8984            res.icon = info.icon;
8985            res.system = res.providerInfo.applicationInfo.isSystemApp();
8986            return res;
8987        }
8988
8989        @Override
8990        protected void sortResults(List<ResolveInfo> results) {
8991            Collections.sort(results, mResolvePrioritySorter);
8992        }
8993
8994        @Override
8995        protected void dumpFilter(PrintWriter out, String prefix,
8996                PackageParser.ProviderIntentInfo filter) {
8997            out.print(prefix);
8998            out.print(
8999                    Integer.toHexString(System.identityHashCode(filter.provider)));
9000            out.print(' ');
9001            filter.provider.printComponentShortName(out);
9002            out.print(" filter ");
9003            out.println(Integer.toHexString(System.identityHashCode(filter)));
9004        }
9005
9006        @Override
9007        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9008            return filter.provider;
9009        }
9010
9011        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9012            PackageParser.Provider provider = (PackageParser.Provider)label;
9013            out.print(prefix); out.print(
9014                    Integer.toHexString(System.identityHashCode(provider)));
9015                    out.print(' ');
9016                    provider.printComponentShortName(out);
9017            if (count > 1) {
9018                out.print(" ("); out.print(count); out.print(" filters)");
9019            }
9020            out.println();
9021        }
9022
9023        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9024                = new ArrayMap<ComponentName, PackageParser.Provider>();
9025        private int mFlags;
9026    };
9027
9028    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9029            new Comparator<ResolveInfo>() {
9030        public int compare(ResolveInfo r1, ResolveInfo r2) {
9031            int v1 = r1.priority;
9032            int v2 = r2.priority;
9033            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9034            if (v1 != v2) {
9035                return (v1 > v2) ? -1 : 1;
9036            }
9037            v1 = r1.preferredOrder;
9038            v2 = r2.preferredOrder;
9039            if (v1 != v2) {
9040                return (v1 > v2) ? -1 : 1;
9041            }
9042            if (r1.isDefault != r2.isDefault) {
9043                return r1.isDefault ? -1 : 1;
9044            }
9045            v1 = r1.match;
9046            v2 = r2.match;
9047            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9048            if (v1 != v2) {
9049                return (v1 > v2) ? -1 : 1;
9050            }
9051            if (r1.system != r2.system) {
9052                return r1.system ? -1 : 1;
9053            }
9054            return 0;
9055        }
9056    };
9057
9058    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9059            new Comparator<ProviderInfo>() {
9060        public int compare(ProviderInfo p1, ProviderInfo p2) {
9061            final int v1 = p1.initOrder;
9062            final int v2 = p2.initOrder;
9063            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9064        }
9065    };
9066
9067    final void sendPackageBroadcast(final String action, final String pkg,
9068            final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
9069            final int[] userIds) {
9070        mHandler.post(new Runnable() {
9071            @Override
9072            public void run() {
9073                try {
9074                    final IActivityManager am = ActivityManagerNative.getDefault();
9075                    if (am == null) return;
9076                    final int[] resolvedUserIds;
9077                    if (userIds == null) {
9078                        resolvedUserIds = am.getRunningUserIds();
9079                    } else {
9080                        resolvedUserIds = userIds;
9081                    }
9082                    for (int id : resolvedUserIds) {
9083                        final Intent intent = new Intent(action,
9084                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9085                        if (extras != null) {
9086                            intent.putExtras(extras);
9087                        }
9088                        if (targetPkg != null) {
9089                            intent.setPackage(targetPkg);
9090                        }
9091                        // Modify the UID when posting to other users
9092                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9093                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9094                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9095                            intent.putExtra(Intent.EXTRA_UID, uid);
9096                        }
9097                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9098                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
9099                        if (DEBUG_BROADCASTS) {
9100                            RuntimeException here = new RuntimeException("here");
9101                            here.fillInStackTrace();
9102                            Slog.d(TAG, "Sending to user " + id + ": "
9103                                    + intent.toShortString(false, true, false, false)
9104                                    + " " + intent.getExtras(), here);
9105                        }
9106                        am.broadcastIntent(null, intent, null, finishedReceiver,
9107                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9108                                null, finishedReceiver != null, false, id);
9109                    }
9110                } catch (RemoteException ex) {
9111                }
9112            }
9113        });
9114    }
9115
9116    /**
9117     * Check if the external storage media is available. This is true if there
9118     * is a mounted external storage medium or if the external storage is
9119     * emulated.
9120     */
9121    private boolean isExternalMediaAvailable() {
9122        return mMediaMounted || Environment.isExternalStorageEmulated();
9123    }
9124
9125    @Override
9126    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9127        // writer
9128        synchronized (mPackages) {
9129            if (!isExternalMediaAvailable()) {
9130                // If the external storage is no longer mounted at this point,
9131                // the caller may not have been able to delete all of this
9132                // packages files and can not delete any more.  Bail.
9133                return null;
9134            }
9135            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9136            if (lastPackage != null) {
9137                pkgs.remove(lastPackage);
9138            }
9139            if (pkgs.size() > 0) {
9140                return pkgs.get(0);
9141            }
9142        }
9143        return null;
9144    }
9145
9146    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9147        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9148                userId, andCode ? 1 : 0, packageName);
9149        if (mSystemReady) {
9150            msg.sendToTarget();
9151        } else {
9152            if (mPostSystemReadyMessages == null) {
9153                mPostSystemReadyMessages = new ArrayList<>();
9154            }
9155            mPostSystemReadyMessages.add(msg);
9156        }
9157    }
9158
9159    void startCleaningPackages() {
9160        // reader
9161        synchronized (mPackages) {
9162            if (!isExternalMediaAvailable()) {
9163                return;
9164            }
9165            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9166                return;
9167            }
9168        }
9169        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9170        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9171        IActivityManager am = ActivityManagerNative.getDefault();
9172        if (am != null) {
9173            try {
9174                am.startService(null, intent, null, UserHandle.USER_OWNER);
9175            } catch (RemoteException e) {
9176            }
9177        }
9178    }
9179
9180    @Override
9181    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9182            int installFlags, String installerPackageName, VerificationParams verificationParams,
9183            String packageAbiOverride) {
9184        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9185                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9186    }
9187
9188    @Override
9189    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9190            int installFlags, String installerPackageName, VerificationParams verificationParams,
9191            String packageAbiOverride, int userId) {
9192        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9193
9194        final int callingUid = Binder.getCallingUid();
9195        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9196
9197        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9198            try {
9199                if (observer != null) {
9200                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9201                }
9202            } catch (RemoteException re) {
9203            }
9204            return;
9205        }
9206
9207        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9208            installFlags |= PackageManager.INSTALL_FROM_ADB;
9209
9210        } else {
9211            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9212            // about installerPackageName.
9213
9214            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9215            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9216        }
9217
9218        UserHandle user;
9219        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9220            user = UserHandle.ALL;
9221        } else {
9222            user = new UserHandle(userId);
9223        }
9224
9225        // Only system components can circumvent runtime permissions when installing.
9226        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9227                && mContext.checkCallingOrSelfPermission(Manifest.permission
9228                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9229            throw new SecurityException("You need the "
9230                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9231                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9232        }
9233
9234        verificationParams.setInstallerUid(callingUid);
9235
9236        final File originFile = new File(originPath);
9237        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9238
9239        final Message msg = mHandler.obtainMessage(INIT_COPY);
9240        msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName,
9241                null, verificationParams, user, packageAbiOverride);
9242        mHandler.sendMessage(msg);
9243    }
9244
9245    void installStage(String packageName, File stagedDir, String stagedCid,
9246            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
9247            String installerPackageName, int installerUid, UserHandle user) {
9248        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
9249                params.referrerUri, installerUid, null);
9250        verifParams.setInstallerUid(installerUid);
9251
9252        final OriginInfo origin;
9253        if (stagedDir != null) {
9254            origin = OriginInfo.fromStagedFile(stagedDir);
9255        } else {
9256            origin = OriginInfo.fromStagedContainer(stagedCid);
9257        }
9258
9259        final Message msg = mHandler.obtainMessage(INIT_COPY);
9260        msg.obj = new InstallParams(origin, null, observer, params.installFlags,
9261                installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride);
9262        mHandler.sendMessage(msg);
9263    }
9264
9265    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
9266        Bundle extras = new Bundle(1);
9267        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
9268
9269        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
9270                packageName, extras, null, null, new int[] {userId});
9271        try {
9272            IActivityManager am = ActivityManagerNative.getDefault();
9273            final boolean isSystem =
9274                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
9275            if (isSystem && am.isUserRunning(userId, false)) {
9276                // The just-installed/enabled app is bundled on the system, so presumed
9277                // to be able to run automatically without needing an explicit launch.
9278                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
9279                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
9280                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
9281                        .setPackage(packageName);
9282                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
9283                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
9284            }
9285        } catch (RemoteException e) {
9286            // shouldn't happen
9287            Slog.w(TAG, "Unable to bootstrap installed package", e);
9288        }
9289    }
9290
9291    @Override
9292    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9293            int userId) {
9294        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9295        PackageSetting pkgSetting;
9296        final int uid = Binder.getCallingUid();
9297        enforceCrossUserPermission(uid, userId, true, true,
9298                "setApplicationHiddenSetting for user " + userId);
9299
9300        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9301            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9302            return false;
9303        }
9304
9305        long callingId = Binder.clearCallingIdentity();
9306        try {
9307            boolean sendAdded = false;
9308            boolean sendRemoved = false;
9309            // writer
9310            synchronized (mPackages) {
9311                pkgSetting = mSettings.mPackages.get(packageName);
9312                if (pkgSetting == null) {
9313                    return false;
9314                }
9315                if (pkgSetting.getHidden(userId) != hidden) {
9316                    pkgSetting.setHidden(hidden, userId);
9317                    mSettings.writePackageRestrictionsLPr(userId);
9318                    if (hidden) {
9319                        sendRemoved = true;
9320                    } else {
9321                        sendAdded = true;
9322                    }
9323                }
9324            }
9325            if (sendAdded) {
9326                sendPackageAddedForUser(packageName, pkgSetting, userId);
9327                return true;
9328            }
9329            if (sendRemoved) {
9330                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
9331                        "hiding pkg");
9332                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
9333            }
9334        } finally {
9335            Binder.restoreCallingIdentity(callingId);
9336        }
9337        return false;
9338    }
9339
9340    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9341            int userId) {
9342        final PackageRemovedInfo info = new PackageRemovedInfo();
9343        info.removedPackage = packageName;
9344        info.removedUsers = new int[] {userId};
9345        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9346        info.sendBroadcast(false, false, false);
9347    }
9348
9349    /**
9350     * Returns true if application is not found or there was an error. Otherwise it returns
9351     * the hidden state of the package for the given user.
9352     */
9353    @Override
9354    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9355        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9356        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9357                false, "getApplicationHidden for user " + userId);
9358        PackageSetting pkgSetting;
9359        long callingId = Binder.clearCallingIdentity();
9360        try {
9361            // writer
9362            synchronized (mPackages) {
9363                pkgSetting = mSettings.mPackages.get(packageName);
9364                if (pkgSetting == null) {
9365                    return true;
9366                }
9367                return pkgSetting.getHidden(userId);
9368            }
9369        } finally {
9370            Binder.restoreCallingIdentity(callingId);
9371        }
9372    }
9373
9374    /**
9375     * @hide
9376     */
9377    @Override
9378    public int installExistingPackageAsUser(String packageName, int userId) {
9379        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9380                null);
9381        PackageSetting pkgSetting;
9382        final int uid = Binder.getCallingUid();
9383        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9384                + userId);
9385        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9386            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9387        }
9388
9389        long callingId = Binder.clearCallingIdentity();
9390        try {
9391            boolean sendAdded = false;
9392
9393            // writer
9394            synchronized (mPackages) {
9395                pkgSetting = mSettings.mPackages.get(packageName);
9396                if (pkgSetting == null) {
9397                    return PackageManager.INSTALL_FAILED_INVALID_URI;
9398                }
9399                if (!pkgSetting.getInstalled(userId)) {
9400                    pkgSetting.setInstalled(true, userId);
9401                    pkgSetting.setHidden(false, userId);
9402                    mSettings.writePackageRestrictionsLPr(userId);
9403                    sendAdded = true;
9404                }
9405            }
9406
9407            if (sendAdded) {
9408                sendPackageAddedForUser(packageName, pkgSetting, userId);
9409            }
9410        } finally {
9411            Binder.restoreCallingIdentity(callingId);
9412        }
9413
9414        return PackageManager.INSTALL_SUCCEEDED;
9415    }
9416
9417    boolean isUserRestricted(int userId, String restrictionKey) {
9418        Bundle restrictions = sUserManager.getUserRestrictions(userId);
9419        if (restrictions.getBoolean(restrictionKey, false)) {
9420            Log.w(TAG, "User is restricted: " + restrictionKey);
9421            return true;
9422        }
9423        return false;
9424    }
9425
9426    @Override
9427    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
9428        mContext.enforceCallingOrSelfPermission(
9429                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9430                "Only package verification agents can verify applications");
9431
9432        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9433        final PackageVerificationResponse response = new PackageVerificationResponse(
9434                verificationCode, Binder.getCallingUid());
9435        msg.arg1 = id;
9436        msg.obj = response;
9437        mHandler.sendMessage(msg);
9438    }
9439
9440    @Override
9441    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
9442            long millisecondsToDelay) {
9443        mContext.enforceCallingOrSelfPermission(
9444                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9445                "Only package verification agents can extend verification timeouts");
9446
9447        final PackageVerificationState state = mPendingVerification.get(id);
9448        final PackageVerificationResponse response = new PackageVerificationResponse(
9449                verificationCodeAtTimeout, Binder.getCallingUid());
9450
9451        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
9452            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
9453        }
9454        if (millisecondsToDelay < 0) {
9455            millisecondsToDelay = 0;
9456        }
9457        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9458                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9459            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9460        }
9461
9462        if ((state != null) && !state.timeoutExtended()) {
9463            state.extendTimeout();
9464
9465            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9466            msg.arg1 = id;
9467            msg.obj = response;
9468            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
9469        }
9470    }
9471
9472    private void broadcastPackageVerified(int verificationId, Uri packageUri,
9473            int verificationCode, UserHandle user) {
9474        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
9475        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
9476        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9477        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9478        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
9479
9480        mContext.sendBroadcastAsUser(intent, user,
9481                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
9482    }
9483
9484    private ComponentName matchComponentForVerifier(String packageName,
9485            List<ResolveInfo> receivers) {
9486        ActivityInfo targetReceiver = null;
9487
9488        final int NR = receivers.size();
9489        for (int i = 0; i < NR; i++) {
9490            final ResolveInfo info = receivers.get(i);
9491            if (info.activityInfo == null) {
9492                continue;
9493            }
9494
9495            if (packageName.equals(info.activityInfo.packageName)) {
9496                targetReceiver = info.activityInfo;
9497                break;
9498            }
9499        }
9500
9501        if (targetReceiver == null) {
9502            return null;
9503        }
9504
9505        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
9506    }
9507
9508    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
9509            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
9510        if (pkgInfo.verifiers.length == 0) {
9511            return null;
9512        }
9513
9514        final int N = pkgInfo.verifiers.length;
9515        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
9516        for (int i = 0; i < N; i++) {
9517            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
9518
9519            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
9520                    receivers);
9521            if (comp == null) {
9522                continue;
9523            }
9524
9525            final int verifierUid = getUidForVerifier(verifierInfo);
9526            if (verifierUid == -1) {
9527                continue;
9528            }
9529
9530            if (DEBUG_VERIFY) {
9531                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
9532                        + " with the correct signature");
9533            }
9534            sufficientVerifiers.add(comp);
9535            verificationState.addSufficientVerifier(verifierUid);
9536        }
9537
9538        return sufficientVerifiers;
9539    }
9540
9541    private int getUidForVerifier(VerifierInfo verifierInfo) {
9542        synchronized (mPackages) {
9543            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
9544            if (pkg == null) {
9545                return -1;
9546            } else if (pkg.mSignatures.length != 1) {
9547                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9548                        + " has more than one signature; ignoring");
9549                return -1;
9550            }
9551
9552            /*
9553             * If the public key of the package's signature does not match
9554             * our expected public key, then this is a different package and
9555             * we should skip.
9556             */
9557
9558            final byte[] expectedPublicKey;
9559            try {
9560                final Signature verifierSig = pkg.mSignatures[0];
9561                final PublicKey publicKey = verifierSig.getPublicKey();
9562                expectedPublicKey = publicKey.getEncoded();
9563            } catch (CertificateException e) {
9564                return -1;
9565            }
9566
9567            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
9568
9569            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
9570                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9571                        + " does not have the expected public key; ignoring");
9572                return -1;
9573            }
9574
9575            return pkg.applicationInfo.uid;
9576        }
9577    }
9578
9579    @Override
9580    public void finishPackageInstall(int token) {
9581        enforceSystemOrRoot("Only the system is allowed to finish installs");
9582
9583        if (DEBUG_INSTALL) {
9584            Slog.v(TAG, "BM finishing package install for " + token);
9585        }
9586
9587        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9588        mHandler.sendMessage(msg);
9589    }
9590
9591    /**
9592     * Get the verification agent timeout.
9593     *
9594     * @return verification timeout in milliseconds
9595     */
9596    private long getVerificationTimeout() {
9597        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
9598                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
9599                DEFAULT_VERIFICATION_TIMEOUT);
9600    }
9601
9602    /**
9603     * Get the default verification agent response code.
9604     *
9605     * @return default verification response code
9606     */
9607    private int getDefaultVerificationResponse() {
9608        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9609                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
9610                DEFAULT_VERIFICATION_RESPONSE);
9611    }
9612
9613    /**
9614     * Check whether or not package verification has been enabled.
9615     *
9616     * @return true if verification should be performed
9617     */
9618    private boolean isVerificationEnabled(int userId, int installFlags) {
9619        if (!DEFAULT_VERIFY_ENABLE) {
9620            return false;
9621        }
9622
9623        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
9624
9625        // Check if installing from ADB
9626        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
9627            // Do not run verification in a test harness environment
9628            if (ActivityManager.isRunningInTestHarness()) {
9629                return false;
9630            }
9631            if (ensureVerifyAppsEnabled) {
9632                return true;
9633            }
9634            // Check if the developer does not want package verification for ADB installs
9635            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9636                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
9637                return false;
9638            }
9639        }
9640
9641        if (ensureVerifyAppsEnabled) {
9642            return true;
9643        }
9644
9645        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9646                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9647    }
9648
9649    @Override
9650    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9651            throws RemoteException {
9652        mContext.enforceCallingOrSelfPermission(
9653                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9654                "Only intentfilter verification agents can verify applications");
9655
9656        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9657        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9658                Binder.getCallingUid(), verificationCode, failedDomains);
9659        msg.arg1 = id;
9660        msg.obj = response;
9661        mHandler.sendMessage(msg);
9662    }
9663
9664    @Override
9665    public int getIntentVerificationStatus(String packageName, int userId) {
9666        synchronized (mPackages) {
9667            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
9668        }
9669    }
9670
9671    @Override
9672    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
9673        mContext.enforceCallingOrSelfPermission(
9674                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9675
9676        boolean result = false;
9677        synchronized (mPackages) {
9678            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
9679        }
9680        if (result) {
9681            scheduleWritePackageRestrictionsLocked(userId);
9682        }
9683        return result;
9684    }
9685
9686    @Override
9687    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
9688        synchronized (mPackages) {
9689            return mSettings.getIntentFilterVerificationsLPr(packageName);
9690        }
9691    }
9692
9693    @Override
9694    public List<IntentFilter> getAllIntentFilters(String packageName) {
9695        if (TextUtils.isEmpty(packageName)) {
9696            return Collections.<IntentFilter>emptyList();
9697        }
9698        synchronized (mPackages) {
9699            PackageParser.Package pkg = mPackages.get(packageName);
9700            if (pkg == null || pkg.activities == null) {
9701                return Collections.<IntentFilter>emptyList();
9702            }
9703            final int count = pkg.activities.size();
9704            ArrayList<IntentFilter> result = new ArrayList<>();
9705            for (int n=0; n<count; n++) {
9706                PackageParser.Activity activity = pkg.activities.get(n);
9707                if (activity.intents != null || activity.intents.size() > 0) {
9708                    result.addAll(activity.intents);
9709                }
9710            }
9711            return result;
9712        }
9713    }
9714
9715    @Override
9716    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
9717        mContext.enforceCallingOrSelfPermission(
9718                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9719
9720        synchronized (mPackages) {
9721            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
9722            if (packageName != null) {
9723                result |= updateIntentVerificationStatus(packageName,
9724                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
9725                        UserHandle.myUserId());
9726                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
9727                        packageName, userId);
9728            }
9729            return result;
9730        }
9731    }
9732
9733    @Override
9734    public String getDefaultBrowserPackageName(int userId) {
9735        synchronized (mPackages) {
9736            return mSettings.getDefaultBrowserPackageNameLPw(userId);
9737        }
9738    }
9739
9740    /**
9741     * Get the "allow unknown sources" setting.
9742     *
9743     * @return the current "allow unknown sources" setting
9744     */
9745    private int getUnknownSourcesSettings() {
9746        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9747                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
9748                -1);
9749    }
9750
9751    @Override
9752    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
9753        final int uid = Binder.getCallingUid();
9754        // writer
9755        synchronized (mPackages) {
9756            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
9757            if (targetPackageSetting == null) {
9758                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
9759            }
9760
9761            PackageSetting installerPackageSetting;
9762            if (installerPackageName != null) {
9763                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
9764                if (installerPackageSetting == null) {
9765                    throw new IllegalArgumentException("Unknown installer package: "
9766                            + installerPackageName);
9767                }
9768            } else {
9769                installerPackageSetting = null;
9770            }
9771
9772            Signature[] callerSignature;
9773            Object obj = mSettings.getUserIdLPr(uid);
9774            if (obj != null) {
9775                if (obj instanceof SharedUserSetting) {
9776                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
9777                } else if (obj instanceof PackageSetting) {
9778                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
9779                } else {
9780                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
9781                }
9782            } else {
9783                throw new SecurityException("Unknown calling uid " + uid);
9784            }
9785
9786            // Verify: can't set installerPackageName to a package that is
9787            // not signed with the same cert as the caller.
9788            if (installerPackageSetting != null) {
9789                if (compareSignatures(callerSignature,
9790                        installerPackageSetting.signatures.mSignatures)
9791                        != PackageManager.SIGNATURE_MATCH) {
9792                    throw new SecurityException(
9793                            "Caller does not have same cert as new installer package "
9794                            + installerPackageName);
9795                }
9796            }
9797
9798            // Verify: if target already has an installer package, it must
9799            // be signed with the same cert as the caller.
9800            if (targetPackageSetting.installerPackageName != null) {
9801                PackageSetting setting = mSettings.mPackages.get(
9802                        targetPackageSetting.installerPackageName);
9803                // If the currently set package isn't valid, then it's always
9804                // okay to change it.
9805                if (setting != null) {
9806                    if (compareSignatures(callerSignature,
9807                            setting.signatures.mSignatures)
9808                            != PackageManager.SIGNATURE_MATCH) {
9809                        throw new SecurityException(
9810                                "Caller does not have same cert as old installer package "
9811                                + targetPackageSetting.installerPackageName);
9812                    }
9813                }
9814            }
9815
9816            // Okay!
9817            targetPackageSetting.installerPackageName = installerPackageName;
9818            scheduleWriteSettingsLocked();
9819        }
9820    }
9821
9822    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
9823        // Queue up an async operation since the package installation may take a little while.
9824        mHandler.post(new Runnable() {
9825            public void run() {
9826                mHandler.removeCallbacks(this);
9827                 // Result object to be returned
9828                PackageInstalledInfo res = new PackageInstalledInfo();
9829                res.returnCode = currentStatus;
9830                res.uid = -1;
9831                res.pkg = null;
9832                res.removedInfo = new PackageRemovedInfo();
9833                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
9834                    args.doPreInstall(res.returnCode);
9835                    synchronized (mInstallLock) {
9836                        installPackageLI(args, res);
9837                    }
9838                    args.doPostInstall(res.returnCode, res.uid);
9839                }
9840
9841                // A restore should be performed at this point if (a) the install
9842                // succeeded, (b) the operation is not an update, and (c) the new
9843                // package has not opted out of backup participation.
9844                final boolean update = res.removedInfo.removedPackage != null;
9845                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
9846                boolean doRestore = !update
9847                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
9848
9849                // Set up the post-install work request bookkeeping.  This will be used
9850                // and cleaned up by the post-install event handling regardless of whether
9851                // there's a restore pass performed.  Token values are >= 1.
9852                int token;
9853                if (mNextInstallToken < 0) mNextInstallToken = 1;
9854                token = mNextInstallToken++;
9855
9856                PostInstallData data = new PostInstallData(args, res);
9857                mRunningInstalls.put(token, data);
9858                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
9859
9860                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
9861                    // Pass responsibility to the Backup Manager.  It will perform a
9862                    // restore if appropriate, then pass responsibility back to the
9863                    // Package Manager to run the post-install observer callbacks
9864                    // and broadcasts.
9865                    IBackupManager bm = IBackupManager.Stub.asInterface(
9866                            ServiceManager.getService(Context.BACKUP_SERVICE));
9867                    if (bm != null) {
9868                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
9869                                + " to BM for possible restore");
9870                        try {
9871                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
9872                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
9873                            } else {
9874                                doRestore = false;
9875                            }
9876                        } catch (RemoteException e) {
9877                            // can't happen; the backup manager is local
9878                        } catch (Exception e) {
9879                            Slog.e(TAG, "Exception trying to enqueue restore", e);
9880                            doRestore = false;
9881                        }
9882                    } else {
9883                        Slog.e(TAG, "Backup Manager not found!");
9884                        doRestore = false;
9885                    }
9886                }
9887
9888                if (!doRestore) {
9889                    // No restore possible, or the Backup Manager was mysteriously not
9890                    // available -- just fire the post-install work request directly.
9891                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
9892                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9893                    mHandler.sendMessage(msg);
9894                }
9895            }
9896        });
9897    }
9898
9899    private abstract class HandlerParams {
9900        private static final int MAX_RETRIES = 4;
9901
9902        /**
9903         * Number of times startCopy() has been attempted and had a non-fatal
9904         * error.
9905         */
9906        private int mRetries = 0;
9907
9908        /** User handle for the user requesting the information or installation. */
9909        private final UserHandle mUser;
9910
9911        HandlerParams(UserHandle user) {
9912            mUser = user;
9913        }
9914
9915        UserHandle getUser() {
9916            return mUser;
9917        }
9918
9919        final boolean startCopy() {
9920            boolean res;
9921            try {
9922                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
9923
9924                if (++mRetries > MAX_RETRIES) {
9925                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
9926                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
9927                    handleServiceError();
9928                    return false;
9929                } else {
9930                    handleStartCopy();
9931                    res = true;
9932                }
9933            } catch (RemoteException e) {
9934                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
9935                mHandler.sendEmptyMessage(MCS_RECONNECT);
9936                res = false;
9937            }
9938            handleReturnCode();
9939            return res;
9940        }
9941
9942        final void serviceError() {
9943            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
9944            handleServiceError();
9945            handleReturnCode();
9946        }
9947
9948        abstract void handleStartCopy() throws RemoteException;
9949        abstract void handleServiceError();
9950        abstract void handleReturnCode();
9951    }
9952
9953    class MeasureParams extends HandlerParams {
9954        private final PackageStats mStats;
9955        private boolean mSuccess;
9956
9957        private final IPackageStatsObserver mObserver;
9958
9959        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
9960            super(new UserHandle(stats.userHandle));
9961            mObserver = observer;
9962            mStats = stats;
9963        }
9964
9965        @Override
9966        public String toString() {
9967            return "MeasureParams{"
9968                + Integer.toHexString(System.identityHashCode(this))
9969                + " " + mStats.packageName + "}";
9970        }
9971
9972        @Override
9973        void handleStartCopy() throws RemoteException {
9974            synchronized (mInstallLock) {
9975                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
9976            }
9977
9978            if (mSuccess) {
9979                final boolean mounted;
9980                if (Environment.isExternalStorageEmulated()) {
9981                    mounted = true;
9982                } else {
9983                    final String status = Environment.getExternalStorageState();
9984                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
9985                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
9986                }
9987
9988                if (mounted) {
9989                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
9990
9991                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
9992                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
9993
9994                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
9995                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
9996
9997                    // Always subtract cache size, since it's a subdirectory
9998                    mStats.externalDataSize -= mStats.externalCacheSize;
9999
10000                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10001                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10002
10003                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10004                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10005                }
10006            }
10007        }
10008
10009        @Override
10010        void handleReturnCode() {
10011            if (mObserver != null) {
10012                try {
10013                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10014                } catch (RemoteException e) {
10015                    Slog.i(TAG, "Observer no longer exists.");
10016                }
10017            }
10018        }
10019
10020        @Override
10021        void handleServiceError() {
10022            Slog.e(TAG, "Could not measure application " + mStats.packageName
10023                            + " external storage");
10024        }
10025    }
10026
10027    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10028            throws RemoteException {
10029        long result = 0;
10030        for (File path : paths) {
10031            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10032        }
10033        return result;
10034    }
10035
10036    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10037        for (File path : paths) {
10038            try {
10039                mcs.clearDirectory(path.getAbsolutePath());
10040            } catch (RemoteException e) {
10041            }
10042        }
10043    }
10044
10045    static class OriginInfo {
10046        /**
10047         * Location where install is coming from, before it has been
10048         * copied/renamed into place. This could be a single monolithic APK
10049         * file, or a cluster directory. This location may be untrusted.
10050         */
10051        final File file;
10052        final String cid;
10053
10054        /**
10055         * Flag indicating that {@link #file} or {@link #cid} has already been
10056         * staged, meaning downstream users don't need to defensively copy the
10057         * contents.
10058         */
10059        final boolean staged;
10060
10061        /**
10062         * Flag indicating that {@link #file} or {@link #cid} is an already
10063         * installed app that is being moved.
10064         */
10065        final boolean existing;
10066
10067        final String resolvedPath;
10068        final File resolvedFile;
10069
10070        static OriginInfo fromNothing() {
10071            return new OriginInfo(null, null, false, false);
10072        }
10073
10074        static OriginInfo fromUntrustedFile(File file) {
10075            return new OriginInfo(file, null, false, false);
10076        }
10077
10078        static OriginInfo fromExistingFile(File file) {
10079            return new OriginInfo(file, null, false, true);
10080        }
10081
10082        static OriginInfo fromStagedFile(File file) {
10083            return new OriginInfo(file, null, true, false);
10084        }
10085
10086        static OriginInfo fromStagedContainer(String cid) {
10087            return new OriginInfo(null, cid, true, false);
10088        }
10089
10090        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10091            this.file = file;
10092            this.cid = cid;
10093            this.staged = staged;
10094            this.existing = existing;
10095
10096            if (cid != null) {
10097                resolvedPath = PackageHelper.getSdDir(cid);
10098                resolvedFile = new File(resolvedPath);
10099            } else if (file != null) {
10100                resolvedPath = file.getAbsolutePath();
10101                resolvedFile = file;
10102            } else {
10103                resolvedPath = null;
10104                resolvedFile = null;
10105            }
10106        }
10107    }
10108
10109    class MoveInfo {
10110        final int moveId;
10111        final String fromUuid;
10112        final String toUuid;
10113        final String packageName;
10114        final String dataAppName;
10115        final int appId;
10116        final String seinfo;
10117
10118        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10119                String dataAppName, int appId, String seinfo) {
10120            this.moveId = moveId;
10121            this.fromUuid = fromUuid;
10122            this.toUuid = toUuid;
10123            this.packageName = packageName;
10124            this.dataAppName = dataAppName;
10125            this.appId = appId;
10126            this.seinfo = seinfo;
10127        }
10128    }
10129
10130    class InstallParams extends HandlerParams {
10131        final OriginInfo origin;
10132        final MoveInfo move;
10133        final IPackageInstallObserver2 observer;
10134        int installFlags;
10135        final String installerPackageName;
10136        final String volumeUuid;
10137        final VerificationParams verificationParams;
10138        private InstallArgs mArgs;
10139        private int mRet;
10140        final String packageAbiOverride;
10141
10142        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10143                int installFlags, String installerPackageName, String volumeUuid,
10144                VerificationParams verificationParams, UserHandle user, String packageAbiOverride) {
10145            super(user);
10146            this.origin = origin;
10147            this.move = move;
10148            this.observer = observer;
10149            this.installFlags = installFlags;
10150            this.installerPackageName = installerPackageName;
10151            this.volumeUuid = volumeUuid;
10152            this.verificationParams = verificationParams;
10153            this.packageAbiOverride = packageAbiOverride;
10154        }
10155
10156        @Override
10157        public String toString() {
10158            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10159                    + " file=" + origin.file + " cid=" + origin.cid + "}";
10160        }
10161
10162        public ManifestDigest getManifestDigest() {
10163            if (verificationParams == null) {
10164                return null;
10165            }
10166            return verificationParams.getManifestDigest();
10167        }
10168
10169        private int installLocationPolicy(PackageInfoLite pkgLite) {
10170            String packageName = pkgLite.packageName;
10171            int installLocation = pkgLite.installLocation;
10172            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10173            // reader
10174            synchronized (mPackages) {
10175                PackageParser.Package pkg = mPackages.get(packageName);
10176                if (pkg != null) {
10177                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10178                        // Check for downgrading.
10179                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10180                            try {
10181                                checkDowngrade(pkg, pkgLite);
10182                            } catch (PackageManagerException e) {
10183                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10184                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
10185                            }
10186                        }
10187                        // Check for updated system application.
10188                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10189                            if (onSd) {
10190                                Slog.w(TAG, "Cannot install update to system app on sdcard");
10191                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
10192                            }
10193                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10194                        } else {
10195                            if (onSd) {
10196                                // Install flag overrides everything.
10197                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10198                            }
10199                            // If current upgrade specifies particular preference
10200                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
10201                                // Application explicitly specified internal.
10202                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10203                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
10204                                // App explictly prefers external. Let policy decide
10205                            } else {
10206                                // Prefer previous location
10207                                if (isExternal(pkg)) {
10208                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10209                                }
10210                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10211                            }
10212                        }
10213                    } else {
10214                        // Invalid install. Return error code
10215                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
10216                    }
10217                }
10218            }
10219            // All the special cases have been taken care of.
10220            // Return result based on recommended install location.
10221            if (onSd) {
10222                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10223            }
10224            return pkgLite.recommendedInstallLocation;
10225        }
10226
10227        /*
10228         * Invoke remote method to get package information and install
10229         * location values. Override install location based on default
10230         * policy if needed and then create install arguments based
10231         * on the install location.
10232         */
10233        public void handleStartCopy() throws RemoteException {
10234            int ret = PackageManager.INSTALL_SUCCEEDED;
10235
10236            // If we're already staged, we've firmly committed to an install location
10237            if (origin.staged) {
10238                if (origin.file != null) {
10239                    installFlags |= PackageManager.INSTALL_INTERNAL;
10240                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10241                } else if (origin.cid != null) {
10242                    installFlags |= PackageManager.INSTALL_EXTERNAL;
10243                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
10244                } else {
10245                    throw new IllegalStateException("Invalid stage location");
10246                }
10247            }
10248
10249            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10250            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
10251
10252            PackageInfoLite pkgLite = null;
10253
10254            if (onInt && onSd) {
10255                // Check if both bits are set.
10256                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
10257                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10258            } else {
10259                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
10260                        packageAbiOverride);
10261
10262                /*
10263                 * If we have too little free space, try to free cache
10264                 * before giving up.
10265                 */
10266                if (!origin.staged && pkgLite.recommendedInstallLocation
10267                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10268                    // TODO: focus freeing disk space on the target device
10269                    final StorageManager storage = StorageManager.from(mContext);
10270                    final long lowThreshold = storage.getStorageLowBytes(
10271                            Environment.getDataDirectory());
10272
10273                    final long sizeBytes = mContainerService.calculateInstalledSize(
10274                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
10275
10276                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
10277                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
10278                                installFlags, packageAbiOverride);
10279                    }
10280
10281                    /*
10282                     * The cache free must have deleted the file we
10283                     * downloaded to install.
10284                     *
10285                     * TODO: fix the "freeCache" call to not delete
10286                     *       the file we care about.
10287                     */
10288                    if (pkgLite.recommendedInstallLocation
10289                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10290                        pkgLite.recommendedInstallLocation
10291                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
10292                    }
10293                }
10294            }
10295
10296            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10297                int loc = pkgLite.recommendedInstallLocation;
10298                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
10299                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10300                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
10301                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
10302                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10303                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10304                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
10305                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
10306                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10307                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
10308                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
10309                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
10310                } else {
10311                    // Override with defaults if needed.
10312                    loc = installLocationPolicy(pkgLite);
10313                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
10314                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
10315                    } else if (!onSd && !onInt) {
10316                        // Override install location with flags
10317                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
10318                            // Set the flag to install on external media.
10319                            installFlags |= PackageManager.INSTALL_EXTERNAL;
10320                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
10321                        } else {
10322                            // Make sure the flag for installing on external
10323                            // media is unset
10324                            installFlags |= PackageManager.INSTALL_INTERNAL;
10325                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10326                        }
10327                    }
10328                }
10329            }
10330
10331            final InstallArgs args = createInstallArgs(this);
10332            mArgs = args;
10333
10334            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10335                 /*
10336                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
10337                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
10338                 */
10339                int userIdentifier = getUser().getIdentifier();
10340                if (userIdentifier == UserHandle.USER_ALL
10341                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
10342                    userIdentifier = UserHandle.USER_OWNER;
10343                }
10344
10345                /*
10346                 * Determine if we have any installed package verifiers. If we
10347                 * do, then we'll defer to them to verify the packages.
10348                 */
10349                final int requiredUid = mRequiredVerifierPackage == null ? -1
10350                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
10351                if (!origin.existing && requiredUid != -1
10352                        && isVerificationEnabled(userIdentifier, installFlags)) {
10353                    final Intent verification = new Intent(
10354                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
10355                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10356                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
10357                            PACKAGE_MIME_TYPE);
10358                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10359
10360                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
10361                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10362                            0 /* TODO: Which userId? */);
10363
10364                    if (DEBUG_VERIFY) {
10365                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10366                                + verification.toString() + " with " + pkgLite.verifiers.length
10367                                + " optional verifiers");
10368                    }
10369
10370                    final int verificationId = mPendingVerificationToken++;
10371
10372                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10373
10374                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10375                            installerPackageName);
10376
10377                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10378                            installFlags);
10379
10380                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10381                            pkgLite.packageName);
10382
10383                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10384                            pkgLite.versionCode);
10385
10386                    if (verificationParams != null) {
10387                        if (verificationParams.getVerificationURI() != null) {
10388                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10389                                 verificationParams.getVerificationURI());
10390                        }
10391                        if (verificationParams.getOriginatingURI() != null) {
10392                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10393                                  verificationParams.getOriginatingURI());
10394                        }
10395                        if (verificationParams.getReferrer() != null) {
10396                            verification.putExtra(Intent.EXTRA_REFERRER,
10397                                  verificationParams.getReferrer());
10398                        }
10399                        if (verificationParams.getOriginatingUid() >= 0) {
10400                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
10401                                  verificationParams.getOriginatingUid());
10402                        }
10403                        if (verificationParams.getInstallerUid() >= 0) {
10404                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
10405                                  verificationParams.getInstallerUid());
10406                        }
10407                    }
10408
10409                    final PackageVerificationState verificationState = new PackageVerificationState(
10410                            requiredUid, args);
10411
10412                    mPendingVerification.append(verificationId, verificationState);
10413
10414                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
10415                            receivers, verificationState);
10416
10417                    /*
10418                     * If any sufficient verifiers were listed in the package
10419                     * manifest, attempt to ask them.
10420                     */
10421                    if (sufficientVerifiers != null) {
10422                        final int N = sufficientVerifiers.size();
10423                        if (N == 0) {
10424                            Slog.i(TAG, "Additional verifiers required, but none installed.");
10425                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
10426                        } else {
10427                            for (int i = 0; i < N; i++) {
10428                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
10429
10430                                final Intent sufficientIntent = new Intent(verification);
10431                                sufficientIntent.setComponent(verifierComponent);
10432
10433                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
10434                            }
10435                        }
10436                    }
10437
10438                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
10439                            mRequiredVerifierPackage, receivers);
10440                    if (ret == PackageManager.INSTALL_SUCCEEDED
10441                            && mRequiredVerifierPackage != null) {
10442                        /*
10443                         * Send the intent to the required verification agent,
10444                         * but only start the verification timeout after the
10445                         * target BroadcastReceivers have run.
10446                         */
10447                        verification.setComponent(requiredVerifierComponent);
10448                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
10449                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10450                                new BroadcastReceiver() {
10451                                    @Override
10452                                    public void onReceive(Context context, Intent intent) {
10453                                        final Message msg = mHandler
10454                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
10455                                        msg.arg1 = verificationId;
10456                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
10457                                    }
10458                                }, null, 0, null, null);
10459
10460                        /*
10461                         * We don't want the copy to proceed until verification
10462                         * succeeds, so null out this field.
10463                         */
10464                        mArgs = null;
10465                    }
10466                } else {
10467                    /*
10468                     * No package verification is enabled, so immediately start
10469                     * the remote call to initiate copy using temporary file.
10470                     */
10471                    ret = args.copyApk(mContainerService, true);
10472                }
10473            }
10474
10475            mRet = ret;
10476        }
10477
10478        @Override
10479        void handleReturnCode() {
10480            // If mArgs is null, then MCS couldn't be reached. When it
10481            // reconnects, it will try again to install. At that point, this
10482            // will succeed.
10483            if (mArgs != null) {
10484                processPendingInstall(mArgs, mRet);
10485            }
10486        }
10487
10488        @Override
10489        void handleServiceError() {
10490            mArgs = createInstallArgs(this);
10491            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10492        }
10493
10494        public boolean isForwardLocked() {
10495            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10496        }
10497    }
10498
10499    /**
10500     * Used during creation of InstallArgs
10501     *
10502     * @param installFlags package installation flags
10503     * @return true if should be installed on external storage
10504     */
10505    private static boolean installOnExternalAsec(int installFlags) {
10506        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
10507            return false;
10508        }
10509        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
10510            return true;
10511        }
10512        return false;
10513    }
10514
10515    /**
10516     * Used during creation of InstallArgs
10517     *
10518     * @param installFlags package installation flags
10519     * @return true if should be installed as forward locked
10520     */
10521    private static boolean installForwardLocked(int installFlags) {
10522        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10523    }
10524
10525    private InstallArgs createInstallArgs(InstallParams params) {
10526        if (params.move != null) {
10527            return new MoveInstallArgs(params);
10528        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
10529            return new AsecInstallArgs(params);
10530        } else {
10531            return new FileInstallArgs(params);
10532        }
10533    }
10534
10535    /**
10536     * Create args that describe an existing installed package. Typically used
10537     * when cleaning up old installs, or used as a move source.
10538     */
10539    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
10540            String resourcePath, String[] instructionSets) {
10541        final boolean isInAsec;
10542        if (installOnExternalAsec(installFlags)) {
10543            /* Apps on SD card are always in ASEC containers. */
10544            isInAsec = true;
10545        } else if (installForwardLocked(installFlags)
10546                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
10547            /*
10548             * Forward-locked apps are only in ASEC containers if they're the
10549             * new style
10550             */
10551            isInAsec = true;
10552        } else {
10553            isInAsec = false;
10554        }
10555
10556        if (isInAsec) {
10557            return new AsecInstallArgs(codePath, instructionSets,
10558                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
10559        } else {
10560            return new FileInstallArgs(codePath, resourcePath, instructionSets);
10561        }
10562    }
10563
10564    static abstract class InstallArgs {
10565        /** @see InstallParams#origin */
10566        final OriginInfo origin;
10567        /** @see InstallParams#move */
10568        final MoveInfo move;
10569
10570        final IPackageInstallObserver2 observer;
10571        // Always refers to PackageManager flags only
10572        final int installFlags;
10573        final String installerPackageName;
10574        final String volumeUuid;
10575        final ManifestDigest manifestDigest;
10576        final UserHandle user;
10577        final String abiOverride;
10578
10579        // The list of instruction sets supported by this app. This is currently
10580        // only used during the rmdex() phase to clean up resources. We can get rid of this
10581        // if we move dex files under the common app path.
10582        /* nullable */ String[] instructionSets;
10583
10584        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10585                int installFlags, String installerPackageName, String volumeUuid,
10586                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
10587                String abiOverride) {
10588            this.origin = origin;
10589            this.move = move;
10590            this.installFlags = installFlags;
10591            this.observer = observer;
10592            this.installerPackageName = installerPackageName;
10593            this.volumeUuid = volumeUuid;
10594            this.manifestDigest = manifestDigest;
10595            this.user = user;
10596            this.instructionSets = instructionSets;
10597            this.abiOverride = abiOverride;
10598        }
10599
10600        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
10601        abstract int doPreInstall(int status);
10602
10603        /**
10604         * Rename package into final resting place. All paths on the given
10605         * scanned package should be updated to reflect the rename.
10606         */
10607        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
10608        abstract int doPostInstall(int status, int uid);
10609
10610        /** @see PackageSettingBase#codePathString */
10611        abstract String getCodePath();
10612        /** @see PackageSettingBase#resourcePathString */
10613        abstract String getResourcePath();
10614
10615        // Need installer lock especially for dex file removal.
10616        abstract void cleanUpResourcesLI();
10617        abstract boolean doPostDeleteLI(boolean delete);
10618
10619        /**
10620         * Called before the source arguments are copied. This is used mostly
10621         * for MoveParams when it needs to read the source file to put it in the
10622         * destination.
10623         */
10624        int doPreCopy() {
10625            return PackageManager.INSTALL_SUCCEEDED;
10626        }
10627
10628        /**
10629         * Called after the source arguments are copied. This is used mostly for
10630         * MoveParams when it needs to read the source file to put it in the
10631         * destination.
10632         *
10633         * @return
10634         */
10635        int doPostCopy(int uid) {
10636            return PackageManager.INSTALL_SUCCEEDED;
10637        }
10638
10639        protected boolean isFwdLocked() {
10640            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10641        }
10642
10643        protected boolean isExternalAsec() {
10644            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10645        }
10646
10647        UserHandle getUser() {
10648            return user;
10649        }
10650    }
10651
10652    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
10653        if (!allCodePaths.isEmpty()) {
10654            if (instructionSets == null) {
10655                throw new IllegalStateException("instructionSet == null");
10656            }
10657            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
10658            for (String codePath : allCodePaths) {
10659                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
10660                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
10661                    if (retCode < 0) {
10662                        Slog.w(TAG, "Couldn't remove dex file for package: "
10663                                + " at location " + codePath + ", retcode=" + retCode);
10664                        // we don't consider this to be a failure of the core package deletion
10665                    }
10666                }
10667            }
10668        }
10669    }
10670
10671    /**
10672     * Logic to handle installation of non-ASEC applications, including copying
10673     * and renaming logic.
10674     */
10675    class FileInstallArgs extends InstallArgs {
10676        private File codeFile;
10677        private File resourceFile;
10678
10679        // Example topology:
10680        // /data/app/com.example/base.apk
10681        // /data/app/com.example/split_foo.apk
10682        // /data/app/com.example/lib/arm/libfoo.so
10683        // /data/app/com.example/lib/arm64/libfoo.so
10684        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
10685
10686        /** New install */
10687        FileInstallArgs(InstallParams params) {
10688            super(params.origin, params.move, params.observer, params.installFlags,
10689                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10690                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10691            if (isFwdLocked()) {
10692                throw new IllegalArgumentException("Forward locking only supported in ASEC");
10693            }
10694        }
10695
10696        /** Existing install */
10697        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
10698            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
10699                    null);
10700            this.codeFile = (codePath != null) ? new File(codePath) : null;
10701            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
10702        }
10703
10704        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10705            if (origin.staged) {
10706                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
10707                codeFile = origin.file;
10708                resourceFile = origin.file;
10709                return PackageManager.INSTALL_SUCCEEDED;
10710            }
10711
10712            try {
10713                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
10714                codeFile = tempDir;
10715                resourceFile = tempDir;
10716            } catch (IOException e) {
10717                Slog.w(TAG, "Failed to create copy file: " + e);
10718                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10719            }
10720
10721            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
10722                @Override
10723                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
10724                    if (!FileUtils.isValidExtFilename(name)) {
10725                        throw new IllegalArgumentException("Invalid filename: " + name);
10726                    }
10727                    try {
10728                        final File file = new File(codeFile, name);
10729                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
10730                                O_RDWR | O_CREAT, 0644);
10731                        Os.chmod(file.getAbsolutePath(), 0644);
10732                        return new ParcelFileDescriptor(fd);
10733                    } catch (ErrnoException e) {
10734                        throw new RemoteException("Failed to open: " + e.getMessage());
10735                    }
10736                }
10737            };
10738
10739            int ret = PackageManager.INSTALL_SUCCEEDED;
10740            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
10741            if (ret != PackageManager.INSTALL_SUCCEEDED) {
10742                Slog.e(TAG, "Failed to copy package");
10743                return ret;
10744            }
10745
10746            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
10747            NativeLibraryHelper.Handle handle = null;
10748            try {
10749                handle = NativeLibraryHelper.Handle.create(codeFile);
10750                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
10751                        abiOverride);
10752            } catch (IOException e) {
10753                Slog.e(TAG, "Copying native libraries failed", e);
10754                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10755            } finally {
10756                IoUtils.closeQuietly(handle);
10757            }
10758
10759            return ret;
10760        }
10761
10762        int doPreInstall(int status) {
10763            if (status != PackageManager.INSTALL_SUCCEEDED) {
10764                cleanUp();
10765            }
10766            return status;
10767        }
10768
10769        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10770            if (status != PackageManager.INSTALL_SUCCEEDED) {
10771                cleanUp();
10772                return false;
10773            }
10774
10775            final File targetDir = codeFile.getParentFile();
10776            final File beforeCodeFile = codeFile;
10777            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
10778
10779            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
10780            try {
10781                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
10782            } catch (ErrnoException e) {
10783                Slog.w(TAG, "Failed to rename", e);
10784                return false;
10785            }
10786
10787            if (!SELinux.restoreconRecursive(afterCodeFile)) {
10788                Slog.w(TAG, "Failed to restorecon");
10789                return false;
10790            }
10791
10792            // Reflect the rename internally
10793            codeFile = afterCodeFile;
10794            resourceFile = afterCodeFile;
10795
10796            // Reflect the rename in scanned details
10797            pkg.codePath = afterCodeFile.getAbsolutePath();
10798            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10799                    pkg.baseCodePath);
10800            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10801                    pkg.splitCodePaths);
10802
10803            // Reflect the rename in app info
10804            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10805            pkg.applicationInfo.setCodePath(pkg.codePath);
10806            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10807            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10808            pkg.applicationInfo.setResourcePath(pkg.codePath);
10809            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10810            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10811
10812            return true;
10813        }
10814
10815        int doPostInstall(int status, int uid) {
10816            if (status != PackageManager.INSTALL_SUCCEEDED) {
10817                cleanUp();
10818            }
10819            return status;
10820        }
10821
10822        @Override
10823        String getCodePath() {
10824            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
10825        }
10826
10827        @Override
10828        String getResourcePath() {
10829            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
10830        }
10831
10832        private boolean cleanUp() {
10833            if (codeFile == null || !codeFile.exists()) {
10834                return false;
10835            }
10836
10837            if (codeFile.isDirectory()) {
10838                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
10839            } else {
10840                codeFile.delete();
10841            }
10842
10843            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
10844                resourceFile.delete();
10845            }
10846
10847            return true;
10848        }
10849
10850        void cleanUpResourcesLI() {
10851            // Try enumerating all code paths before deleting
10852            List<String> allCodePaths = Collections.EMPTY_LIST;
10853            if (codeFile != null && codeFile.exists()) {
10854                try {
10855                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
10856                    allCodePaths = pkg.getAllCodePaths();
10857                } catch (PackageParserException e) {
10858                    // Ignored; we tried our best
10859                }
10860            }
10861
10862            cleanUp();
10863            removeDexFiles(allCodePaths, instructionSets);
10864        }
10865
10866        boolean doPostDeleteLI(boolean delete) {
10867            // XXX err, shouldn't we respect the delete flag?
10868            cleanUpResourcesLI();
10869            return true;
10870        }
10871    }
10872
10873    private boolean isAsecExternal(String cid) {
10874        final String asecPath = PackageHelper.getSdFilesystem(cid);
10875        return !asecPath.startsWith(mAsecInternalPath);
10876    }
10877
10878    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
10879            PackageManagerException {
10880        if (copyRet < 0) {
10881            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
10882                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
10883                throw new PackageManagerException(copyRet, message);
10884            }
10885        }
10886    }
10887
10888    /**
10889     * Extract the MountService "container ID" from the full code path of an
10890     * .apk.
10891     */
10892    static String cidFromCodePath(String fullCodePath) {
10893        int eidx = fullCodePath.lastIndexOf("/");
10894        String subStr1 = fullCodePath.substring(0, eidx);
10895        int sidx = subStr1.lastIndexOf("/");
10896        return subStr1.substring(sidx+1, eidx);
10897    }
10898
10899    /**
10900     * Logic to handle installation of ASEC applications, including copying and
10901     * renaming logic.
10902     */
10903    class AsecInstallArgs extends InstallArgs {
10904        static final String RES_FILE_NAME = "pkg.apk";
10905        static final String PUBLIC_RES_FILE_NAME = "res.zip";
10906
10907        String cid;
10908        String packagePath;
10909        String resourcePath;
10910
10911        /** New install */
10912        AsecInstallArgs(InstallParams params) {
10913            super(params.origin, params.move, params.observer, params.installFlags,
10914                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10915                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10916        }
10917
10918        /** Existing install */
10919        AsecInstallArgs(String fullCodePath, String[] instructionSets,
10920                        boolean isExternal, boolean isForwardLocked) {
10921            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
10922                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
10923                    instructionSets, null);
10924            // Hackily pretend we're still looking at a full code path
10925            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
10926                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
10927            }
10928
10929            // Extract cid from fullCodePath
10930            int eidx = fullCodePath.lastIndexOf("/");
10931            String subStr1 = fullCodePath.substring(0, eidx);
10932            int sidx = subStr1.lastIndexOf("/");
10933            cid = subStr1.substring(sidx+1, eidx);
10934            setMountPath(subStr1);
10935        }
10936
10937        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
10938            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
10939                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
10940                    instructionSets, null);
10941            this.cid = cid;
10942            setMountPath(PackageHelper.getSdDir(cid));
10943        }
10944
10945        void createCopyFile() {
10946            cid = mInstallerService.allocateExternalStageCidLegacy();
10947        }
10948
10949        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10950            if (origin.staged) {
10951                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
10952                cid = origin.cid;
10953                setMountPath(PackageHelper.getSdDir(cid));
10954                return PackageManager.INSTALL_SUCCEEDED;
10955            }
10956
10957            if (temp) {
10958                createCopyFile();
10959            } else {
10960                /*
10961                 * Pre-emptively destroy the container since it's destroyed if
10962                 * copying fails due to it existing anyway.
10963                 */
10964                PackageHelper.destroySdDir(cid);
10965            }
10966
10967            final String newMountPath = imcs.copyPackageToContainer(
10968                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
10969                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
10970
10971            if (newMountPath != null) {
10972                setMountPath(newMountPath);
10973                return PackageManager.INSTALL_SUCCEEDED;
10974            } else {
10975                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10976            }
10977        }
10978
10979        @Override
10980        String getCodePath() {
10981            return packagePath;
10982        }
10983
10984        @Override
10985        String getResourcePath() {
10986            return resourcePath;
10987        }
10988
10989        int doPreInstall(int status) {
10990            if (status != PackageManager.INSTALL_SUCCEEDED) {
10991                // Destroy container
10992                PackageHelper.destroySdDir(cid);
10993            } else {
10994                boolean mounted = PackageHelper.isContainerMounted(cid);
10995                if (!mounted) {
10996                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
10997                            Process.SYSTEM_UID);
10998                    if (newMountPath != null) {
10999                        setMountPath(newMountPath);
11000                    } else {
11001                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11002                    }
11003                }
11004            }
11005            return status;
11006        }
11007
11008        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11009            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11010            String newMountPath = null;
11011            if (PackageHelper.isContainerMounted(cid)) {
11012                // Unmount the container
11013                if (!PackageHelper.unMountSdDir(cid)) {
11014                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11015                    return false;
11016                }
11017            }
11018            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11019                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11020                        " which might be stale. Will try to clean up.");
11021                // Clean up the stale container and proceed to recreate.
11022                if (!PackageHelper.destroySdDir(newCacheId)) {
11023                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11024                    return false;
11025                }
11026                // Successfully cleaned up stale container. Try to rename again.
11027                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11028                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11029                            + " inspite of cleaning it up.");
11030                    return false;
11031                }
11032            }
11033            if (!PackageHelper.isContainerMounted(newCacheId)) {
11034                Slog.w(TAG, "Mounting container " + newCacheId);
11035                newMountPath = PackageHelper.mountSdDir(newCacheId,
11036                        getEncryptKey(), Process.SYSTEM_UID);
11037            } else {
11038                newMountPath = PackageHelper.getSdDir(newCacheId);
11039            }
11040            if (newMountPath == null) {
11041                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11042                return false;
11043            }
11044            Log.i(TAG, "Succesfully renamed " + cid +
11045                    " to " + newCacheId +
11046                    " at new path: " + newMountPath);
11047            cid = newCacheId;
11048
11049            final File beforeCodeFile = new File(packagePath);
11050            setMountPath(newMountPath);
11051            final File afterCodeFile = new File(packagePath);
11052
11053            // Reflect the rename in scanned details
11054            pkg.codePath = afterCodeFile.getAbsolutePath();
11055            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11056                    pkg.baseCodePath);
11057            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11058                    pkg.splitCodePaths);
11059
11060            // Reflect the rename in app info
11061            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11062            pkg.applicationInfo.setCodePath(pkg.codePath);
11063            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11064            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11065            pkg.applicationInfo.setResourcePath(pkg.codePath);
11066            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11067            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11068
11069            return true;
11070        }
11071
11072        private void setMountPath(String mountPath) {
11073            final File mountFile = new File(mountPath);
11074
11075            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11076            if (monolithicFile.exists()) {
11077                packagePath = monolithicFile.getAbsolutePath();
11078                if (isFwdLocked()) {
11079                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11080                } else {
11081                    resourcePath = packagePath;
11082                }
11083            } else {
11084                packagePath = mountFile.getAbsolutePath();
11085                resourcePath = packagePath;
11086            }
11087        }
11088
11089        int doPostInstall(int status, int uid) {
11090            if (status != PackageManager.INSTALL_SUCCEEDED) {
11091                cleanUp();
11092            } else {
11093                final int groupOwner;
11094                final String protectedFile;
11095                if (isFwdLocked()) {
11096                    groupOwner = UserHandle.getSharedAppGid(uid);
11097                    protectedFile = RES_FILE_NAME;
11098                } else {
11099                    groupOwner = -1;
11100                    protectedFile = null;
11101                }
11102
11103                if (uid < Process.FIRST_APPLICATION_UID
11104                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11105                    Slog.e(TAG, "Failed to finalize " + cid);
11106                    PackageHelper.destroySdDir(cid);
11107                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11108                }
11109
11110                boolean mounted = PackageHelper.isContainerMounted(cid);
11111                if (!mounted) {
11112                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11113                }
11114            }
11115            return status;
11116        }
11117
11118        private void cleanUp() {
11119            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11120
11121            // Destroy secure container
11122            PackageHelper.destroySdDir(cid);
11123        }
11124
11125        private List<String> getAllCodePaths() {
11126            final File codeFile = new File(getCodePath());
11127            if (codeFile != null && codeFile.exists()) {
11128                try {
11129                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11130                    return pkg.getAllCodePaths();
11131                } catch (PackageParserException e) {
11132                    // Ignored; we tried our best
11133                }
11134            }
11135            return Collections.EMPTY_LIST;
11136        }
11137
11138        void cleanUpResourcesLI() {
11139            // Enumerate all code paths before deleting
11140            cleanUpResourcesLI(getAllCodePaths());
11141        }
11142
11143        private void cleanUpResourcesLI(List<String> allCodePaths) {
11144            cleanUp();
11145            removeDexFiles(allCodePaths, instructionSets);
11146        }
11147
11148        String getPackageName() {
11149            return getAsecPackageName(cid);
11150        }
11151
11152        boolean doPostDeleteLI(boolean delete) {
11153            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
11154            final List<String> allCodePaths = getAllCodePaths();
11155            boolean mounted = PackageHelper.isContainerMounted(cid);
11156            if (mounted) {
11157                // Unmount first
11158                if (PackageHelper.unMountSdDir(cid)) {
11159                    mounted = false;
11160                }
11161            }
11162            if (!mounted && delete) {
11163                cleanUpResourcesLI(allCodePaths);
11164            }
11165            return !mounted;
11166        }
11167
11168        @Override
11169        int doPreCopy() {
11170            if (isFwdLocked()) {
11171                if (!PackageHelper.fixSdPermissions(cid,
11172                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
11173                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11174                }
11175            }
11176
11177            return PackageManager.INSTALL_SUCCEEDED;
11178        }
11179
11180        @Override
11181        int doPostCopy(int uid) {
11182            if (isFwdLocked()) {
11183                if (uid < Process.FIRST_APPLICATION_UID
11184                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
11185                                RES_FILE_NAME)) {
11186                    Slog.e(TAG, "Failed to finalize " + cid);
11187                    PackageHelper.destroySdDir(cid);
11188                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11189                }
11190            }
11191
11192            return PackageManager.INSTALL_SUCCEEDED;
11193        }
11194    }
11195
11196    /**
11197     * Logic to handle movement of existing installed applications.
11198     */
11199    class MoveInstallArgs extends InstallArgs {
11200        private File codeFile;
11201        private File resourceFile;
11202
11203        /** New install */
11204        MoveInstallArgs(InstallParams params) {
11205            super(params.origin, params.move, params.observer, params.installFlags,
11206                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11207                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
11208        }
11209
11210        int copyApk(IMediaContainerService imcs, boolean temp) {
11211            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
11212                    + move.fromUuid + " to " + move.toUuid);
11213            synchronized (mInstaller) {
11214                if (mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
11215                        move.dataAppName, move.appId, move.seinfo) != 0) {
11216                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11217                }
11218            }
11219
11220            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
11221            resourceFile = codeFile;
11222            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
11223
11224            return PackageManager.INSTALL_SUCCEEDED;
11225        }
11226
11227        int doPreInstall(int status) {
11228            if (status != PackageManager.INSTALL_SUCCEEDED) {
11229                cleanUp();
11230            }
11231            return status;
11232        }
11233
11234        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11235            if (status != PackageManager.INSTALL_SUCCEEDED) {
11236                cleanUp();
11237                return false;
11238            }
11239
11240            // Reflect the move in app info
11241            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11242            pkg.applicationInfo.setCodePath(pkg.codePath);
11243            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11244            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11245            pkg.applicationInfo.setResourcePath(pkg.codePath);
11246            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11247            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11248
11249            return true;
11250        }
11251
11252        int doPostInstall(int status, int uid) {
11253            if (status != PackageManager.INSTALL_SUCCEEDED) {
11254                cleanUp();
11255            }
11256            return status;
11257        }
11258
11259        @Override
11260        String getCodePath() {
11261            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11262        }
11263
11264        @Override
11265        String getResourcePath() {
11266            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11267        }
11268
11269        private boolean cleanUp() {
11270            if (codeFile == null || !codeFile.exists()) {
11271                return false;
11272            }
11273
11274            if (codeFile.isDirectory()) {
11275                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11276            } else {
11277                codeFile.delete();
11278            }
11279
11280            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11281                resourceFile.delete();
11282            }
11283
11284            return true;
11285        }
11286
11287        void cleanUpResourcesLI() {
11288            cleanUp();
11289        }
11290
11291        boolean doPostDeleteLI(boolean delete) {
11292            // XXX err, shouldn't we respect the delete flag?
11293            cleanUpResourcesLI();
11294            return true;
11295        }
11296    }
11297
11298    static String getAsecPackageName(String packageCid) {
11299        int idx = packageCid.lastIndexOf("-");
11300        if (idx == -1) {
11301            return packageCid;
11302        }
11303        return packageCid.substring(0, idx);
11304    }
11305
11306    // Utility method used to create code paths based on package name and available index.
11307    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
11308        String idxStr = "";
11309        int idx = 1;
11310        // Fall back to default value of idx=1 if prefix is not
11311        // part of oldCodePath
11312        if (oldCodePath != null) {
11313            String subStr = oldCodePath;
11314            // Drop the suffix right away
11315            if (suffix != null && subStr.endsWith(suffix)) {
11316                subStr = subStr.substring(0, subStr.length() - suffix.length());
11317            }
11318            // If oldCodePath already contains prefix find out the
11319            // ending index to either increment or decrement.
11320            int sidx = subStr.lastIndexOf(prefix);
11321            if (sidx != -1) {
11322                subStr = subStr.substring(sidx + prefix.length());
11323                if (subStr != null) {
11324                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
11325                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
11326                    }
11327                    try {
11328                        idx = Integer.parseInt(subStr);
11329                        if (idx <= 1) {
11330                            idx++;
11331                        } else {
11332                            idx--;
11333                        }
11334                    } catch(NumberFormatException e) {
11335                    }
11336                }
11337            }
11338        }
11339        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
11340        return prefix + idxStr;
11341    }
11342
11343    private File getNextCodePath(File targetDir, String packageName) {
11344        int suffix = 1;
11345        File result;
11346        do {
11347            result = new File(targetDir, packageName + "-" + suffix);
11348            suffix++;
11349        } while (result.exists());
11350        return result;
11351    }
11352
11353    // Utility method that returns the relative package path with respect
11354    // to the installation directory. Like say for /data/data/com.test-1.apk
11355    // string com.test-1 is returned.
11356    static String deriveCodePathName(String codePath) {
11357        if (codePath == null) {
11358            return null;
11359        }
11360        final File codeFile = new File(codePath);
11361        final String name = codeFile.getName();
11362        if (codeFile.isDirectory()) {
11363            return name;
11364        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
11365            final int lastDot = name.lastIndexOf('.');
11366            return name.substring(0, lastDot);
11367        } else {
11368            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11369            return null;
11370        }
11371    }
11372
11373    class PackageInstalledInfo {
11374        String name;
11375        int uid;
11376        // The set of users that originally had this package installed.
11377        int[] origUsers;
11378        // The set of users that now have this package installed.
11379        int[] newUsers;
11380        PackageParser.Package pkg;
11381        int returnCode;
11382        String returnMsg;
11383        PackageRemovedInfo removedInfo;
11384
11385        public void setError(int code, String msg) {
11386            returnCode = code;
11387            returnMsg = msg;
11388            Slog.w(TAG, msg);
11389        }
11390
11391        public void setError(String msg, PackageParserException e) {
11392            returnCode = e.error;
11393            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11394            Slog.w(TAG, msg, e);
11395        }
11396
11397        public void setError(String msg, PackageManagerException e) {
11398            returnCode = e.error;
11399            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11400            Slog.w(TAG, msg, e);
11401        }
11402
11403        // In some error cases we want to convey more info back to the observer
11404        String origPackage;
11405        String origPermission;
11406    }
11407
11408    /*
11409     * Install a non-existing package.
11410     */
11411    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11412            UserHandle user, String installerPackageName, String volumeUuid,
11413            PackageInstalledInfo res) {
11414        // Remember this for later, in case we need to rollback this install
11415        String pkgName = pkg.packageName;
11416
11417        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
11418        final boolean dataDirExists = PackageManager.getDataDirForUser(volumeUuid, pkgName,
11419                UserHandle.USER_OWNER).exists();
11420        synchronized(mPackages) {
11421            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
11422                // A package with the same name is already installed, though
11423                // it has been renamed to an older name.  The package we
11424                // are trying to install should be installed as an update to
11425                // the existing one, but that has not been requested, so bail.
11426                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11427                        + " without first uninstalling package running as "
11428                        + mSettings.mRenamedPackages.get(pkgName));
11429                return;
11430            }
11431            if (mPackages.containsKey(pkgName)) {
11432                // Don't allow installation over an existing package with the same name.
11433                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11434                        + " without first uninstalling.");
11435                return;
11436            }
11437        }
11438
11439        try {
11440            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
11441                    System.currentTimeMillis(), user);
11442
11443            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
11444            // delete the partially installed application. the data directory will have to be
11445            // restored if it was already existing
11446            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11447                // remove package from internal structures.  Note that we want deletePackageX to
11448                // delete the package data and cache directories that it created in
11449                // scanPackageLocked, unless those directories existed before we even tried to
11450                // install.
11451                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
11452                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
11453                                res.removedInfo, true);
11454            }
11455
11456        } catch (PackageManagerException e) {
11457            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11458        }
11459    }
11460
11461    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
11462        // Can't rotate keys during boot or if sharedUser.
11463        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
11464                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
11465            return false;
11466        }
11467        // app is using upgradeKeySets; make sure all are valid
11468        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11469        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
11470        for (int i = 0; i < upgradeKeySets.length; i++) {
11471            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
11472                Slog.wtf(TAG, "Package "
11473                         + (oldPs.name != null ? oldPs.name : "<null>")
11474                         + " contains upgrade-key-set reference to unknown key-set: "
11475                         + upgradeKeySets[i]
11476                         + " reverting to signatures check.");
11477                return false;
11478            }
11479        }
11480        return true;
11481    }
11482
11483    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
11484        // Upgrade keysets are being used.  Determine if new package has a superset of the
11485        // required keys.
11486        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
11487        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11488        for (int i = 0; i < upgradeKeySets.length; i++) {
11489            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
11490            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
11491                return true;
11492            }
11493        }
11494        return false;
11495    }
11496
11497    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11498            UserHandle user, String installerPackageName, String volumeUuid,
11499            PackageInstalledInfo res) {
11500        final PackageParser.Package oldPackage;
11501        final String pkgName = pkg.packageName;
11502        final int[] allUsers;
11503        final boolean[] perUserInstalled;
11504        final boolean weFroze;
11505
11506        // First find the old package info and check signatures
11507        synchronized(mPackages) {
11508            oldPackage = mPackages.get(pkgName);
11509            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
11510            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11511            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11512                if(!checkUpgradeKeySetLP(ps, pkg)) {
11513                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11514                            "New package not signed by keys specified by upgrade-keysets: "
11515                            + pkgName);
11516                    return;
11517                }
11518            } else {
11519                // default to original signature matching
11520                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
11521                    != PackageManager.SIGNATURE_MATCH) {
11522                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11523                            "New package has a different signature: " + pkgName);
11524                    return;
11525                }
11526            }
11527
11528            // In case of rollback, remember per-user/profile install state
11529            allUsers = sUserManager.getUserIds();
11530            perUserInstalled = new boolean[allUsers.length];
11531            for (int i = 0; i < allUsers.length; i++) {
11532                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11533            }
11534
11535            // Mark the app as frozen to prevent launching during the upgrade
11536            // process, and then kill all running instances
11537            if (!ps.frozen) {
11538                ps.frozen = true;
11539                weFroze = true;
11540            } else {
11541                weFroze = false;
11542            }
11543        }
11544
11545        // Now that we're guarded by frozen state, kill app during upgrade
11546        killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg");
11547
11548        try {
11549            boolean sysPkg = (isSystemApp(oldPackage));
11550            if (sysPkg) {
11551                replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11552                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11553            } else {
11554                replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11555                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11556            }
11557        } finally {
11558            // Regardless of success or failure of upgrade steps above, always
11559            // unfreeze the package if we froze it
11560            if (weFroze) {
11561                unfreezePackage(pkgName);
11562            }
11563        }
11564    }
11565
11566    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
11567            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11568            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11569            String volumeUuid, PackageInstalledInfo res) {
11570        String pkgName = deletedPackage.packageName;
11571        boolean deletedPkg = true;
11572        boolean updatedSettings = false;
11573
11574        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
11575                + deletedPackage);
11576        long origUpdateTime;
11577        if (pkg.mExtras != null) {
11578            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
11579        } else {
11580            origUpdateTime = 0;
11581        }
11582
11583        // First delete the existing package while retaining the data directory
11584        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
11585                res.removedInfo, true)) {
11586            // If the existing package wasn't successfully deleted
11587            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
11588            deletedPkg = false;
11589        } else {
11590            // Successfully deleted the old package; proceed with replace.
11591
11592            // If deleted package lived in a container, give users a chance to
11593            // relinquish resources before killing.
11594            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
11595                if (DEBUG_INSTALL) {
11596                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
11597                }
11598                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
11599                final ArrayList<String> pkgList = new ArrayList<String>(1);
11600                pkgList.add(deletedPackage.applicationInfo.packageName);
11601                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
11602            }
11603
11604            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
11605            try {
11606                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
11607                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
11608                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11609                        perUserInstalled, res, user);
11610                updatedSettings = true;
11611            } catch (PackageManagerException e) {
11612                res.setError("Package couldn't be installed in " + pkg.codePath, e);
11613            }
11614        }
11615
11616        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11617            // remove package from internal structures.  Note that we want deletePackageX to
11618            // delete the package data and cache directories that it created in
11619            // scanPackageLocked, unless those directories existed before we even tried to
11620            // install.
11621            if(updatedSettings) {
11622                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
11623                deletePackageLI(
11624                        pkgName, null, true, allUsers, perUserInstalled,
11625                        PackageManager.DELETE_KEEP_DATA,
11626                                res.removedInfo, true);
11627            }
11628            // Since we failed to install the new package we need to restore the old
11629            // package that we deleted.
11630            if (deletedPkg) {
11631                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
11632                File restoreFile = new File(deletedPackage.codePath);
11633                // Parse old package
11634                boolean oldExternal = isExternal(deletedPackage);
11635                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
11636                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
11637                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11638                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
11639                try {
11640                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
11641                } catch (PackageManagerException e) {
11642                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
11643                            + e.getMessage());
11644                    return;
11645                }
11646                // Restore of old package succeeded. Update permissions.
11647                // writer
11648                synchronized (mPackages) {
11649                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
11650                            UPDATE_PERMISSIONS_ALL);
11651                    // can downgrade to reader
11652                    mSettings.writeLPr();
11653                }
11654                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
11655            }
11656        }
11657    }
11658
11659    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
11660            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11661            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11662            String volumeUuid, PackageInstalledInfo res) {
11663        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
11664                + ", old=" + deletedPackage);
11665        boolean disabledSystem = false;
11666        boolean updatedSettings = false;
11667        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
11668        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
11669                != 0) {
11670            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11671        }
11672        String packageName = deletedPackage.packageName;
11673        if (packageName == null) {
11674            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11675                    "Attempt to delete null packageName.");
11676            return;
11677        }
11678        PackageParser.Package oldPkg;
11679        PackageSetting oldPkgSetting;
11680        // reader
11681        synchronized (mPackages) {
11682            oldPkg = mPackages.get(packageName);
11683            oldPkgSetting = mSettings.mPackages.get(packageName);
11684            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
11685                    (oldPkgSetting == null)) {
11686                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11687                        "Couldn't find package:" + packageName + " information");
11688                return;
11689            }
11690        }
11691
11692        res.removedInfo.uid = oldPkg.applicationInfo.uid;
11693        res.removedInfo.removedPackage = packageName;
11694        // Remove existing system package
11695        removePackageLI(oldPkgSetting, true);
11696        // writer
11697        synchronized (mPackages) {
11698            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
11699            if (!disabledSystem && deletedPackage != null) {
11700                // We didn't need to disable the .apk as a current system package,
11701                // which means we are replacing another update that is already
11702                // installed.  We need to make sure to delete the older one's .apk.
11703                res.removedInfo.args = createInstallArgsForExisting(0,
11704                        deletedPackage.applicationInfo.getCodePath(),
11705                        deletedPackage.applicationInfo.getResourcePath(),
11706                        getAppDexInstructionSets(deletedPackage.applicationInfo));
11707            } else {
11708                res.removedInfo.args = null;
11709            }
11710        }
11711
11712        // Successfully disabled the old package. Now proceed with re-installation
11713        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
11714
11715        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11716        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
11717
11718        PackageParser.Package newPackage = null;
11719        try {
11720            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
11721            if (newPackage.mExtras != null) {
11722                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
11723                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
11724                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
11725
11726                // is the update attempting to change shared user? that isn't going to work...
11727                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
11728                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
11729                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
11730                            + " to " + newPkgSetting.sharedUser);
11731                    updatedSettings = true;
11732                }
11733            }
11734
11735            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11736                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11737                        perUserInstalled, res, user);
11738                updatedSettings = true;
11739            }
11740
11741        } catch (PackageManagerException e) {
11742            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11743        }
11744
11745        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11746            // Re installation failed. Restore old information
11747            // Remove new pkg information
11748            if (newPackage != null) {
11749                removeInstalledPackageLI(newPackage, true);
11750            }
11751            // Add back the old system package
11752            try {
11753                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
11754            } catch (PackageManagerException e) {
11755                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
11756            }
11757            // Restore the old system information in Settings
11758            synchronized (mPackages) {
11759                if (disabledSystem) {
11760                    mSettings.enableSystemPackageLPw(packageName);
11761                }
11762                if (updatedSettings) {
11763                    mSettings.setInstallerPackageName(packageName,
11764                            oldPkgSetting.installerPackageName);
11765                }
11766                mSettings.writeLPr();
11767            }
11768        }
11769    }
11770
11771    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
11772            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
11773            UserHandle user) {
11774        String pkgName = newPackage.packageName;
11775        synchronized (mPackages) {
11776            //write settings. the installStatus will be incomplete at this stage.
11777            //note that the new package setting would have already been
11778            //added to mPackages. It hasn't been persisted yet.
11779            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
11780            mSettings.writeLPr();
11781        }
11782
11783        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
11784
11785        synchronized (mPackages) {
11786            updatePermissionsLPw(newPackage.packageName, newPackage,
11787                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
11788                            ? UPDATE_PERMISSIONS_ALL : 0));
11789            // For system-bundled packages, we assume that installing an upgraded version
11790            // of the package implies that the user actually wants to run that new code,
11791            // so we enable the package.
11792            PackageSetting ps = mSettings.mPackages.get(pkgName);
11793            if (ps != null) {
11794                if (isSystemApp(newPackage)) {
11795                    // NB: implicit assumption that system package upgrades apply to all users
11796                    if (DEBUG_INSTALL) {
11797                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
11798                    }
11799                    if (res.origUsers != null) {
11800                        for (int userHandle : res.origUsers) {
11801                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
11802                                    userHandle, installerPackageName);
11803                        }
11804                    }
11805                    // Also convey the prior install/uninstall state
11806                    if (allUsers != null && perUserInstalled != null) {
11807                        for (int i = 0; i < allUsers.length; i++) {
11808                            if (DEBUG_INSTALL) {
11809                                Slog.d(TAG, "    user " + allUsers[i]
11810                                        + " => " + perUserInstalled[i]);
11811                            }
11812                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
11813                        }
11814                        // these install state changes will be persisted in the
11815                        // upcoming call to mSettings.writeLPr().
11816                    }
11817                }
11818                // It's implied that when a user requests installation, they want the app to be
11819                // installed and enabled.
11820                int userId = user.getIdentifier();
11821                if (userId != UserHandle.USER_ALL) {
11822                    ps.setInstalled(true, userId);
11823                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
11824                }
11825            }
11826            res.name = pkgName;
11827            res.uid = newPackage.applicationInfo.uid;
11828            res.pkg = newPackage;
11829            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
11830            mSettings.setInstallerPackageName(pkgName, installerPackageName);
11831            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11832            //to update install status
11833            mSettings.writeLPr();
11834        }
11835    }
11836
11837    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
11838        final int installFlags = args.installFlags;
11839        final String installerPackageName = args.installerPackageName;
11840        final String volumeUuid = args.volumeUuid;
11841        final File tmpPackageFile = new File(args.getCodePath());
11842        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
11843        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
11844                || (args.volumeUuid != null));
11845        boolean replace = false;
11846        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
11847        if (args.move != null) {
11848            // moving a complete application; perfom an initial scan on the new install location
11849            scanFlags |= SCAN_INITIAL;
11850        }
11851        // Result object to be returned
11852        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11853
11854        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
11855        // Retrieve PackageSettings and parse package
11856        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
11857                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
11858                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11859        PackageParser pp = new PackageParser();
11860        pp.setSeparateProcesses(mSeparateProcesses);
11861        pp.setDisplayMetrics(mMetrics);
11862
11863        final PackageParser.Package pkg;
11864        try {
11865            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
11866        } catch (PackageParserException e) {
11867            res.setError("Failed parse during installPackageLI", e);
11868            return;
11869        }
11870
11871        // Mark that we have an install time CPU ABI override.
11872        pkg.cpuAbiOverride = args.abiOverride;
11873
11874        String pkgName = res.name = pkg.packageName;
11875        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
11876            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
11877                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
11878                return;
11879            }
11880        }
11881
11882        try {
11883            pp.collectCertificates(pkg, parseFlags);
11884            pp.collectManifestDigest(pkg);
11885        } catch (PackageParserException e) {
11886            res.setError("Failed collect during installPackageLI", e);
11887            return;
11888        }
11889
11890        /* If the installer passed in a manifest digest, compare it now. */
11891        if (args.manifestDigest != null) {
11892            if (DEBUG_INSTALL) {
11893                final String parsedManifest = pkg.manifestDigest == null ? "null"
11894                        : pkg.manifestDigest.toString();
11895                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
11896                        + parsedManifest);
11897            }
11898
11899            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
11900                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
11901                return;
11902            }
11903        } else if (DEBUG_INSTALL) {
11904            final String parsedManifest = pkg.manifestDigest == null
11905                    ? "null" : pkg.manifestDigest.toString();
11906            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
11907        }
11908
11909        // Get rid of all references to package scan path via parser.
11910        pp = null;
11911        String oldCodePath = null;
11912        boolean systemApp = false;
11913        synchronized (mPackages) {
11914            // Check if installing already existing package
11915            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
11916                String oldName = mSettings.mRenamedPackages.get(pkgName);
11917                if (pkg.mOriginalPackages != null
11918                        && pkg.mOriginalPackages.contains(oldName)
11919                        && mPackages.containsKey(oldName)) {
11920                    // This package is derived from an original package,
11921                    // and this device has been updating from that original
11922                    // name.  We must continue using the original name, so
11923                    // rename the new package here.
11924                    pkg.setPackageName(oldName);
11925                    pkgName = pkg.packageName;
11926                    replace = true;
11927                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
11928                            + oldName + " pkgName=" + pkgName);
11929                } else if (mPackages.containsKey(pkgName)) {
11930                    // This package, under its official name, already exists
11931                    // on the device; we should replace it.
11932                    replace = true;
11933                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
11934                }
11935
11936                // Prevent apps opting out from runtime permissions
11937                if (replace) {
11938                    PackageParser.Package oldPackage = mPackages.get(pkgName);
11939                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
11940                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
11941                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
11942                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
11943                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
11944                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
11945                                        + " doesn't support runtime permissions but the old"
11946                                        + " target SDK " + oldTargetSdk + " does.");
11947                        return;
11948                    }
11949                }
11950            }
11951
11952            PackageSetting ps = mSettings.mPackages.get(pkgName);
11953            if (ps != null) {
11954                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
11955
11956                // Quick sanity check that we're signed correctly if updating;
11957                // we'll check this again later when scanning, but we want to
11958                // bail early here before tripping over redefined permissions.
11959                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11960                    if (!checkUpgradeKeySetLP(ps, pkg)) {
11961                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
11962                                + pkg.packageName + " upgrade keys do not match the "
11963                                + "previously installed version");
11964                        return;
11965                    }
11966                } else {
11967                    try {
11968                        verifySignaturesLP(ps, pkg);
11969                    } catch (PackageManagerException e) {
11970                        res.setError(e.error, e.getMessage());
11971                        return;
11972                    }
11973                }
11974
11975                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
11976                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
11977                    systemApp = (ps.pkg.applicationInfo.flags &
11978                            ApplicationInfo.FLAG_SYSTEM) != 0;
11979                }
11980                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
11981            }
11982
11983            // Check whether the newly-scanned package wants to define an already-defined perm
11984            int N = pkg.permissions.size();
11985            for (int i = N-1; i >= 0; i--) {
11986                PackageParser.Permission perm = pkg.permissions.get(i);
11987                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
11988                if (bp != null) {
11989                    // If the defining package is signed with our cert, it's okay.  This
11990                    // also includes the "updating the same package" case, of course.
11991                    // "updating same package" could also involve key-rotation.
11992                    final boolean sigsOk;
11993                    if (bp.sourcePackage.equals(pkg.packageName)
11994                            && (bp.packageSetting instanceof PackageSetting)
11995                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
11996                                    scanFlags))) {
11997                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
11998                    } else {
11999                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12000                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12001                    }
12002                    if (!sigsOk) {
12003                        // If the owning package is the system itself, we log but allow
12004                        // install to proceed; we fail the install on all other permission
12005                        // redefinitions.
12006                        if (!bp.sourcePackage.equals("android")) {
12007                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12008                                    + pkg.packageName + " attempting to redeclare permission "
12009                                    + perm.info.name + " already owned by " + bp.sourcePackage);
12010                            res.origPermission = perm.info.name;
12011                            res.origPackage = bp.sourcePackage;
12012                            return;
12013                        } else {
12014                            Slog.w(TAG, "Package " + pkg.packageName
12015                                    + " attempting to redeclare system permission "
12016                                    + perm.info.name + "; ignoring new declaration");
12017                            pkg.permissions.remove(i);
12018                        }
12019                    }
12020                }
12021            }
12022
12023        }
12024
12025        if (systemApp && onExternal) {
12026            // Disable updates to system apps on sdcard
12027            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12028                    "Cannot install updates to system apps on sdcard");
12029            return;
12030        }
12031
12032        if (args.move != null) {
12033            // We did an in-place move, so dex is ready to roll
12034            scanFlags |= SCAN_NO_DEX;
12035            scanFlags |= SCAN_MOVE;
12036        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
12037            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
12038            scanFlags |= SCAN_NO_DEX;
12039
12040            try {
12041                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
12042                        true /* extract libs */);
12043            } catch (PackageManagerException pme) {
12044                Slog.e(TAG, "Error deriving application ABI", pme);
12045                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
12046                return;
12047            }
12048
12049            // Run dexopt before old package gets removed, to minimize time when app is unavailable
12050            int result = mPackageDexOptimizer
12051                    .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */,
12052                            false /* defer */, false /* inclDependencies */);
12053            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
12054                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
12055                return;
12056            }
12057        }
12058
12059        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
12060            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
12061            return;
12062        }
12063
12064        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
12065
12066        if (replace) {
12067            replacePackageLI(pkg, parseFlags, scanFlags, args.user,
12068                    installerPackageName, volumeUuid, res);
12069        } else {
12070            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
12071                    args.user, installerPackageName, volumeUuid, res);
12072        }
12073        synchronized (mPackages) {
12074            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12075            if (ps != null) {
12076                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12077            }
12078        }
12079    }
12080
12081    private void startIntentFilterVerifications(int userId, boolean replacing,
12082            PackageParser.Package pkg) {
12083        if (mIntentFilterVerifierComponent == null) {
12084            Slog.w(TAG, "No IntentFilter verification will not be done as "
12085                    + "there is no IntentFilterVerifier available!");
12086            return;
12087        }
12088
12089        final int verifierUid = getPackageUid(
12090                mIntentFilterVerifierComponent.getPackageName(),
12091                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
12092
12093        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
12094        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
12095        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
12096        mHandler.sendMessage(msg);
12097    }
12098
12099    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
12100            PackageParser.Package pkg) {
12101        int size = pkg.activities.size();
12102        if (size == 0) {
12103            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12104                    "No activity, so no need to verify any IntentFilter!");
12105            return;
12106        }
12107
12108        final boolean hasDomainURLs = hasDomainURLs(pkg);
12109        if (!hasDomainURLs) {
12110            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12111                    "No domain URLs, so no need to verify any IntentFilter!");
12112            return;
12113        }
12114
12115        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
12116                + " if any IntentFilter from the " + size
12117                + " Activities needs verification ...");
12118
12119        int count = 0;
12120        final String packageName = pkg.packageName;
12121
12122        synchronized (mPackages) {
12123            // If this is a new install and we see that we've already run verification for this
12124            // package, we have nothing to do: it means the state was restored from backup.
12125            if (!replacing) {
12126                IntentFilterVerificationInfo ivi =
12127                        mSettings.getIntentFilterVerificationLPr(packageName);
12128                if (ivi != null) {
12129                    if (DEBUG_DOMAIN_VERIFICATION) {
12130                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
12131                                + ivi.getStatusString());
12132                    }
12133                    return;
12134                }
12135            }
12136
12137            // If any filters need to be verified, then all need to be.
12138            boolean needToVerify = false;
12139            for (PackageParser.Activity a : pkg.activities) {
12140                for (ActivityIntentInfo filter : a.intents) {
12141                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
12142                        if (DEBUG_DOMAIN_VERIFICATION) {
12143                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
12144                        }
12145                        needToVerify = true;
12146                        break;
12147                    }
12148                }
12149            }
12150
12151            if (needToVerify) {
12152                final int verificationId = mIntentFilterVerificationToken++;
12153                for (PackageParser.Activity a : pkg.activities) {
12154                    for (ActivityIntentInfo filter : a.intents) {
12155                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
12156                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12157                                    "Verification needed for IntentFilter:" + filter.toString());
12158                            mIntentFilterVerifier.addOneIntentFilterVerification(
12159                                    verifierUid, userId, verificationId, filter, packageName);
12160                            count++;
12161                        }
12162                    }
12163                }
12164            }
12165        }
12166
12167        if (count > 0) {
12168            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
12169                    + " IntentFilter verification" + (count > 1 ? "s" : "")
12170                    +  " for userId:" + userId);
12171            mIntentFilterVerifier.startVerifications(userId);
12172        } else {
12173            if (DEBUG_DOMAIN_VERIFICATION) {
12174                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
12175            }
12176        }
12177    }
12178
12179    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
12180        final ComponentName cn  = filter.activity.getComponentName();
12181        final String packageName = cn.getPackageName();
12182
12183        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
12184                packageName);
12185        if (ivi == null) {
12186            return true;
12187        }
12188        int status = ivi.getStatus();
12189        switch (status) {
12190            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
12191            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
12192                return true;
12193
12194            default:
12195                // Nothing to do
12196                return false;
12197        }
12198    }
12199
12200    private static boolean isMultiArch(PackageSetting ps) {
12201        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12202    }
12203
12204    private static boolean isMultiArch(ApplicationInfo info) {
12205        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12206    }
12207
12208    private static boolean isExternal(PackageParser.Package pkg) {
12209        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12210    }
12211
12212    private static boolean isExternal(PackageSetting ps) {
12213        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12214    }
12215
12216    private static boolean isExternal(ApplicationInfo info) {
12217        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12218    }
12219
12220    private static boolean isSystemApp(PackageParser.Package pkg) {
12221        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
12222    }
12223
12224    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
12225        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
12226    }
12227
12228    private static boolean hasDomainURLs(PackageParser.Package pkg) {
12229        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
12230    }
12231
12232    private static boolean isSystemApp(PackageSetting ps) {
12233        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
12234    }
12235
12236    private static boolean isUpdatedSystemApp(PackageSetting ps) {
12237        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
12238    }
12239
12240    private int packageFlagsToInstallFlags(PackageSetting ps) {
12241        int installFlags = 0;
12242        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
12243            // This existing package was an external ASEC install when we have
12244            // the external flag without a UUID
12245            installFlags |= PackageManager.INSTALL_EXTERNAL;
12246        }
12247        if (ps.isForwardLocked()) {
12248            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12249        }
12250        return installFlags;
12251    }
12252
12253    private void deleteTempPackageFiles() {
12254        final FilenameFilter filter = new FilenameFilter() {
12255            public boolean accept(File dir, String name) {
12256                return name.startsWith("vmdl") && name.endsWith(".tmp");
12257            }
12258        };
12259        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
12260            file.delete();
12261        }
12262    }
12263
12264    @Override
12265    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
12266            int flags) {
12267        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
12268                flags);
12269    }
12270
12271    @Override
12272    public void deletePackage(final String packageName,
12273            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
12274        mContext.enforceCallingOrSelfPermission(
12275                android.Manifest.permission.DELETE_PACKAGES, null);
12276        final int uid = Binder.getCallingUid();
12277        if (UserHandle.getUserId(uid) != userId) {
12278            mContext.enforceCallingPermission(
12279                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
12280                    "deletePackage for user " + userId);
12281        }
12282        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
12283            try {
12284                observer.onPackageDeleted(packageName,
12285                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
12286            } catch (RemoteException re) {
12287            }
12288            return;
12289        }
12290
12291        boolean uninstallBlocked = false;
12292        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
12293            int[] users = sUserManager.getUserIds();
12294            for (int i = 0; i < users.length; ++i) {
12295                if (getBlockUninstallForUser(packageName, users[i])) {
12296                    uninstallBlocked = true;
12297                    break;
12298                }
12299            }
12300        } else {
12301            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
12302        }
12303        if (uninstallBlocked) {
12304            try {
12305                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
12306                        null);
12307            } catch (RemoteException re) {
12308            }
12309            return;
12310        }
12311
12312        if (DEBUG_REMOVE) {
12313            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
12314        }
12315        // Queue up an async operation since the package deletion may take a little while.
12316        mHandler.post(new Runnable() {
12317            public void run() {
12318                mHandler.removeCallbacks(this);
12319                final int returnCode = deletePackageX(packageName, userId, flags);
12320                if (observer != null) {
12321                    try {
12322                        observer.onPackageDeleted(packageName, returnCode, null);
12323                    } catch (RemoteException e) {
12324                        Log.i(TAG, "Observer no longer exists.");
12325                    } //end catch
12326                } //end if
12327            } //end run
12328        });
12329    }
12330
12331    private boolean isPackageDeviceAdmin(String packageName, int userId) {
12332        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12333                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12334        try {
12335            if (dpm != null) {
12336                if (dpm.isDeviceOwner(packageName)) {
12337                    return true;
12338                }
12339                int[] users;
12340                if (userId == UserHandle.USER_ALL) {
12341                    users = sUserManager.getUserIds();
12342                } else {
12343                    users = new int[]{userId};
12344                }
12345                for (int i = 0; i < users.length; ++i) {
12346                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
12347                        return true;
12348                    }
12349                }
12350            }
12351        } catch (RemoteException e) {
12352        }
12353        return false;
12354    }
12355
12356    /**
12357     *  This method is an internal method that could be get invoked either
12358     *  to delete an installed package or to clean up a failed installation.
12359     *  After deleting an installed package, a broadcast is sent to notify any
12360     *  listeners that the package has been installed. For cleaning up a failed
12361     *  installation, the broadcast is not necessary since the package's
12362     *  installation wouldn't have sent the initial broadcast either
12363     *  The key steps in deleting a package are
12364     *  deleting the package information in internal structures like mPackages,
12365     *  deleting the packages base directories through installd
12366     *  updating mSettings to reflect current status
12367     *  persisting settings for later use
12368     *  sending a broadcast if necessary
12369     */
12370    private int deletePackageX(String packageName, int userId, int flags) {
12371        final PackageRemovedInfo info = new PackageRemovedInfo();
12372        final boolean res;
12373
12374        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
12375                ? UserHandle.ALL : new UserHandle(userId);
12376
12377        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
12378            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
12379            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
12380        }
12381
12382        boolean removedForAllUsers = false;
12383        boolean systemUpdate = false;
12384
12385        // for the uninstall-updates case and restricted profiles, remember the per-
12386        // userhandle installed state
12387        int[] allUsers;
12388        boolean[] perUserInstalled;
12389        synchronized (mPackages) {
12390            PackageSetting ps = mSettings.mPackages.get(packageName);
12391            allUsers = sUserManager.getUserIds();
12392            perUserInstalled = new boolean[allUsers.length];
12393            for (int i = 0; i < allUsers.length; i++) {
12394                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12395            }
12396        }
12397
12398        synchronized (mInstallLock) {
12399            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
12400            res = deletePackageLI(packageName, removeForUser,
12401                    true, allUsers, perUserInstalled,
12402                    flags | REMOVE_CHATTY, info, true);
12403            systemUpdate = info.isRemovedPackageSystemUpdate;
12404            if (res && !systemUpdate && mPackages.get(packageName) == null) {
12405                removedForAllUsers = true;
12406            }
12407            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
12408                    + " removedForAllUsers=" + removedForAllUsers);
12409        }
12410
12411        if (res) {
12412            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
12413
12414            // If the removed package was a system update, the old system package
12415            // was re-enabled; we need to broadcast this information
12416            if (systemUpdate) {
12417                Bundle extras = new Bundle(1);
12418                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
12419                        ? info.removedAppId : info.uid);
12420                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12421
12422                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
12423                        extras, null, null, null);
12424                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
12425                        extras, null, null, null);
12426                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
12427                        null, packageName, null, null);
12428            }
12429        }
12430        // Force a gc here.
12431        Runtime.getRuntime().gc();
12432        // Delete the resources here after sending the broadcast to let
12433        // other processes clean up before deleting resources.
12434        if (info.args != null) {
12435            synchronized (mInstallLock) {
12436                info.args.doPostDeleteLI(true);
12437            }
12438        }
12439
12440        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
12441    }
12442
12443    class PackageRemovedInfo {
12444        String removedPackage;
12445        int uid = -1;
12446        int removedAppId = -1;
12447        int[] removedUsers = null;
12448        boolean isRemovedPackageSystemUpdate = false;
12449        // Clean up resources deleted packages.
12450        InstallArgs args = null;
12451
12452        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
12453            Bundle extras = new Bundle(1);
12454            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
12455            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
12456            if (replacing) {
12457                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12458            }
12459            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
12460            if (removedPackage != null) {
12461                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
12462                        extras, null, null, removedUsers);
12463                if (fullRemove && !replacing) {
12464                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
12465                            extras, null, null, removedUsers);
12466                }
12467            }
12468            if (removedAppId >= 0) {
12469                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
12470                        removedUsers);
12471            }
12472        }
12473    }
12474
12475    /*
12476     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
12477     * flag is not set, the data directory is removed as well.
12478     * make sure this flag is set for partially installed apps. If not its meaningless to
12479     * delete a partially installed application.
12480     */
12481    private void removePackageDataLI(PackageSetting ps,
12482            int[] allUserHandles, boolean[] perUserInstalled,
12483            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
12484        String packageName = ps.name;
12485        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
12486        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
12487        // Retrieve object to delete permissions for shared user later on
12488        final PackageSetting deletedPs;
12489        // reader
12490        synchronized (mPackages) {
12491            deletedPs = mSettings.mPackages.get(packageName);
12492            if (outInfo != null) {
12493                outInfo.removedPackage = packageName;
12494                outInfo.removedUsers = deletedPs != null
12495                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
12496                        : null;
12497            }
12498        }
12499        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12500            removeDataDirsLI(ps.volumeUuid, packageName);
12501            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
12502        }
12503        // writer
12504        synchronized (mPackages) {
12505            if (deletedPs != null) {
12506                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12507                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
12508                    clearDefaultBrowserIfNeeded(packageName);
12509                    if (outInfo != null) {
12510                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
12511                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
12512                    }
12513                    updatePermissionsLPw(deletedPs.name, null, 0);
12514                    if (deletedPs.sharedUser != null) {
12515                        // Remove permissions associated with package. Since runtime
12516                        // permissions are per user we have to kill the removed package
12517                        // or packages running under the shared user of the removed
12518                        // package if revoking the permissions requested only by the removed
12519                        // package is successful and this causes a change in gids.
12520                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12521                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
12522                                    userId);
12523                            if (userIdToKill == UserHandle.USER_ALL
12524                                    || userIdToKill >= UserHandle.USER_OWNER) {
12525                                // If gids changed for this user, kill all affected packages.
12526                                mHandler.post(new Runnable() {
12527                                    @Override
12528                                    public void run() {
12529                                        // This has to happen with no lock held.
12530                                        killSettingPackagesForUser(deletedPs, userIdToKill,
12531                                                KILL_APP_REASON_GIDS_CHANGED);
12532                                    }
12533                                });
12534                            break;
12535                            }
12536                        }
12537                    }
12538                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
12539                }
12540                // make sure to preserve per-user disabled state if this removal was just
12541                // a downgrade of a system app to the factory package
12542                if (allUserHandles != null && perUserInstalled != null) {
12543                    if (DEBUG_REMOVE) {
12544                        Slog.d(TAG, "Propagating install state across downgrade");
12545                    }
12546                    for (int i = 0; i < allUserHandles.length; i++) {
12547                        if (DEBUG_REMOVE) {
12548                            Slog.d(TAG, "    user " + allUserHandles[i]
12549                                    + " => " + perUserInstalled[i]);
12550                        }
12551                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12552                    }
12553                }
12554            }
12555            // can downgrade to reader
12556            if (writeSettings) {
12557                // Save settings now
12558                mSettings.writeLPr();
12559            }
12560        }
12561        if (outInfo != null) {
12562            // A user ID was deleted here. Go through all users and remove it
12563            // from KeyStore.
12564            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
12565        }
12566    }
12567
12568    static boolean locationIsPrivileged(File path) {
12569        try {
12570            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
12571                    .getCanonicalPath();
12572            return path.getCanonicalPath().startsWith(privilegedAppDir);
12573        } catch (IOException e) {
12574            Slog.e(TAG, "Unable to access code path " + path);
12575        }
12576        return false;
12577    }
12578
12579    /*
12580     * Tries to delete system package.
12581     */
12582    private boolean deleteSystemPackageLI(PackageSetting newPs,
12583            int[] allUserHandles, boolean[] perUserInstalled,
12584            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
12585        final boolean applyUserRestrictions
12586                = (allUserHandles != null) && (perUserInstalled != null);
12587        PackageSetting disabledPs = null;
12588        // Confirm if the system package has been updated
12589        // An updated system app can be deleted. This will also have to restore
12590        // the system pkg from system partition
12591        // reader
12592        synchronized (mPackages) {
12593            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
12594        }
12595        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
12596                + " disabledPs=" + disabledPs);
12597        if (disabledPs == null) {
12598            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
12599            return false;
12600        } else if (DEBUG_REMOVE) {
12601            Slog.d(TAG, "Deleting system pkg from data partition");
12602        }
12603        if (DEBUG_REMOVE) {
12604            if (applyUserRestrictions) {
12605                Slog.d(TAG, "Remembering install states:");
12606                for (int i = 0; i < allUserHandles.length; i++) {
12607                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
12608                }
12609            }
12610        }
12611        // Delete the updated package
12612        outInfo.isRemovedPackageSystemUpdate = true;
12613        if (disabledPs.versionCode < newPs.versionCode) {
12614            // Delete data for downgrades
12615            flags &= ~PackageManager.DELETE_KEEP_DATA;
12616        } else {
12617            // Preserve data by setting flag
12618            flags |= PackageManager.DELETE_KEEP_DATA;
12619        }
12620        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
12621                allUserHandles, perUserInstalled, outInfo, writeSettings);
12622        if (!ret) {
12623            return false;
12624        }
12625        // writer
12626        synchronized (mPackages) {
12627            // Reinstate the old system package
12628            mSettings.enableSystemPackageLPw(newPs.name);
12629            // Remove any native libraries from the upgraded package.
12630            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
12631        }
12632        // Install the system package
12633        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
12634        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
12635        if (locationIsPrivileged(disabledPs.codePath)) {
12636            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12637        }
12638
12639        final PackageParser.Package newPkg;
12640        try {
12641            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
12642        } catch (PackageManagerException e) {
12643            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
12644            return false;
12645        }
12646
12647        // writer
12648        synchronized (mPackages) {
12649            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
12650            updatePermissionsLPw(newPkg.packageName, newPkg,
12651                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
12652            if (applyUserRestrictions) {
12653                if (DEBUG_REMOVE) {
12654                    Slog.d(TAG, "Propagating install state across reinstall");
12655                }
12656                for (int i = 0; i < allUserHandles.length; i++) {
12657                    if (DEBUG_REMOVE) {
12658                        Slog.d(TAG, "    user " + allUserHandles[i]
12659                                + " => " + perUserInstalled[i]);
12660                    }
12661                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12662                }
12663                // Regardless of writeSettings we need to ensure that this restriction
12664                // state propagation is persisted
12665                mSettings.writeAllUsersPackageRestrictionsLPr();
12666            }
12667            // can downgrade to reader here
12668            if (writeSettings) {
12669                mSettings.writeLPr();
12670            }
12671        }
12672        return true;
12673    }
12674
12675    private boolean deleteInstalledPackageLI(PackageSetting ps,
12676            boolean deleteCodeAndResources, int flags,
12677            int[] allUserHandles, boolean[] perUserInstalled,
12678            PackageRemovedInfo outInfo, boolean writeSettings) {
12679        if (outInfo != null) {
12680            outInfo.uid = ps.appId;
12681        }
12682
12683        // Delete package data from internal structures and also remove data if flag is set
12684        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
12685
12686        // Delete application code and resources
12687        if (deleteCodeAndResources && (outInfo != null)) {
12688            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
12689                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
12690            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
12691        }
12692        return true;
12693    }
12694
12695    @Override
12696    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
12697            int userId) {
12698        mContext.enforceCallingOrSelfPermission(
12699                android.Manifest.permission.DELETE_PACKAGES, null);
12700        synchronized (mPackages) {
12701            PackageSetting ps = mSettings.mPackages.get(packageName);
12702            if (ps == null) {
12703                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
12704                return false;
12705            }
12706            if (!ps.getInstalled(userId)) {
12707                // Can't block uninstall for an app that is not installed or enabled.
12708                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
12709                return false;
12710            }
12711            ps.setBlockUninstall(blockUninstall, userId);
12712            mSettings.writePackageRestrictionsLPr(userId);
12713        }
12714        return true;
12715    }
12716
12717    @Override
12718    public boolean getBlockUninstallForUser(String packageName, int userId) {
12719        synchronized (mPackages) {
12720            PackageSetting ps = mSettings.mPackages.get(packageName);
12721            if (ps == null) {
12722                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
12723                return false;
12724            }
12725            return ps.getBlockUninstall(userId);
12726        }
12727    }
12728
12729    /*
12730     * This method handles package deletion in general
12731     */
12732    private boolean deletePackageLI(String packageName, UserHandle user,
12733            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
12734            int flags, PackageRemovedInfo outInfo,
12735            boolean writeSettings) {
12736        if (packageName == null) {
12737            Slog.w(TAG, "Attempt to delete null packageName.");
12738            return false;
12739        }
12740        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
12741        PackageSetting ps;
12742        boolean dataOnly = false;
12743        int removeUser = -1;
12744        int appId = -1;
12745        synchronized (mPackages) {
12746            ps = mSettings.mPackages.get(packageName);
12747            if (ps == null) {
12748                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12749                return false;
12750            }
12751            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
12752                    && user.getIdentifier() != UserHandle.USER_ALL) {
12753                // The caller is asking that the package only be deleted for a single
12754                // user.  To do this, we just mark its uninstalled state and delete
12755                // its data.  If this is a system app, we only allow this to happen if
12756                // they have set the special DELETE_SYSTEM_APP which requests different
12757                // semantics than normal for uninstalling system apps.
12758                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
12759                ps.setUserState(user.getIdentifier(),
12760                        COMPONENT_ENABLED_STATE_DEFAULT,
12761                        false, //installed
12762                        true,  //stopped
12763                        true,  //notLaunched
12764                        false, //hidden
12765                        null, null, null,
12766                        false, // blockUninstall
12767                        INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
12768                if (!isSystemApp(ps)) {
12769                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
12770                        // Other user still have this package installed, so all
12771                        // we need to do is clear this user's data and save that
12772                        // it is uninstalled.
12773                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
12774                        removeUser = user.getIdentifier();
12775                        appId = ps.appId;
12776                        scheduleWritePackageRestrictionsLocked(removeUser);
12777                    } else {
12778                        // We need to set it back to 'installed' so the uninstall
12779                        // broadcasts will be sent correctly.
12780                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
12781                        ps.setInstalled(true, user.getIdentifier());
12782                    }
12783                } else {
12784                    // This is a system app, so we assume that the
12785                    // other users still have this package installed, so all
12786                    // we need to do is clear this user's data and save that
12787                    // it is uninstalled.
12788                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
12789                    removeUser = user.getIdentifier();
12790                    appId = ps.appId;
12791                    scheduleWritePackageRestrictionsLocked(removeUser);
12792                }
12793            }
12794        }
12795
12796        if (removeUser >= 0) {
12797            // From above, we determined that we are deleting this only
12798            // for a single user.  Continue the work here.
12799            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
12800            if (outInfo != null) {
12801                outInfo.removedPackage = packageName;
12802                outInfo.removedAppId = appId;
12803                outInfo.removedUsers = new int[] {removeUser};
12804            }
12805            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
12806            removeKeystoreDataIfNeeded(removeUser, appId);
12807            schedulePackageCleaning(packageName, removeUser, false);
12808            synchronized (mPackages) {
12809                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
12810                    scheduleWritePackageRestrictionsLocked(removeUser);
12811                }
12812                revokeRuntimePermissionsAndClearAllFlagsLocked(ps.getPermissionsState(),
12813                        removeUser);
12814            }
12815            return true;
12816        }
12817
12818        if (dataOnly) {
12819            // Delete application data first
12820            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
12821            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
12822            return true;
12823        }
12824
12825        boolean ret = false;
12826        if (isSystemApp(ps)) {
12827            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
12828            // When an updated system application is deleted we delete the existing resources as well and
12829            // fall back to existing code in system partition
12830            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
12831                    flags, outInfo, writeSettings);
12832        } else {
12833            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
12834            // Kill application pre-emptively especially for apps on sd.
12835            killApplication(packageName, ps.appId, "uninstall pkg");
12836            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
12837                    allUserHandles, perUserInstalled,
12838                    outInfo, writeSettings);
12839        }
12840
12841        return ret;
12842    }
12843
12844    private final class ClearStorageConnection implements ServiceConnection {
12845        IMediaContainerService mContainerService;
12846
12847        @Override
12848        public void onServiceConnected(ComponentName name, IBinder service) {
12849            synchronized (this) {
12850                mContainerService = IMediaContainerService.Stub.asInterface(service);
12851                notifyAll();
12852            }
12853        }
12854
12855        @Override
12856        public void onServiceDisconnected(ComponentName name) {
12857        }
12858    }
12859
12860    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
12861        final boolean mounted;
12862        if (Environment.isExternalStorageEmulated()) {
12863            mounted = true;
12864        } else {
12865            final String status = Environment.getExternalStorageState();
12866
12867            mounted = status.equals(Environment.MEDIA_MOUNTED)
12868                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
12869        }
12870
12871        if (!mounted) {
12872            return;
12873        }
12874
12875        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
12876        int[] users;
12877        if (userId == UserHandle.USER_ALL) {
12878            users = sUserManager.getUserIds();
12879        } else {
12880            users = new int[] { userId };
12881        }
12882        final ClearStorageConnection conn = new ClearStorageConnection();
12883        if (mContext.bindServiceAsUser(
12884                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
12885            try {
12886                for (int curUser : users) {
12887                    long timeout = SystemClock.uptimeMillis() + 5000;
12888                    synchronized (conn) {
12889                        long now = SystemClock.uptimeMillis();
12890                        while (conn.mContainerService == null && now < timeout) {
12891                            try {
12892                                conn.wait(timeout - now);
12893                            } catch (InterruptedException e) {
12894                            }
12895                        }
12896                    }
12897                    if (conn.mContainerService == null) {
12898                        return;
12899                    }
12900
12901                    final UserEnvironment userEnv = new UserEnvironment(curUser);
12902                    clearDirectory(conn.mContainerService,
12903                            userEnv.buildExternalStorageAppCacheDirs(packageName));
12904                    if (allData) {
12905                        clearDirectory(conn.mContainerService,
12906                                userEnv.buildExternalStorageAppDataDirs(packageName));
12907                        clearDirectory(conn.mContainerService,
12908                                userEnv.buildExternalStorageAppMediaDirs(packageName));
12909                    }
12910                }
12911            } finally {
12912                mContext.unbindService(conn);
12913            }
12914        }
12915    }
12916
12917    @Override
12918    public void clearApplicationUserData(final String packageName,
12919            final IPackageDataObserver observer, final int userId) {
12920        mContext.enforceCallingOrSelfPermission(
12921                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
12922        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
12923        // Queue up an async operation since the package deletion may take a little while.
12924        mHandler.post(new Runnable() {
12925            public void run() {
12926                mHandler.removeCallbacks(this);
12927                final boolean succeeded;
12928                synchronized (mInstallLock) {
12929                    succeeded = clearApplicationUserDataLI(packageName, userId);
12930                }
12931                clearExternalStorageDataSync(packageName, userId, true);
12932                if (succeeded) {
12933                    // invoke DeviceStorageMonitor's update method to clear any notifications
12934                    DeviceStorageMonitorInternal
12935                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
12936                    if (dsm != null) {
12937                        dsm.checkMemory();
12938                    }
12939                }
12940                if(observer != null) {
12941                    try {
12942                        observer.onRemoveCompleted(packageName, succeeded);
12943                    } catch (RemoteException e) {
12944                        Log.i(TAG, "Observer no longer exists.");
12945                    }
12946                } //end if observer
12947            } //end run
12948        });
12949    }
12950
12951    private boolean clearApplicationUserDataLI(String packageName, int userId) {
12952        if (packageName == null) {
12953            Slog.w(TAG, "Attempt to delete null packageName.");
12954            return false;
12955        }
12956
12957        // Try finding details about the requested package
12958        PackageParser.Package pkg;
12959        synchronized (mPackages) {
12960            pkg = mPackages.get(packageName);
12961            if (pkg == null) {
12962                final PackageSetting ps = mSettings.mPackages.get(packageName);
12963                if (ps != null) {
12964                    pkg = ps.pkg;
12965                }
12966            }
12967
12968            if (pkg == null) {
12969                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12970                return false;
12971            }
12972
12973            PackageSetting ps = (PackageSetting) pkg.mExtras;
12974            PermissionsState permissionsState = ps.getPermissionsState();
12975            revokeRuntimePermissionsAndClearUserSetFlagsLocked(permissionsState, userId);
12976        }
12977
12978        // Always delete data directories for package, even if we found no other
12979        // record of app. This helps users recover from UID mismatches without
12980        // resorting to a full data wipe.
12981        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
12982        if (retCode < 0) {
12983            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
12984            return false;
12985        }
12986
12987        final int appId = pkg.applicationInfo.uid;
12988        removeKeystoreDataIfNeeded(userId, appId);
12989
12990        // Create a native library symlink only if we have native libraries
12991        // and if the native libraries are 32 bit libraries. We do not provide
12992        // this symlink for 64 bit libraries.
12993        if (pkg.applicationInfo.primaryCpuAbi != null &&
12994                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
12995            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
12996            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
12997                    nativeLibPath, userId) < 0) {
12998                Slog.w(TAG, "Failed linking native library dir");
12999                return false;
13000            }
13001        }
13002
13003        return true;
13004    }
13005
13006
13007    /**
13008     * Revokes granted runtime permissions and clears resettable flags
13009     * which are flags that can be set by a user interaction.
13010     *
13011     * @param permissionsState The permission state to reset.
13012     * @param userId The device user for which to do a reset.
13013     */
13014    private void revokeRuntimePermissionsAndClearUserSetFlagsLocked(
13015            PermissionsState permissionsState, int userId) {
13016        final int userSetFlags = PackageManager.FLAG_PERMISSION_USER_SET
13017                | PackageManager.FLAG_PERMISSION_USER_FIXED
13018                | PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13019
13020        revokeRuntimePermissionsAndClearFlagsLocked(permissionsState, userId, userSetFlags);
13021    }
13022
13023    /**
13024     * Revokes granted runtime permissions and clears all flags.
13025     *
13026     * @param permissionsState The permission state to reset.
13027     * @param userId The device user for which to do a reset.
13028     */
13029    private void revokeRuntimePermissionsAndClearAllFlagsLocked(
13030            PermissionsState permissionsState, int userId) {
13031        revokeRuntimePermissionsAndClearFlagsLocked(permissionsState, userId,
13032                PackageManager.MASK_PERMISSION_FLAGS);
13033    }
13034
13035    /**
13036     * Revokes granted runtime permissions and clears certain flags.
13037     *
13038     * @param permissionsState The permission state to reset.
13039     * @param userId The device user for which to do a reset.
13040     * @param flags The flags that is going to be reset.
13041     */
13042    private void revokeRuntimePermissionsAndClearFlagsLocked(
13043            PermissionsState permissionsState, final int userId, int flags) {
13044        boolean needsWrite = false;
13045
13046        for (PermissionState state : permissionsState.getRuntimePermissionStates(userId)) {
13047            BasePermission bp = mSettings.mPermissions.get(state.getName());
13048            if (bp != null) {
13049                permissionsState.revokeRuntimePermission(bp, userId);
13050                permissionsState.updatePermissionFlags(bp, userId, flags, 0);
13051                needsWrite = true;
13052            }
13053        }
13054
13055        // Ensure default permissions are never cleared.
13056        mHandler.post(new Runnable() {
13057            @Override
13058            public void run() {
13059                mDefaultPermissionPolicy.grantDefaultPermissions(userId);
13060            }
13061        });
13062
13063        if (needsWrite) {
13064            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
13065        }
13066    }
13067
13068    /**
13069     * Remove entries from the keystore daemon. Will only remove it if the
13070     * {@code appId} is valid.
13071     */
13072    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
13073        if (appId < 0) {
13074            return;
13075        }
13076
13077        final KeyStore keyStore = KeyStore.getInstance();
13078        if (keyStore != null) {
13079            if (userId == UserHandle.USER_ALL) {
13080                for (final int individual : sUserManager.getUserIds()) {
13081                    keyStore.clearUid(UserHandle.getUid(individual, appId));
13082                }
13083            } else {
13084                keyStore.clearUid(UserHandle.getUid(userId, appId));
13085            }
13086        } else {
13087            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
13088        }
13089    }
13090
13091    @Override
13092    public void deleteApplicationCacheFiles(final String packageName,
13093            final IPackageDataObserver observer) {
13094        mContext.enforceCallingOrSelfPermission(
13095                android.Manifest.permission.DELETE_CACHE_FILES, null);
13096        // Queue up an async operation since the package deletion may take a little while.
13097        final int userId = UserHandle.getCallingUserId();
13098        mHandler.post(new Runnable() {
13099            public void run() {
13100                mHandler.removeCallbacks(this);
13101                final boolean succeded;
13102                synchronized (mInstallLock) {
13103                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
13104                }
13105                clearExternalStorageDataSync(packageName, userId, false);
13106                if (observer != null) {
13107                    try {
13108                        observer.onRemoveCompleted(packageName, succeded);
13109                    } catch (RemoteException e) {
13110                        Log.i(TAG, "Observer no longer exists.");
13111                    }
13112                } //end if observer
13113            } //end run
13114        });
13115    }
13116
13117    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
13118        if (packageName == null) {
13119            Slog.w(TAG, "Attempt to delete null packageName.");
13120            return false;
13121        }
13122        PackageParser.Package p;
13123        synchronized (mPackages) {
13124            p = mPackages.get(packageName);
13125        }
13126        if (p == null) {
13127            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13128            return false;
13129        }
13130        final ApplicationInfo applicationInfo = p.applicationInfo;
13131        if (applicationInfo == null) {
13132            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13133            return false;
13134        }
13135        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
13136        if (retCode < 0) {
13137            Slog.w(TAG, "Couldn't remove cache files for package: "
13138                       + packageName + " u" + userId);
13139            return false;
13140        }
13141        return true;
13142    }
13143
13144    @Override
13145    public void getPackageSizeInfo(final String packageName, int userHandle,
13146            final IPackageStatsObserver observer) {
13147        mContext.enforceCallingOrSelfPermission(
13148                android.Manifest.permission.GET_PACKAGE_SIZE, null);
13149        if (packageName == null) {
13150            throw new IllegalArgumentException("Attempt to get size of null packageName");
13151        }
13152
13153        PackageStats stats = new PackageStats(packageName, userHandle);
13154
13155        /*
13156         * Queue up an async operation since the package measurement may take a
13157         * little while.
13158         */
13159        Message msg = mHandler.obtainMessage(INIT_COPY);
13160        msg.obj = new MeasureParams(stats, observer);
13161        mHandler.sendMessage(msg);
13162    }
13163
13164    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
13165            PackageStats pStats) {
13166        if (packageName == null) {
13167            Slog.w(TAG, "Attempt to get size of null packageName.");
13168            return false;
13169        }
13170        PackageParser.Package p;
13171        boolean dataOnly = false;
13172        String libDirRoot = null;
13173        String asecPath = null;
13174        PackageSetting ps = null;
13175        synchronized (mPackages) {
13176            p = mPackages.get(packageName);
13177            ps = mSettings.mPackages.get(packageName);
13178            if(p == null) {
13179                dataOnly = true;
13180                if((ps == null) || (ps.pkg == null)) {
13181                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13182                    return false;
13183                }
13184                p = ps.pkg;
13185            }
13186            if (ps != null) {
13187                libDirRoot = ps.legacyNativeLibraryPathString;
13188            }
13189            if (p != null && (isExternal(p) || p.isForwardLocked())) {
13190                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
13191                if (secureContainerId != null) {
13192                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
13193                }
13194            }
13195        }
13196        String publicSrcDir = null;
13197        if(!dataOnly) {
13198            final ApplicationInfo applicationInfo = p.applicationInfo;
13199            if (applicationInfo == null) {
13200                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13201                return false;
13202            }
13203            if (p.isForwardLocked()) {
13204                publicSrcDir = applicationInfo.getBaseResourcePath();
13205            }
13206        }
13207        // TODO: extend to measure size of split APKs
13208        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
13209        // not just the first level.
13210        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
13211        // just the primary.
13212        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
13213        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath,
13214                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
13215        if (res < 0) {
13216            return false;
13217        }
13218
13219        // Fix-up for forward-locked applications in ASEC containers.
13220        if (!isExternal(p)) {
13221            pStats.codeSize += pStats.externalCodeSize;
13222            pStats.externalCodeSize = 0L;
13223        }
13224
13225        return true;
13226    }
13227
13228
13229    @Override
13230    public void addPackageToPreferred(String packageName) {
13231        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
13232    }
13233
13234    @Override
13235    public void removePackageFromPreferred(String packageName) {
13236        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
13237    }
13238
13239    @Override
13240    public List<PackageInfo> getPreferredPackages(int flags) {
13241        return new ArrayList<PackageInfo>();
13242    }
13243
13244    private int getUidTargetSdkVersionLockedLPr(int uid) {
13245        Object obj = mSettings.getUserIdLPr(uid);
13246        if (obj instanceof SharedUserSetting) {
13247            final SharedUserSetting sus = (SharedUserSetting) obj;
13248            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
13249            final Iterator<PackageSetting> it = sus.packages.iterator();
13250            while (it.hasNext()) {
13251                final PackageSetting ps = it.next();
13252                if (ps.pkg != null) {
13253                    int v = ps.pkg.applicationInfo.targetSdkVersion;
13254                    if (v < vers) vers = v;
13255                }
13256            }
13257            return vers;
13258        } else if (obj instanceof PackageSetting) {
13259            final PackageSetting ps = (PackageSetting) obj;
13260            if (ps.pkg != null) {
13261                return ps.pkg.applicationInfo.targetSdkVersion;
13262            }
13263        }
13264        return Build.VERSION_CODES.CUR_DEVELOPMENT;
13265    }
13266
13267    @Override
13268    public void addPreferredActivity(IntentFilter filter, int match,
13269            ComponentName[] set, ComponentName activity, int userId) {
13270        addPreferredActivityInternal(filter, match, set, activity, true, userId,
13271                "Adding preferred");
13272    }
13273
13274    private void addPreferredActivityInternal(IntentFilter filter, int match,
13275            ComponentName[] set, ComponentName activity, boolean always, int userId,
13276            String opname) {
13277        // writer
13278        int callingUid = Binder.getCallingUid();
13279        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
13280        if (filter.countActions() == 0) {
13281            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13282            return;
13283        }
13284        synchronized (mPackages) {
13285            if (mContext.checkCallingOrSelfPermission(
13286                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13287                    != PackageManager.PERMISSION_GRANTED) {
13288                if (getUidTargetSdkVersionLockedLPr(callingUid)
13289                        < Build.VERSION_CODES.FROYO) {
13290                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
13291                            + callingUid);
13292                    return;
13293                }
13294                mContext.enforceCallingOrSelfPermission(
13295                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13296            }
13297
13298            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
13299            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
13300                    + userId + ":");
13301            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13302            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
13303            scheduleWritePackageRestrictionsLocked(userId);
13304        }
13305    }
13306
13307    @Override
13308    public void replacePreferredActivity(IntentFilter filter, int match,
13309            ComponentName[] set, ComponentName activity, int userId) {
13310        if (filter.countActions() != 1) {
13311            throw new IllegalArgumentException(
13312                    "replacePreferredActivity expects filter to have only 1 action.");
13313        }
13314        if (filter.countDataAuthorities() != 0
13315                || filter.countDataPaths() != 0
13316                || filter.countDataSchemes() > 1
13317                || filter.countDataTypes() != 0) {
13318            throw new IllegalArgumentException(
13319                    "replacePreferredActivity expects filter to have no data authorities, " +
13320                    "paths, or types; and at most one scheme.");
13321        }
13322
13323        final int callingUid = Binder.getCallingUid();
13324        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
13325        synchronized (mPackages) {
13326            if (mContext.checkCallingOrSelfPermission(
13327                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13328                    != PackageManager.PERMISSION_GRANTED) {
13329                if (getUidTargetSdkVersionLockedLPr(callingUid)
13330                        < Build.VERSION_CODES.FROYO) {
13331                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
13332                            + Binder.getCallingUid());
13333                    return;
13334                }
13335                mContext.enforceCallingOrSelfPermission(
13336                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13337            }
13338
13339            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13340            if (pir != null) {
13341                // Get all of the existing entries that exactly match this filter.
13342                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
13343                if (existing != null && existing.size() == 1) {
13344                    PreferredActivity cur = existing.get(0);
13345                    if (DEBUG_PREFERRED) {
13346                        Slog.i(TAG, "Checking replace of preferred:");
13347                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13348                        if (!cur.mPref.mAlways) {
13349                            Slog.i(TAG, "  -- CUR; not mAlways!");
13350                        } else {
13351                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
13352                            Slog.i(TAG, "  -- CUR: mSet="
13353                                    + Arrays.toString(cur.mPref.mSetComponents));
13354                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
13355                            Slog.i(TAG, "  -- NEW: mMatch="
13356                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
13357                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
13358                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
13359                        }
13360                    }
13361                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
13362                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
13363                            && cur.mPref.sameSet(set)) {
13364                        // Setting the preferred activity to what it happens to be already
13365                        if (DEBUG_PREFERRED) {
13366                            Slog.i(TAG, "Replacing with same preferred activity "
13367                                    + cur.mPref.mShortComponent + " for user "
13368                                    + userId + ":");
13369                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13370                        }
13371                        return;
13372                    }
13373                }
13374
13375                if (existing != null) {
13376                    if (DEBUG_PREFERRED) {
13377                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
13378                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13379                    }
13380                    for (int i = 0; i < existing.size(); i++) {
13381                        PreferredActivity pa = existing.get(i);
13382                        if (DEBUG_PREFERRED) {
13383                            Slog.i(TAG, "Removing existing preferred activity "
13384                                    + pa.mPref.mComponent + ":");
13385                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
13386                        }
13387                        pir.removeFilter(pa);
13388                    }
13389                }
13390            }
13391            addPreferredActivityInternal(filter, match, set, activity, true, userId,
13392                    "Replacing preferred");
13393        }
13394    }
13395
13396    @Override
13397    public void clearPackagePreferredActivities(String packageName) {
13398        final int uid = Binder.getCallingUid();
13399        // writer
13400        synchronized (mPackages) {
13401            PackageParser.Package pkg = mPackages.get(packageName);
13402            if (pkg == null || pkg.applicationInfo.uid != uid) {
13403                if (mContext.checkCallingOrSelfPermission(
13404                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13405                        != PackageManager.PERMISSION_GRANTED) {
13406                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
13407                            < Build.VERSION_CODES.FROYO) {
13408                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
13409                                + Binder.getCallingUid());
13410                        return;
13411                    }
13412                    mContext.enforceCallingOrSelfPermission(
13413                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13414                }
13415            }
13416
13417            int user = UserHandle.getCallingUserId();
13418            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
13419                scheduleWritePackageRestrictionsLocked(user);
13420            }
13421        }
13422    }
13423
13424    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13425    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
13426        ArrayList<PreferredActivity> removed = null;
13427        boolean changed = false;
13428        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13429            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
13430            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13431            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
13432                continue;
13433            }
13434            Iterator<PreferredActivity> it = pir.filterIterator();
13435            while (it.hasNext()) {
13436                PreferredActivity pa = it.next();
13437                // Mark entry for removal only if it matches the package name
13438                // and the entry is of type "always".
13439                if (packageName == null ||
13440                        (pa.mPref.mComponent.getPackageName().equals(packageName)
13441                                && pa.mPref.mAlways)) {
13442                    if (removed == null) {
13443                        removed = new ArrayList<PreferredActivity>();
13444                    }
13445                    removed.add(pa);
13446                }
13447            }
13448            if (removed != null) {
13449                for (int j=0; j<removed.size(); j++) {
13450                    PreferredActivity pa = removed.get(j);
13451                    pir.removeFilter(pa);
13452                }
13453                changed = true;
13454            }
13455        }
13456        return changed;
13457    }
13458
13459    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13460    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
13461        if (userId == UserHandle.USER_ALL) {
13462            if (mSettings.removeIntentFilterVerificationLPw(packageName,
13463                    sUserManager.getUserIds())) {
13464                for (int oneUserId : sUserManager.getUserIds()) {
13465                    scheduleWritePackageRestrictionsLocked(oneUserId);
13466                }
13467            }
13468        } else {
13469            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
13470                scheduleWritePackageRestrictionsLocked(userId);
13471            }
13472        }
13473    }
13474
13475
13476    void clearDefaultBrowserIfNeeded(String packageName) {
13477        for (int oneUserId : sUserManager.getUserIds()) {
13478            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
13479            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
13480            if (packageName.equals(defaultBrowserPackageName)) {
13481                setDefaultBrowserPackageName(null, oneUserId);
13482            }
13483        }
13484    }
13485
13486    @Override
13487    public void resetPreferredActivities(int userId) {
13488        mContext.enforceCallingOrSelfPermission(
13489                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13490        // writer
13491        synchronized (mPackages) {
13492            clearPackagePreferredActivitiesLPw(null, userId);
13493            mSettings.applyDefaultPreferredAppsLPw(this, userId);
13494            applyFactoryDefaultBrowserLPw(userId);
13495
13496            scheduleWritePackageRestrictionsLocked(userId);
13497        }
13498    }
13499
13500    @Override
13501    public int getPreferredActivities(List<IntentFilter> outFilters,
13502            List<ComponentName> outActivities, String packageName) {
13503
13504        int num = 0;
13505        final int userId = UserHandle.getCallingUserId();
13506        // reader
13507        synchronized (mPackages) {
13508            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13509            if (pir != null) {
13510                final Iterator<PreferredActivity> it = pir.filterIterator();
13511                while (it.hasNext()) {
13512                    final PreferredActivity pa = it.next();
13513                    if (packageName == null
13514                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
13515                                    && pa.mPref.mAlways)) {
13516                        if (outFilters != null) {
13517                            outFilters.add(new IntentFilter(pa));
13518                        }
13519                        if (outActivities != null) {
13520                            outActivities.add(pa.mPref.mComponent);
13521                        }
13522                    }
13523                }
13524            }
13525        }
13526
13527        return num;
13528    }
13529
13530    @Override
13531    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
13532            int userId) {
13533        int callingUid = Binder.getCallingUid();
13534        if (callingUid != Process.SYSTEM_UID) {
13535            throw new SecurityException(
13536                    "addPersistentPreferredActivity can only be run by the system");
13537        }
13538        if (filter.countActions() == 0) {
13539            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13540            return;
13541        }
13542        synchronized (mPackages) {
13543            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
13544                    " :");
13545            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13546            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
13547                    new PersistentPreferredActivity(filter, activity));
13548            scheduleWritePackageRestrictionsLocked(userId);
13549        }
13550    }
13551
13552    @Override
13553    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
13554        int callingUid = Binder.getCallingUid();
13555        if (callingUid != Process.SYSTEM_UID) {
13556            throw new SecurityException(
13557                    "clearPackagePersistentPreferredActivities can only be run by the system");
13558        }
13559        ArrayList<PersistentPreferredActivity> removed = null;
13560        boolean changed = false;
13561        synchronized (mPackages) {
13562            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
13563                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
13564                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
13565                        .valueAt(i);
13566                if (userId != thisUserId) {
13567                    continue;
13568                }
13569                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
13570                while (it.hasNext()) {
13571                    PersistentPreferredActivity ppa = it.next();
13572                    // Mark entry for removal only if it matches the package name.
13573                    if (ppa.mComponent.getPackageName().equals(packageName)) {
13574                        if (removed == null) {
13575                            removed = new ArrayList<PersistentPreferredActivity>();
13576                        }
13577                        removed.add(ppa);
13578                    }
13579                }
13580                if (removed != null) {
13581                    for (int j=0; j<removed.size(); j++) {
13582                        PersistentPreferredActivity ppa = removed.get(j);
13583                        ppir.removeFilter(ppa);
13584                    }
13585                    changed = true;
13586                }
13587            }
13588
13589            if (changed) {
13590                scheduleWritePackageRestrictionsLocked(userId);
13591            }
13592        }
13593    }
13594
13595    /**
13596     * Common machinery for picking apart a restored XML blob and passing
13597     * it to a caller-supplied functor to be applied to the running system.
13598     */
13599    private void restoreFromXml(XmlPullParser parser, int userId,
13600            String expectedStartTag, BlobXmlRestorer functor)
13601            throws IOException, XmlPullParserException {
13602        int type;
13603        while ((type = parser.next()) != XmlPullParser.START_TAG
13604                && type != XmlPullParser.END_DOCUMENT) {
13605        }
13606        if (type != XmlPullParser.START_TAG) {
13607            // oops didn't find a start tag?!
13608            if (DEBUG_BACKUP) {
13609                Slog.e(TAG, "Didn't find start tag during restore");
13610            }
13611            return;
13612        }
13613
13614        // this is supposed to be TAG_PREFERRED_BACKUP
13615        if (!expectedStartTag.equals(parser.getName())) {
13616            if (DEBUG_BACKUP) {
13617                Slog.e(TAG, "Found unexpected tag " + parser.getName());
13618            }
13619            return;
13620        }
13621
13622        // skip interfering stuff, then we're aligned with the backing implementation
13623        while ((type = parser.next()) == XmlPullParser.TEXT) { }
13624        functor.apply(parser, userId);
13625    }
13626
13627    private interface BlobXmlRestorer {
13628        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
13629    }
13630
13631    /**
13632     * Non-Binder method, support for the backup/restore mechanism: write the
13633     * full set of preferred activities in its canonical XML format.  Returns the
13634     * XML output as a byte array, or null if there is none.
13635     */
13636    @Override
13637    public byte[] getPreferredActivityBackup(int userId) {
13638        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13639            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
13640        }
13641
13642        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13643        try {
13644            final XmlSerializer serializer = new FastXmlSerializer();
13645            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13646            serializer.startDocument(null, true);
13647            serializer.startTag(null, TAG_PREFERRED_BACKUP);
13648
13649            synchronized (mPackages) {
13650                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
13651            }
13652
13653            serializer.endTag(null, TAG_PREFERRED_BACKUP);
13654            serializer.endDocument();
13655            serializer.flush();
13656        } catch (Exception e) {
13657            if (DEBUG_BACKUP) {
13658                Slog.e(TAG, "Unable to write preferred activities for backup", e);
13659            }
13660            return null;
13661        }
13662
13663        return dataStream.toByteArray();
13664    }
13665
13666    @Override
13667    public void restorePreferredActivities(byte[] backup, int userId) {
13668        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13669            throw new SecurityException("Only the system may call restorePreferredActivities()");
13670        }
13671
13672        try {
13673            final XmlPullParser parser = Xml.newPullParser();
13674            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13675            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
13676                    new BlobXmlRestorer() {
13677                        @Override
13678                        public void apply(XmlPullParser parser, int userId)
13679                                throws XmlPullParserException, IOException {
13680                            synchronized (mPackages) {
13681                                mSettings.readPreferredActivitiesLPw(parser, userId);
13682                            }
13683                        }
13684                    } );
13685        } catch (Exception e) {
13686            if (DEBUG_BACKUP) {
13687                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
13688            }
13689        }
13690    }
13691
13692    /**
13693     * Non-Binder method, support for the backup/restore mechanism: write the
13694     * default browser (etc) settings in its canonical XML format.  Returns the default
13695     * browser XML representation as a byte array, or null if there is none.
13696     */
13697    @Override
13698    public byte[] getDefaultAppsBackup(int userId) {
13699        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13700            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
13701        }
13702
13703        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13704        try {
13705            final XmlSerializer serializer = new FastXmlSerializer();
13706            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13707            serializer.startDocument(null, true);
13708            serializer.startTag(null, TAG_DEFAULT_APPS);
13709
13710            synchronized (mPackages) {
13711                mSettings.writeDefaultAppsLPr(serializer, userId);
13712            }
13713
13714            serializer.endTag(null, TAG_DEFAULT_APPS);
13715            serializer.endDocument();
13716            serializer.flush();
13717        } catch (Exception e) {
13718            if (DEBUG_BACKUP) {
13719                Slog.e(TAG, "Unable to write default apps for backup", e);
13720            }
13721            return null;
13722        }
13723
13724        return dataStream.toByteArray();
13725    }
13726
13727    @Override
13728    public void restoreDefaultApps(byte[] backup, int userId) {
13729        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13730            throw new SecurityException("Only the system may call restoreDefaultApps()");
13731        }
13732
13733        try {
13734            final XmlPullParser parser = Xml.newPullParser();
13735            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13736            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
13737                    new BlobXmlRestorer() {
13738                        @Override
13739                        public void apply(XmlPullParser parser, int userId)
13740                                throws XmlPullParserException, IOException {
13741                            synchronized (mPackages) {
13742                                mSettings.readDefaultAppsLPw(parser, userId);
13743                            }
13744                        }
13745                    } );
13746        } catch (Exception e) {
13747            if (DEBUG_BACKUP) {
13748                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
13749            }
13750        }
13751    }
13752
13753    @Override
13754    public byte[] getIntentFilterVerificationBackup(int userId) {
13755        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13756            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
13757        }
13758
13759        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13760        try {
13761            final XmlSerializer serializer = new FastXmlSerializer();
13762            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13763            serializer.startDocument(null, true);
13764            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
13765
13766            synchronized (mPackages) {
13767                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
13768            }
13769
13770            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
13771            serializer.endDocument();
13772            serializer.flush();
13773        } catch (Exception e) {
13774            if (DEBUG_BACKUP) {
13775                Slog.e(TAG, "Unable to write default apps for backup", e);
13776            }
13777            return null;
13778        }
13779
13780        return dataStream.toByteArray();
13781    }
13782
13783    @Override
13784    public void restoreIntentFilterVerification(byte[] backup, int userId) {
13785        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13786            throw new SecurityException("Only the system may call restorePreferredActivities()");
13787        }
13788
13789        try {
13790            final XmlPullParser parser = Xml.newPullParser();
13791            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13792            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
13793                    new BlobXmlRestorer() {
13794                        @Override
13795                        public void apply(XmlPullParser parser, int userId)
13796                                throws XmlPullParserException, IOException {
13797                            synchronized (mPackages) {
13798                                mSettings.readAllDomainVerificationsLPr(parser, userId);
13799                                mSettings.writeLPr();
13800                            }
13801                        }
13802                    } );
13803        } catch (Exception e) {
13804            if (DEBUG_BACKUP) {
13805                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
13806            }
13807        }
13808    }
13809
13810    @Override
13811    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
13812            int sourceUserId, int targetUserId, int flags) {
13813        mContext.enforceCallingOrSelfPermission(
13814                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
13815        int callingUid = Binder.getCallingUid();
13816        enforceOwnerRights(ownerPackage, callingUid);
13817        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
13818        if (intentFilter.countActions() == 0) {
13819            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
13820            return;
13821        }
13822        synchronized (mPackages) {
13823            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
13824                    ownerPackage, targetUserId, flags);
13825            CrossProfileIntentResolver resolver =
13826                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
13827            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
13828            // We have all those whose filter is equal. Now checking if the rest is equal as well.
13829            if (existing != null) {
13830                int size = existing.size();
13831                for (int i = 0; i < size; i++) {
13832                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
13833                        return;
13834                    }
13835                }
13836            }
13837            resolver.addFilter(newFilter);
13838            scheduleWritePackageRestrictionsLocked(sourceUserId);
13839        }
13840    }
13841
13842    @Override
13843    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
13844        mContext.enforceCallingOrSelfPermission(
13845                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
13846        int callingUid = Binder.getCallingUid();
13847        enforceOwnerRights(ownerPackage, callingUid);
13848        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
13849        synchronized (mPackages) {
13850            CrossProfileIntentResolver resolver =
13851                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
13852            ArraySet<CrossProfileIntentFilter> set =
13853                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
13854            for (CrossProfileIntentFilter filter : set) {
13855                if (filter.getOwnerPackage().equals(ownerPackage)) {
13856                    resolver.removeFilter(filter);
13857                }
13858            }
13859            scheduleWritePackageRestrictionsLocked(sourceUserId);
13860        }
13861    }
13862
13863    // Enforcing that callingUid is owning pkg on userId
13864    private void enforceOwnerRights(String pkg, int callingUid) {
13865        // The system owns everything.
13866        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
13867            return;
13868        }
13869        int callingUserId = UserHandle.getUserId(callingUid);
13870        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
13871        if (pi == null) {
13872            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
13873                    + callingUserId);
13874        }
13875        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
13876            throw new SecurityException("Calling uid " + callingUid
13877                    + " does not own package " + pkg);
13878        }
13879    }
13880
13881    @Override
13882    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
13883        Intent intent = new Intent(Intent.ACTION_MAIN);
13884        intent.addCategory(Intent.CATEGORY_HOME);
13885
13886        final int callingUserId = UserHandle.getCallingUserId();
13887        List<ResolveInfo> list = queryIntentActivities(intent, null,
13888                PackageManager.GET_META_DATA, callingUserId);
13889        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
13890                true, false, false, callingUserId);
13891
13892        allHomeCandidates.clear();
13893        if (list != null) {
13894            for (ResolveInfo ri : list) {
13895                allHomeCandidates.add(ri);
13896            }
13897        }
13898        return (preferred == null || preferred.activityInfo == null)
13899                ? null
13900                : new ComponentName(preferred.activityInfo.packageName,
13901                        preferred.activityInfo.name);
13902    }
13903
13904    @Override
13905    public void setApplicationEnabledSetting(String appPackageName,
13906            int newState, int flags, int userId, String callingPackage) {
13907        if (!sUserManager.exists(userId)) return;
13908        if (callingPackage == null) {
13909            callingPackage = Integer.toString(Binder.getCallingUid());
13910        }
13911        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
13912    }
13913
13914    @Override
13915    public void setComponentEnabledSetting(ComponentName componentName,
13916            int newState, int flags, int userId) {
13917        if (!sUserManager.exists(userId)) return;
13918        setEnabledSetting(componentName.getPackageName(),
13919                componentName.getClassName(), newState, flags, userId, null);
13920    }
13921
13922    private void setEnabledSetting(final String packageName, String className, int newState,
13923            final int flags, int userId, String callingPackage) {
13924        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
13925              || newState == COMPONENT_ENABLED_STATE_ENABLED
13926              || newState == COMPONENT_ENABLED_STATE_DISABLED
13927              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
13928              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
13929            throw new IllegalArgumentException("Invalid new component state: "
13930                    + newState);
13931        }
13932        PackageSetting pkgSetting;
13933        final int uid = Binder.getCallingUid();
13934        final int permission = mContext.checkCallingOrSelfPermission(
13935                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
13936        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
13937        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
13938        boolean sendNow = false;
13939        boolean isApp = (className == null);
13940        String componentName = isApp ? packageName : className;
13941        int packageUid = -1;
13942        ArrayList<String> components;
13943
13944        // writer
13945        synchronized (mPackages) {
13946            pkgSetting = mSettings.mPackages.get(packageName);
13947            if (pkgSetting == null) {
13948                if (className == null) {
13949                    throw new IllegalArgumentException(
13950                            "Unknown package: " + packageName);
13951                }
13952                throw new IllegalArgumentException(
13953                        "Unknown component: " + packageName
13954                        + "/" + className);
13955            }
13956            // Allow root and verify that userId is not being specified by a different user
13957            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
13958                throw new SecurityException(
13959                        "Permission Denial: attempt to change component state from pid="
13960                        + Binder.getCallingPid()
13961                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
13962            }
13963            if (className == null) {
13964                // We're dealing with an application/package level state change
13965                if (pkgSetting.getEnabled(userId) == newState) {
13966                    // Nothing to do
13967                    return;
13968                }
13969                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
13970                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
13971                    // Don't care about who enables an app.
13972                    callingPackage = null;
13973                }
13974                pkgSetting.setEnabled(newState, userId, callingPackage);
13975                // pkgSetting.pkg.mSetEnabled = newState;
13976            } else {
13977                // We're dealing with a component level state change
13978                // First, verify that this is a valid class name.
13979                PackageParser.Package pkg = pkgSetting.pkg;
13980                if (pkg == null || !pkg.hasComponentClassName(className)) {
13981                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
13982                        throw new IllegalArgumentException("Component class " + className
13983                                + " does not exist in " + packageName);
13984                    } else {
13985                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
13986                                + className + " does not exist in " + packageName);
13987                    }
13988                }
13989                switch (newState) {
13990                case COMPONENT_ENABLED_STATE_ENABLED:
13991                    if (!pkgSetting.enableComponentLPw(className, userId)) {
13992                        return;
13993                    }
13994                    break;
13995                case COMPONENT_ENABLED_STATE_DISABLED:
13996                    if (!pkgSetting.disableComponentLPw(className, userId)) {
13997                        return;
13998                    }
13999                    break;
14000                case COMPONENT_ENABLED_STATE_DEFAULT:
14001                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
14002                        return;
14003                    }
14004                    break;
14005                default:
14006                    Slog.e(TAG, "Invalid new component state: " + newState);
14007                    return;
14008                }
14009            }
14010            scheduleWritePackageRestrictionsLocked(userId);
14011            components = mPendingBroadcasts.get(userId, packageName);
14012            final boolean newPackage = components == null;
14013            if (newPackage) {
14014                components = new ArrayList<String>();
14015            }
14016            if (!components.contains(componentName)) {
14017                components.add(componentName);
14018            }
14019            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
14020                sendNow = true;
14021                // Purge entry from pending broadcast list if another one exists already
14022                // since we are sending one right away.
14023                mPendingBroadcasts.remove(userId, packageName);
14024            } else {
14025                if (newPackage) {
14026                    mPendingBroadcasts.put(userId, packageName, components);
14027                }
14028                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
14029                    // Schedule a message
14030                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
14031                }
14032            }
14033        }
14034
14035        long callingId = Binder.clearCallingIdentity();
14036        try {
14037            if (sendNow) {
14038                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
14039                sendPackageChangedBroadcast(packageName,
14040                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
14041            }
14042        } finally {
14043            Binder.restoreCallingIdentity(callingId);
14044        }
14045    }
14046
14047    private void sendPackageChangedBroadcast(String packageName,
14048            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
14049        if (DEBUG_INSTALL)
14050            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
14051                    + componentNames);
14052        Bundle extras = new Bundle(4);
14053        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
14054        String nameList[] = new String[componentNames.size()];
14055        componentNames.toArray(nameList);
14056        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
14057        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
14058        extras.putInt(Intent.EXTRA_UID, packageUid);
14059        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
14060                new int[] {UserHandle.getUserId(packageUid)});
14061    }
14062
14063    @Override
14064    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
14065        if (!sUserManager.exists(userId)) return;
14066        final int uid = Binder.getCallingUid();
14067        final int permission = mContext.checkCallingOrSelfPermission(
14068                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14069        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14070        enforceCrossUserPermission(uid, userId, true, true, "stop package");
14071        // writer
14072        synchronized (mPackages) {
14073            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
14074                    allowedByPermission, uid, userId)) {
14075                scheduleWritePackageRestrictionsLocked(userId);
14076            }
14077        }
14078    }
14079
14080    @Override
14081    public String getInstallerPackageName(String packageName) {
14082        // reader
14083        synchronized (mPackages) {
14084            return mSettings.getInstallerPackageNameLPr(packageName);
14085        }
14086    }
14087
14088    @Override
14089    public int getApplicationEnabledSetting(String packageName, int userId) {
14090        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14091        int uid = Binder.getCallingUid();
14092        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
14093        // reader
14094        synchronized (mPackages) {
14095            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
14096        }
14097    }
14098
14099    @Override
14100    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
14101        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14102        int uid = Binder.getCallingUid();
14103        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
14104        // reader
14105        synchronized (mPackages) {
14106            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
14107        }
14108    }
14109
14110    @Override
14111    public void enterSafeMode() {
14112        enforceSystemOrRoot("Only the system can request entering safe mode");
14113
14114        if (!mSystemReady) {
14115            mSafeMode = true;
14116        }
14117    }
14118
14119    @Override
14120    public void systemReady() {
14121        mSystemReady = true;
14122
14123        // Read the compatibilty setting when the system is ready.
14124        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
14125                mContext.getContentResolver(),
14126                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
14127        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
14128        if (DEBUG_SETTINGS) {
14129            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
14130        }
14131
14132        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
14133
14134        synchronized (mPackages) {
14135            // Verify that all of the preferred activity components actually
14136            // exist.  It is possible for applications to be updated and at
14137            // that point remove a previously declared activity component that
14138            // had been set as a preferred activity.  We try to clean this up
14139            // the next time we encounter that preferred activity, but it is
14140            // possible for the user flow to never be able to return to that
14141            // situation so here we do a sanity check to make sure we haven't
14142            // left any junk around.
14143            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
14144            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14145                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14146                removed.clear();
14147                for (PreferredActivity pa : pir.filterSet()) {
14148                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
14149                        removed.add(pa);
14150                    }
14151                }
14152                if (removed.size() > 0) {
14153                    for (int r=0; r<removed.size(); r++) {
14154                        PreferredActivity pa = removed.get(r);
14155                        Slog.w(TAG, "Removing dangling preferred activity: "
14156                                + pa.mPref.mComponent);
14157                        pir.removeFilter(pa);
14158                    }
14159                    mSettings.writePackageRestrictionsLPr(
14160                            mSettings.mPreferredActivities.keyAt(i));
14161                }
14162            }
14163
14164            for (int userId : UserManagerService.getInstance().getUserIds()) {
14165                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
14166                    grantPermissionsUserIds = ArrayUtils.appendInt(
14167                            grantPermissionsUserIds, userId);
14168                }
14169            }
14170        }
14171        sUserManager.systemReady();
14172
14173        // If we upgraded grant all default permissions before kicking off.
14174        for (int userId : grantPermissionsUserIds) {
14175            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
14176        }
14177
14178        // Kick off any messages waiting for system ready
14179        if (mPostSystemReadyMessages != null) {
14180            for (Message msg : mPostSystemReadyMessages) {
14181                msg.sendToTarget();
14182            }
14183            mPostSystemReadyMessages = null;
14184        }
14185
14186        // Watch for external volumes that come and go over time
14187        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14188        storage.registerListener(mStorageListener);
14189
14190        mInstallerService.systemReady();
14191        mPackageDexOptimizer.systemReady();
14192    }
14193
14194    @Override
14195    public boolean isSafeMode() {
14196        return mSafeMode;
14197    }
14198
14199    @Override
14200    public boolean hasSystemUidErrors() {
14201        return mHasSystemUidErrors;
14202    }
14203
14204    static String arrayToString(int[] array) {
14205        StringBuffer buf = new StringBuffer(128);
14206        buf.append('[');
14207        if (array != null) {
14208            for (int i=0; i<array.length; i++) {
14209                if (i > 0) buf.append(", ");
14210                buf.append(array[i]);
14211            }
14212        }
14213        buf.append(']');
14214        return buf.toString();
14215    }
14216
14217    static class DumpState {
14218        public static final int DUMP_LIBS = 1 << 0;
14219        public static final int DUMP_FEATURES = 1 << 1;
14220        public static final int DUMP_RESOLVERS = 1 << 2;
14221        public static final int DUMP_PERMISSIONS = 1 << 3;
14222        public static final int DUMP_PACKAGES = 1 << 4;
14223        public static final int DUMP_SHARED_USERS = 1 << 5;
14224        public static final int DUMP_MESSAGES = 1 << 6;
14225        public static final int DUMP_PROVIDERS = 1 << 7;
14226        public static final int DUMP_VERIFIERS = 1 << 8;
14227        public static final int DUMP_PREFERRED = 1 << 9;
14228        public static final int DUMP_PREFERRED_XML = 1 << 10;
14229        public static final int DUMP_KEYSETS = 1 << 11;
14230        public static final int DUMP_VERSION = 1 << 12;
14231        public static final int DUMP_INSTALLS = 1 << 13;
14232        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
14233        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
14234
14235        public static final int OPTION_SHOW_FILTERS = 1 << 0;
14236
14237        private int mTypes;
14238
14239        private int mOptions;
14240
14241        private boolean mTitlePrinted;
14242
14243        private SharedUserSetting mSharedUser;
14244
14245        public boolean isDumping(int type) {
14246            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
14247                return true;
14248            }
14249
14250            return (mTypes & type) != 0;
14251        }
14252
14253        public void setDump(int type) {
14254            mTypes |= type;
14255        }
14256
14257        public boolean isOptionEnabled(int option) {
14258            return (mOptions & option) != 0;
14259        }
14260
14261        public void setOptionEnabled(int option) {
14262            mOptions |= option;
14263        }
14264
14265        public boolean onTitlePrinted() {
14266            final boolean printed = mTitlePrinted;
14267            mTitlePrinted = true;
14268            return printed;
14269        }
14270
14271        public boolean getTitlePrinted() {
14272            return mTitlePrinted;
14273        }
14274
14275        public void setTitlePrinted(boolean enabled) {
14276            mTitlePrinted = enabled;
14277        }
14278
14279        public SharedUserSetting getSharedUser() {
14280            return mSharedUser;
14281        }
14282
14283        public void setSharedUser(SharedUserSetting user) {
14284            mSharedUser = user;
14285        }
14286    }
14287
14288    @Override
14289    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
14290        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
14291                != PackageManager.PERMISSION_GRANTED) {
14292            pw.println("Permission Denial: can't dump ActivityManager from from pid="
14293                    + Binder.getCallingPid()
14294                    + ", uid=" + Binder.getCallingUid()
14295                    + " without permission "
14296                    + android.Manifest.permission.DUMP);
14297            return;
14298        }
14299
14300        DumpState dumpState = new DumpState();
14301        boolean fullPreferred = false;
14302        boolean checkin = false;
14303
14304        String packageName = null;
14305        ArraySet<String> permissionNames = null;
14306
14307        int opti = 0;
14308        while (opti < args.length) {
14309            String opt = args[opti];
14310            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
14311                break;
14312            }
14313            opti++;
14314
14315            if ("-a".equals(opt)) {
14316                // Right now we only know how to print all.
14317            } else if ("-h".equals(opt)) {
14318                pw.println("Package manager dump options:");
14319                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
14320                pw.println("    --checkin: dump for a checkin");
14321                pw.println("    -f: print details of intent filters");
14322                pw.println("    -h: print this help");
14323                pw.println("  cmd may be one of:");
14324                pw.println("    l[ibraries]: list known shared libraries");
14325                pw.println("    f[ibraries]: list device features");
14326                pw.println("    k[eysets]: print known keysets");
14327                pw.println("    r[esolvers]: dump intent resolvers");
14328                pw.println("    perm[issions]: dump permissions");
14329                pw.println("    permission [name ...]: dump declaration and use of given permission");
14330                pw.println("    pref[erred]: print preferred package settings");
14331                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
14332                pw.println("    prov[iders]: dump content providers");
14333                pw.println("    p[ackages]: dump installed packages");
14334                pw.println("    s[hared-users]: dump shared user IDs");
14335                pw.println("    m[essages]: print collected runtime messages");
14336                pw.println("    v[erifiers]: print package verifier info");
14337                pw.println("    version: print database version info");
14338                pw.println("    write: write current settings now");
14339                pw.println("    <package.name>: info about given package");
14340                pw.println("    installs: details about install sessions");
14341                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
14342                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
14343                return;
14344            } else if ("--checkin".equals(opt)) {
14345                checkin = true;
14346            } else if ("-f".equals(opt)) {
14347                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14348            } else {
14349                pw.println("Unknown argument: " + opt + "; use -h for help");
14350            }
14351        }
14352
14353        // Is the caller requesting to dump a particular piece of data?
14354        if (opti < args.length) {
14355            String cmd = args[opti];
14356            opti++;
14357            // Is this a package name?
14358            if ("android".equals(cmd) || cmd.contains(".")) {
14359                packageName = cmd;
14360                // When dumping a single package, we always dump all of its
14361                // filter information since the amount of data will be reasonable.
14362                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14363            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
14364                dumpState.setDump(DumpState.DUMP_LIBS);
14365            } else if ("f".equals(cmd) || "features".equals(cmd)) {
14366                dumpState.setDump(DumpState.DUMP_FEATURES);
14367            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
14368                dumpState.setDump(DumpState.DUMP_RESOLVERS);
14369            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
14370                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
14371            } else if ("permission".equals(cmd)) {
14372                if (opti >= args.length) {
14373                    pw.println("Error: permission requires permission name");
14374                    return;
14375                }
14376                permissionNames = new ArraySet<>();
14377                while (opti < args.length) {
14378                    permissionNames.add(args[opti]);
14379                    opti++;
14380                }
14381                dumpState.setDump(DumpState.DUMP_PERMISSIONS
14382                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
14383            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
14384                dumpState.setDump(DumpState.DUMP_PREFERRED);
14385            } else if ("preferred-xml".equals(cmd)) {
14386                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
14387                if (opti < args.length && "--full".equals(args[opti])) {
14388                    fullPreferred = true;
14389                    opti++;
14390                }
14391            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
14392                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
14393            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
14394                dumpState.setDump(DumpState.DUMP_PACKAGES);
14395            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
14396                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
14397            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
14398                dumpState.setDump(DumpState.DUMP_PROVIDERS);
14399            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
14400                dumpState.setDump(DumpState.DUMP_MESSAGES);
14401            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
14402                dumpState.setDump(DumpState.DUMP_VERIFIERS);
14403            } else if ("i".equals(cmd) || "ifv".equals(cmd)
14404                    || "intent-filter-verifiers".equals(cmd)) {
14405                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
14406            } else if ("version".equals(cmd)) {
14407                dumpState.setDump(DumpState.DUMP_VERSION);
14408            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
14409                dumpState.setDump(DumpState.DUMP_KEYSETS);
14410            } else if ("installs".equals(cmd)) {
14411                dumpState.setDump(DumpState.DUMP_INSTALLS);
14412            } else if ("write".equals(cmd)) {
14413                synchronized (mPackages) {
14414                    mSettings.writeLPr();
14415                    pw.println("Settings written.");
14416                    return;
14417                }
14418            }
14419        }
14420
14421        if (checkin) {
14422            pw.println("vers,1");
14423        }
14424
14425        // reader
14426        synchronized (mPackages) {
14427            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
14428                if (!checkin) {
14429                    if (dumpState.onTitlePrinted())
14430                        pw.println();
14431                    pw.println("Database versions:");
14432                    pw.print("  SDK Version:");
14433                    pw.print(" internal=");
14434                    pw.print(mSettings.mInternalSdkPlatform);
14435                    pw.print(" external=");
14436                    pw.println(mSettings.mExternalSdkPlatform);
14437                    pw.print("  DB Version:");
14438                    pw.print(" internal=");
14439                    pw.print(mSettings.mInternalDatabaseVersion);
14440                    pw.print(" external=");
14441                    pw.println(mSettings.mExternalDatabaseVersion);
14442                }
14443            }
14444
14445            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
14446                if (!checkin) {
14447                    if (dumpState.onTitlePrinted())
14448                        pw.println();
14449                    pw.println("Verifiers:");
14450                    pw.print("  Required: ");
14451                    pw.print(mRequiredVerifierPackage);
14452                    pw.print(" (uid=");
14453                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
14454                    pw.println(")");
14455                } else if (mRequiredVerifierPackage != null) {
14456                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
14457                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
14458                }
14459            }
14460
14461            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
14462                    packageName == null) {
14463                if (mIntentFilterVerifierComponent != null) {
14464                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
14465                    if (!checkin) {
14466                        if (dumpState.onTitlePrinted())
14467                            pw.println();
14468                        pw.println("Intent Filter Verifier:");
14469                        pw.print("  Using: ");
14470                        pw.print(verifierPackageName);
14471                        pw.print(" (uid=");
14472                        pw.print(getPackageUid(verifierPackageName, 0));
14473                        pw.println(")");
14474                    } else if (verifierPackageName != null) {
14475                        pw.print("ifv,"); pw.print(verifierPackageName);
14476                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
14477                    }
14478                } else {
14479                    pw.println();
14480                    pw.println("No Intent Filter Verifier available!");
14481                }
14482            }
14483
14484            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
14485                boolean printedHeader = false;
14486                final Iterator<String> it = mSharedLibraries.keySet().iterator();
14487                while (it.hasNext()) {
14488                    String name = it.next();
14489                    SharedLibraryEntry ent = mSharedLibraries.get(name);
14490                    if (!checkin) {
14491                        if (!printedHeader) {
14492                            if (dumpState.onTitlePrinted())
14493                                pw.println();
14494                            pw.println("Libraries:");
14495                            printedHeader = true;
14496                        }
14497                        pw.print("  ");
14498                    } else {
14499                        pw.print("lib,");
14500                    }
14501                    pw.print(name);
14502                    if (!checkin) {
14503                        pw.print(" -> ");
14504                    }
14505                    if (ent.path != null) {
14506                        if (!checkin) {
14507                            pw.print("(jar) ");
14508                            pw.print(ent.path);
14509                        } else {
14510                            pw.print(",jar,");
14511                            pw.print(ent.path);
14512                        }
14513                    } else {
14514                        if (!checkin) {
14515                            pw.print("(apk) ");
14516                            pw.print(ent.apk);
14517                        } else {
14518                            pw.print(",apk,");
14519                            pw.print(ent.apk);
14520                        }
14521                    }
14522                    pw.println();
14523                }
14524            }
14525
14526            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
14527                if (dumpState.onTitlePrinted())
14528                    pw.println();
14529                if (!checkin) {
14530                    pw.println("Features:");
14531                }
14532                Iterator<String> it = mAvailableFeatures.keySet().iterator();
14533                while (it.hasNext()) {
14534                    String name = it.next();
14535                    if (!checkin) {
14536                        pw.print("  ");
14537                    } else {
14538                        pw.print("feat,");
14539                    }
14540                    pw.println(name);
14541                }
14542            }
14543
14544            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
14545                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
14546                        : "Activity Resolver Table:", "  ", packageName,
14547                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14548                    dumpState.setTitlePrinted(true);
14549                }
14550                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
14551                        : "Receiver Resolver Table:", "  ", packageName,
14552                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14553                    dumpState.setTitlePrinted(true);
14554                }
14555                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
14556                        : "Service Resolver Table:", "  ", packageName,
14557                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14558                    dumpState.setTitlePrinted(true);
14559                }
14560                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
14561                        : "Provider Resolver Table:", "  ", packageName,
14562                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14563                    dumpState.setTitlePrinted(true);
14564                }
14565            }
14566
14567            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
14568                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14569                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14570                    int user = mSettings.mPreferredActivities.keyAt(i);
14571                    if (pir.dump(pw,
14572                            dumpState.getTitlePrinted()
14573                                ? "\nPreferred Activities User " + user + ":"
14574                                : "Preferred Activities User " + user + ":", "  ",
14575                            packageName, true, false)) {
14576                        dumpState.setTitlePrinted(true);
14577                    }
14578                }
14579            }
14580
14581            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
14582                pw.flush();
14583                FileOutputStream fout = new FileOutputStream(fd);
14584                BufferedOutputStream str = new BufferedOutputStream(fout);
14585                XmlSerializer serializer = new FastXmlSerializer();
14586                try {
14587                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
14588                    serializer.startDocument(null, true);
14589                    serializer.setFeature(
14590                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
14591                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
14592                    serializer.endDocument();
14593                    serializer.flush();
14594                } catch (IllegalArgumentException e) {
14595                    pw.println("Failed writing: " + e);
14596                } catch (IllegalStateException e) {
14597                    pw.println("Failed writing: " + e);
14598                } catch (IOException e) {
14599                    pw.println("Failed writing: " + e);
14600                }
14601            }
14602
14603            if (!checkin
14604                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
14605                    && packageName == null) {
14606                pw.println();
14607                int count = mSettings.mPackages.size();
14608                if (count == 0) {
14609                    pw.println("No domain preferred apps!");
14610                    pw.println();
14611                } else {
14612                    final String prefix = "  ";
14613                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
14614                    if (allPackageSettings.size() == 0) {
14615                        pw.println("No domain preferred apps!");
14616                        pw.println();
14617                    } else {
14618                        pw.println("Domain preferred apps status:");
14619                        pw.println();
14620                        count = 0;
14621                        for (PackageSetting ps : allPackageSettings) {
14622                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
14623                            if (ivi == null || ivi.getPackageName() == null) continue;
14624                            pw.println(prefix + "Package Name: " + ivi.getPackageName());
14625                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
14626                            pw.println(prefix + "Status: " + ivi.getStatusString());
14627                            pw.println();
14628                            count++;
14629                        }
14630                        if (count == 0) {
14631                            pw.println(prefix + "No domain preferred app status!");
14632                            pw.println();
14633                        }
14634                        for (int userId : sUserManager.getUserIds()) {
14635                            pw.println("Domain preferred apps for User " + userId + ":");
14636                            pw.println();
14637                            count = 0;
14638                            for (PackageSetting ps : allPackageSettings) {
14639                                IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
14640                                if (ivi == null || ivi.getPackageName() == null) {
14641                                    continue;
14642                                }
14643                                final int status = ps.getDomainVerificationStatusForUser(userId);
14644                                if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
14645                                    continue;
14646                                }
14647                                pw.println(prefix + "Package Name: " + ivi.getPackageName());
14648                                pw.println(prefix + "Domains: " + ivi.getDomainsString());
14649                                String statusStr = IntentFilterVerificationInfo.
14650                                        getStatusStringFromValue(status);
14651                                pw.println(prefix + "Status: " + statusStr);
14652                                pw.println();
14653                                count++;
14654                            }
14655                            if (count == 0) {
14656                                pw.println(prefix + "No domain preferred apps!");
14657                                pw.println();
14658                            }
14659                        }
14660                    }
14661                }
14662            }
14663
14664            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
14665                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
14666                if (packageName == null && permissionNames == null) {
14667                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
14668                        if (iperm == 0) {
14669                            if (dumpState.onTitlePrinted())
14670                                pw.println();
14671                            pw.println("AppOp Permissions:");
14672                        }
14673                        pw.print("  AppOp Permission ");
14674                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
14675                        pw.println(":");
14676                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
14677                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
14678                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
14679                        }
14680                    }
14681                }
14682            }
14683
14684            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
14685                boolean printedSomething = false;
14686                for (PackageParser.Provider p : mProviders.mProviders.values()) {
14687                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14688                        continue;
14689                    }
14690                    if (!printedSomething) {
14691                        if (dumpState.onTitlePrinted())
14692                            pw.println();
14693                        pw.println("Registered ContentProviders:");
14694                        printedSomething = true;
14695                    }
14696                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
14697                    pw.print("    "); pw.println(p.toString());
14698                }
14699                printedSomething = false;
14700                for (Map.Entry<String, PackageParser.Provider> entry :
14701                        mProvidersByAuthority.entrySet()) {
14702                    PackageParser.Provider p = entry.getValue();
14703                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14704                        continue;
14705                    }
14706                    if (!printedSomething) {
14707                        if (dumpState.onTitlePrinted())
14708                            pw.println();
14709                        pw.println("ContentProvider Authorities:");
14710                        printedSomething = true;
14711                    }
14712                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
14713                    pw.print("    "); pw.println(p.toString());
14714                    if (p.info != null && p.info.applicationInfo != null) {
14715                        final String appInfo = p.info.applicationInfo.toString();
14716                        pw.print("      applicationInfo="); pw.println(appInfo);
14717                    }
14718                }
14719            }
14720
14721            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
14722                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
14723            }
14724
14725            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
14726                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
14727            }
14728
14729            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
14730                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
14731            }
14732
14733            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
14734                // XXX should handle packageName != null by dumping only install data that
14735                // the given package is involved with.
14736                if (dumpState.onTitlePrinted()) pw.println();
14737                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
14738            }
14739
14740            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
14741                if (dumpState.onTitlePrinted()) pw.println();
14742                mSettings.dumpReadMessagesLPr(pw, dumpState);
14743
14744                pw.println();
14745                pw.println("Package warning messages:");
14746                BufferedReader in = null;
14747                String line = null;
14748                try {
14749                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
14750                    while ((line = in.readLine()) != null) {
14751                        if (line.contains("ignored: updated version")) continue;
14752                        pw.println(line);
14753                    }
14754                } catch (IOException ignored) {
14755                } finally {
14756                    IoUtils.closeQuietly(in);
14757                }
14758            }
14759
14760            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
14761                BufferedReader in = null;
14762                String line = null;
14763                try {
14764                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
14765                    while ((line = in.readLine()) != null) {
14766                        if (line.contains("ignored: updated version")) continue;
14767                        pw.print("msg,");
14768                        pw.println(line);
14769                    }
14770                } catch (IOException ignored) {
14771                } finally {
14772                    IoUtils.closeQuietly(in);
14773                }
14774            }
14775        }
14776    }
14777
14778    // ------- apps on sdcard specific code -------
14779    static final boolean DEBUG_SD_INSTALL = false;
14780
14781    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
14782
14783    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
14784
14785    private boolean mMediaMounted = false;
14786
14787    static String getEncryptKey() {
14788        try {
14789            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
14790                    SD_ENCRYPTION_KEYSTORE_NAME);
14791            if (sdEncKey == null) {
14792                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
14793                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
14794                if (sdEncKey == null) {
14795                    Slog.e(TAG, "Failed to create encryption keys");
14796                    return null;
14797                }
14798            }
14799            return sdEncKey;
14800        } catch (NoSuchAlgorithmException nsae) {
14801            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
14802            return null;
14803        } catch (IOException ioe) {
14804            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
14805            return null;
14806        }
14807    }
14808
14809    /*
14810     * Update media status on PackageManager.
14811     */
14812    @Override
14813    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
14814        int callingUid = Binder.getCallingUid();
14815        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
14816            throw new SecurityException("Media status can only be updated by the system");
14817        }
14818        // reader; this apparently protects mMediaMounted, but should probably
14819        // be a different lock in that case.
14820        synchronized (mPackages) {
14821            Log.i(TAG, "Updating external media status from "
14822                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
14823                    + (mediaStatus ? "mounted" : "unmounted"));
14824            if (DEBUG_SD_INSTALL)
14825                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
14826                        + ", mMediaMounted=" + mMediaMounted);
14827            if (mediaStatus == mMediaMounted) {
14828                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
14829                        : 0, -1);
14830                mHandler.sendMessage(msg);
14831                return;
14832            }
14833            mMediaMounted = mediaStatus;
14834        }
14835        // Queue up an async operation since the package installation may take a
14836        // little while.
14837        mHandler.post(new Runnable() {
14838            public void run() {
14839                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
14840            }
14841        });
14842    }
14843
14844    /**
14845     * Called by MountService when the initial ASECs to scan are available.
14846     * Should block until all the ASEC containers are finished being scanned.
14847     */
14848    public void scanAvailableAsecs() {
14849        updateExternalMediaStatusInner(true, false, false);
14850        if (mShouldRestoreconData) {
14851            SELinuxMMAC.setRestoreconDone();
14852            mShouldRestoreconData = false;
14853        }
14854    }
14855
14856    /*
14857     * Collect information of applications on external media, map them against
14858     * existing containers and update information based on current mount status.
14859     * Please note that we always have to report status if reportStatus has been
14860     * set to true especially when unloading packages.
14861     */
14862    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
14863            boolean externalStorage) {
14864        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
14865        int[] uidArr = EmptyArray.INT;
14866
14867        final String[] list = PackageHelper.getSecureContainerList();
14868        if (ArrayUtils.isEmpty(list)) {
14869            Log.i(TAG, "No secure containers found");
14870        } else {
14871            // Process list of secure containers and categorize them
14872            // as active or stale based on their package internal state.
14873
14874            // reader
14875            synchronized (mPackages) {
14876                for (String cid : list) {
14877                    // Leave stages untouched for now; installer service owns them
14878                    if (PackageInstallerService.isStageName(cid)) continue;
14879
14880                    if (DEBUG_SD_INSTALL)
14881                        Log.i(TAG, "Processing container " + cid);
14882                    String pkgName = getAsecPackageName(cid);
14883                    if (pkgName == null) {
14884                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
14885                        continue;
14886                    }
14887                    if (DEBUG_SD_INSTALL)
14888                        Log.i(TAG, "Looking for pkg : " + pkgName);
14889
14890                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
14891                    if (ps == null) {
14892                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
14893                        continue;
14894                    }
14895
14896                    /*
14897                     * Skip packages that are not external if we're unmounting
14898                     * external storage.
14899                     */
14900                    if (externalStorage && !isMounted && !isExternal(ps)) {
14901                        continue;
14902                    }
14903
14904                    final AsecInstallArgs args = new AsecInstallArgs(cid,
14905                            getAppDexInstructionSets(ps), ps.isForwardLocked());
14906                    // The package status is changed only if the code path
14907                    // matches between settings and the container id.
14908                    if (ps.codePathString != null
14909                            && ps.codePathString.startsWith(args.getCodePath())) {
14910                        if (DEBUG_SD_INSTALL) {
14911                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
14912                                    + " at code path: " + ps.codePathString);
14913                        }
14914
14915                        // We do have a valid package installed on sdcard
14916                        processCids.put(args, ps.codePathString);
14917                        final int uid = ps.appId;
14918                        if (uid != -1) {
14919                            uidArr = ArrayUtils.appendInt(uidArr, uid);
14920                        }
14921                    } else {
14922                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
14923                                + ps.codePathString);
14924                    }
14925                }
14926            }
14927
14928            Arrays.sort(uidArr);
14929        }
14930
14931        // Process packages with valid entries.
14932        if (isMounted) {
14933            if (DEBUG_SD_INSTALL)
14934                Log.i(TAG, "Loading packages");
14935            loadMediaPackages(processCids, uidArr);
14936            startCleaningPackages();
14937            mInstallerService.onSecureContainersAvailable();
14938        } else {
14939            if (DEBUG_SD_INSTALL)
14940                Log.i(TAG, "Unloading packages");
14941            unloadMediaPackages(processCids, uidArr, reportStatus);
14942        }
14943    }
14944
14945    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14946            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
14947        final int size = infos.size();
14948        final String[] packageNames = new String[size];
14949        final int[] packageUids = new int[size];
14950        for (int i = 0; i < size; i++) {
14951            final ApplicationInfo info = infos.get(i);
14952            packageNames[i] = info.packageName;
14953            packageUids[i] = info.uid;
14954        }
14955        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
14956                finishedReceiver);
14957    }
14958
14959    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14960            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
14961        sendResourcesChangedBroadcast(mediaStatus, replacing,
14962                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
14963    }
14964
14965    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14966            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
14967        int size = pkgList.length;
14968        if (size > 0) {
14969            // Send broadcasts here
14970            Bundle extras = new Bundle();
14971            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14972            if (uidArr != null) {
14973                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
14974            }
14975            if (replacing) {
14976                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
14977            }
14978            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
14979                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
14980            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
14981        }
14982    }
14983
14984   /*
14985     * Look at potentially valid container ids from processCids If package
14986     * information doesn't match the one on record or package scanning fails,
14987     * the cid is added to list of removeCids. We currently don't delete stale
14988     * containers.
14989     */
14990    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
14991        ArrayList<String> pkgList = new ArrayList<String>();
14992        Set<AsecInstallArgs> keys = processCids.keySet();
14993
14994        for (AsecInstallArgs args : keys) {
14995            String codePath = processCids.get(args);
14996            if (DEBUG_SD_INSTALL)
14997                Log.i(TAG, "Loading container : " + args.cid);
14998            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14999            try {
15000                // Make sure there are no container errors first.
15001                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
15002                    Slog.e(TAG, "Failed to mount cid : " + args.cid
15003                            + " when installing from sdcard");
15004                    continue;
15005                }
15006                // Check code path here.
15007                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
15008                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
15009                            + " does not match one in settings " + codePath);
15010                    continue;
15011                }
15012                // Parse package
15013                int parseFlags = mDefParseFlags;
15014                if (args.isExternalAsec()) {
15015                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
15016                }
15017                if (args.isFwdLocked()) {
15018                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
15019                }
15020
15021                synchronized (mInstallLock) {
15022                    PackageParser.Package pkg = null;
15023                    try {
15024                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
15025                    } catch (PackageManagerException e) {
15026                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
15027                    }
15028                    // Scan the package
15029                    if (pkg != null) {
15030                        /*
15031                         * TODO why is the lock being held? doPostInstall is
15032                         * called in other places without the lock. This needs
15033                         * to be straightened out.
15034                         */
15035                        // writer
15036                        synchronized (mPackages) {
15037                            retCode = PackageManager.INSTALL_SUCCEEDED;
15038                            pkgList.add(pkg.packageName);
15039                            // Post process args
15040                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
15041                                    pkg.applicationInfo.uid);
15042                        }
15043                    } else {
15044                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
15045                    }
15046                }
15047
15048            } finally {
15049                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
15050                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
15051                }
15052            }
15053        }
15054        // writer
15055        synchronized (mPackages) {
15056            // If the platform SDK has changed since the last time we booted,
15057            // we need to re-grant app permission to catch any new ones that
15058            // appear. This is really a hack, and means that apps can in some
15059            // cases get permissions that the user didn't initially explicitly
15060            // allow... it would be nice to have some better way to handle
15061            // this situation.
15062            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
15063            if (regrantPermissions)
15064                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
15065                        + mSdkVersion + "; regranting permissions for external storage");
15066            mSettings.mExternalSdkPlatform = mSdkVersion;
15067
15068            // Make sure group IDs have been assigned, and any permission
15069            // changes in other apps are accounted for
15070            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
15071                    | (regrantPermissions
15072                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
15073                            : 0));
15074
15075            mSettings.updateExternalDatabaseVersion();
15076
15077            // can downgrade to reader
15078            // Persist settings
15079            mSettings.writeLPr();
15080        }
15081        // Send a broadcast to let everyone know we are done processing
15082        if (pkgList.size() > 0) {
15083            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
15084        }
15085    }
15086
15087   /*
15088     * Utility method to unload a list of specified containers
15089     */
15090    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
15091        // Just unmount all valid containers.
15092        for (AsecInstallArgs arg : cidArgs) {
15093            synchronized (mInstallLock) {
15094                arg.doPostDeleteLI(false);
15095           }
15096       }
15097   }
15098
15099    /*
15100     * Unload packages mounted on external media. This involves deleting package
15101     * data from internal structures, sending broadcasts about diabled packages,
15102     * gc'ing to free up references, unmounting all secure containers
15103     * corresponding to packages on external media, and posting a
15104     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
15105     * that we always have to post this message if status has been requested no
15106     * matter what.
15107     */
15108    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
15109            final boolean reportStatus) {
15110        if (DEBUG_SD_INSTALL)
15111            Log.i(TAG, "unloading media packages");
15112        ArrayList<String> pkgList = new ArrayList<String>();
15113        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
15114        final Set<AsecInstallArgs> keys = processCids.keySet();
15115        for (AsecInstallArgs args : keys) {
15116            String pkgName = args.getPackageName();
15117            if (DEBUG_SD_INSTALL)
15118                Log.i(TAG, "Trying to unload pkg : " + pkgName);
15119            // Delete package internally
15120            PackageRemovedInfo outInfo = new PackageRemovedInfo();
15121            synchronized (mInstallLock) {
15122                boolean res = deletePackageLI(pkgName, null, false, null, null,
15123                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
15124                if (res) {
15125                    pkgList.add(pkgName);
15126                } else {
15127                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
15128                    failedList.add(args);
15129                }
15130            }
15131        }
15132
15133        // reader
15134        synchronized (mPackages) {
15135            // We didn't update the settings after removing each package;
15136            // write them now for all packages.
15137            mSettings.writeLPr();
15138        }
15139
15140        // We have to absolutely send UPDATED_MEDIA_STATUS only
15141        // after confirming that all the receivers processed the ordered
15142        // broadcast when packages get disabled, force a gc to clean things up.
15143        // and unload all the containers.
15144        if (pkgList.size() > 0) {
15145            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
15146                    new IIntentReceiver.Stub() {
15147                public void performReceive(Intent intent, int resultCode, String data,
15148                        Bundle extras, boolean ordered, boolean sticky,
15149                        int sendingUser) throws RemoteException {
15150                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
15151                            reportStatus ? 1 : 0, 1, keys);
15152                    mHandler.sendMessage(msg);
15153                }
15154            });
15155        } else {
15156            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
15157                    keys);
15158            mHandler.sendMessage(msg);
15159        }
15160    }
15161
15162    private void loadPrivatePackages(VolumeInfo vol) {
15163        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
15164        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
15165        synchronized (mInstallLock) {
15166        synchronized (mPackages) {
15167            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15168            for (PackageSetting ps : packages) {
15169                final PackageParser.Package pkg;
15170                try {
15171                    pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null);
15172                    loaded.add(pkg.applicationInfo);
15173                } catch (PackageManagerException e) {
15174                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
15175                }
15176            }
15177
15178            // TODO: regrant any permissions that changed based since original install
15179
15180            mSettings.writeLPr();
15181        }
15182        }
15183
15184        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
15185        sendResourcesChangedBroadcast(true, false, loaded, null);
15186    }
15187
15188    private void unloadPrivatePackages(VolumeInfo vol) {
15189        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
15190        synchronized (mInstallLock) {
15191        synchronized (mPackages) {
15192            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15193            for (PackageSetting ps : packages) {
15194                if (ps.pkg == null) continue;
15195
15196                final ApplicationInfo info = ps.pkg.applicationInfo;
15197                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
15198                if (deletePackageLI(ps.name, null, false, null, null,
15199                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
15200                    unloaded.add(info);
15201                } else {
15202                    Slog.w(TAG, "Failed to unload " + ps.codePath);
15203                }
15204            }
15205
15206            mSettings.writeLPr();
15207        }
15208        }
15209
15210        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
15211        sendResourcesChangedBroadcast(false, false, unloaded, null);
15212    }
15213
15214    private void unfreezePackage(String packageName) {
15215        synchronized (mPackages) {
15216            final PackageSetting ps = mSettings.mPackages.get(packageName);
15217            if (ps != null) {
15218                ps.frozen = false;
15219            }
15220        }
15221    }
15222
15223    @Override
15224    public int movePackage(final String packageName, final String volumeUuid) {
15225        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15226
15227        final int moveId = mNextMoveId.getAndIncrement();
15228        try {
15229            movePackageInternal(packageName, volumeUuid, moveId);
15230        } catch (PackageManagerException e) {
15231            Slog.w(TAG, "Failed to move " + packageName, e);
15232            mMoveCallbacks.notifyStatusChanged(moveId,
15233                    PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15234        }
15235        return moveId;
15236    }
15237
15238    private void movePackageInternal(final String packageName, final String volumeUuid,
15239            final int moveId) throws PackageManagerException {
15240        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
15241        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15242        final PackageManager pm = mContext.getPackageManager();
15243
15244        final boolean currentAsec;
15245        final String currentVolumeUuid;
15246        final File codeFile;
15247        final String installerPackageName;
15248        final String packageAbiOverride;
15249        final int appId;
15250        final String seinfo;
15251        final String label;
15252
15253        // reader
15254        synchronized (mPackages) {
15255            final PackageParser.Package pkg = mPackages.get(packageName);
15256            final PackageSetting ps = mSettings.mPackages.get(packageName);
15257            if (pkg == null || ps == null) {
15258                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
15259            }
15260
15261            if (pkg.applicationInfo.isSystemApp()) {
15262                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
15263                        "Cannot move system application");
15264            }
15265
15266            if (Objects.equals(ps.volumeUuid, volumeUuid)) {
15267                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15268                        "Package already moved to " + volumeUuid);
15269            }
15270
15271            final File probe = new File(pkg.codePath);
15272            final File probeOat = new File(probe, "oat");
15273            if (!probe.isDirectory() || !probeOat.isDirectory()) {
15274                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15275                        "Move only supported for modern cluster style installs");
15276            }
15277
15278            if (ps.frozen) {
15279                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
15280                        "Failed to move already frozen package");
15281            }
15282            ps.frozen = true;
15283
15284            currentAsec = pkg.applicationInfo.isForwardLocked()
15285                    || pkg.applicationInfo.isExternalAsec();
15286            currentVolumeUuid = ps.volumeUuid;
15287            codeFile = new File(pkg.codePath);
15288            installerPackageName = ps.installerPackageName;
15289            packageAbiOverride = ps.cpuAbiOverrideString;
15290            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
15291            seinfo = pkg.applicationInfo.seinfo;
15292            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
15293        }
15294
15295        // Now that we're guarded by frozen state, kill app during move
15296        killApplication(packageName, appId, "move pkg");
15297
15298        final Bundle extras = new Bundle();
15299        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
15300        extras.putString(Intent.EXTRA_TITLE, label);
15301        mMoveCallbacks.notifyCreated(moveId, extras);
15302
15303        int installFlags;
15304        final boolean moveCompleteApp;
15305        final File measurePath;
15306
15307        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
15308            installFlags = INSTALL_INTERNAL;
15309            moveCompleteApp = !currentAsec;
15310            measurePath = Environment.getDataAppDirectory(volumeUuid);
15311        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
15312            installFlags = INSTALL_EXTERNAL;
15313            moveCompleteApp = false;
15314            measurePath = storage.getPrimaryPhysicalVolume().getPath();
15315        } else {
15316            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
15317            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
15318                    || !volume.isMountedWritable()) {
15319                unfreezePackage(packageName);
15320                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15321                        "Move location not mounted private volume");
15322            }
15323
15324            Preconditions.checkState(!currentAsec);
15325
15326            installFlags = INSTALL_INTERNAL;
15327            moveCompleteApp = true;
15328            measurePath = Environment.getDataAppDirectory(volumeUuid);
15329        }
15330
15331        final PackageStats stats = new PackageStats(null, -1);
15332        synchronized (mInstaller) {
15333            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
15334                unfreezePackage(packageName);
15335                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15336                        "Failed to measure package size");
15337            }
15338        }
15339
15340        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
15341                + stats.dataSize);
15342
15343        final long startFreeBytes = measurePath.getFreeSpace();
15344        final long sizeBytes;
15345        if (moveCompleteApp) {
15346            sizeBytes = stats.codeSize + stats.dataSize;
15347        } else {
15348            sizeBytes = stats.codeSize;
15349        }
15350
15351        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
15352            unfreezePackage(packageName);
15353            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15354                    "Not enough free space to move");
15355        }
15356
15357        mMoveCallbacks.notifyStatusChanged(moveId, 10);
15358
15359        final CountDownLatch installedLatch = new CountDownLatch(1);
15360        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
15361            @Override
15362            public void onUserActionRequired(Intent intent) throws RemoteException {
15363                throw new IllegalStateException();
15364            }
15365
15366            @Override
15367            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
15368                    Bundle extras) throws RemoteException {
15369                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
15370                        + PackageManager.installStatusToString(returnCode, msg));
15371
15372                installedLatch.countDown();
15373
15374                // Regardless of success or failure of the move operation,
15375                // always unfreeze the package
15376                unfreezePackage(packageName);
15377
15378                final int status = PackageManager.installStatusToPublicStatus(returnCode);
15379                switch (status) {
15380                    case PackageInstaller.STATUS_SUCCESS:
15381                        mMoveCallbacks.notifyStatusChanged(moveId,
15382                                PackageManager.MOVE_SUCCEEDED);
15383                        break;
15384                    case PackageInstaller.STATUS_FAILURE_STORAGE:
15385                        mMoveCallbacks.notifyStatusChanged(moveId,
15386                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
15387                        break;
15388                    default:
15389                        mMoveCallbacks.notifyStatusChanged(moveId,
15390                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15391                        break;
15392                }
15393            }
15394        };
15395
15396        final MoveInfo move;
15397        if (moveCompleteApp) {
15398            // Kick off a thread to report progress estimates
15399            new Thread() {
15400                @Override
15401                public void run() {
15402                    while (true) {
15403                        try {
15404                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
15405                                break;
15406                            }
15407                        } catch (InterruptedException ignored) {
15408                        }
15409
15410                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
15411                        final int progress = 10 + (int) MathUtils.constrain(
15412                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
15413                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
15414                    }
15415                }
15416            }.start();
15417
15418            final String dataAppName = codeFile.getName();
15419            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
15420                    dataAppName, appId, seinfo);
15421        } else {
15422            move = null;
15423        }
15424
15425        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
15426
15427        final Message msg = mHandler.obtainMessage(INIT_COPY);
15428        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
15429        msg.obj = new InstallParams(origin, move, installObserver, installFlags,
15430                installerPackageName, volumeUuid, null, user, packageAbiOverride);
15431        mHandler.sendMessage(msg);
15432    }
15433
15434    @Override
15435    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
15436        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15437
15438        final int realMoveId = mNextMoveId.getAndIncrement();
15439        final Bundle extras = new Bundle();
15440        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
15441        mMoveCallbacks.notifyCreated(realMoveId, extras);
15442
15443        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
15444            @Override
15445            public void onCreated(int moveId, Bundle extras) {
15446                // Ignored
15447            }
15448
15449            @Override
15450            public void onStatusChanged(int moveId, int status, long estMillis) {
15451                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
15452            }
15453        };
15454
15455        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15456        storage.setPrimaryStorageUuid(volumeUuid, callback);
15457        return realMoveId;
15458    }
15459
15460    @Override
15461    public int getMoveStatus(int moveId) {
15462        mContext.enforceCallingOrSelfPermission(
15463                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15464        return mMoveCallbacks.mLastStatus.get(moveId);
15465    }
15466
15467    @Override
15468    public void registerMoveCallback(IPackageMoveObserver callback) {
15469        mContext.enforceCallingOrSelfPermission(
15470                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15471        mMoveCallbacks.register(callback);
15472    }
15473
15474    @Override
15475    public void unregisterMoveCallback(IPackageMoveObserver callback) {
15476        mContext.enforceCallingOrSelfPermission(
15477                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15478        mMoveCallbacks.unregister(callback);
15479    }
15480
15481    @Override
15482    public boolean setInstallLocation(int loc) {
15483        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
15484                null);
15485        if (getInstallLocation() == loc) {
15486            return true;
15487        }
15488        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
15489                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
15490            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
15491                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
15492            return true;
15493        }
15494        return false;
15495   }
15496
15497    @Override
15498    public int getInstallLocation() {
15499        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15500                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
15501                PackageHelper.APP_INSTALL_AUTO);
15502    }
15503
15504    /** Called by UserManagerService */
15505    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
15506        mDirtyUsers.remove(userHandle);
15507        mSettings.removeUserLPw(userHandle);
15508        mPendingBroadcasts.remove(userHandle);
15509        if (mInstaller != null) {
15510            // Technically, we shouldn't be doing this with the package lock
15511            // held.  However, this is very rare, and there is already so much
15512            // other disk I/O going on, that we'll let it slide for now.
15513            final StorageManager storage = StorageManager.from(mContext);
15514            final List<VolumeInfo> vols = storage.getVolumes();
15515            for (VolumeInfo vol : vols) {
15516                if (vol.getType() == VolumeInfo.TYPE_PRIVATE && vol.isMountedWritable()) {
15517                    final String volumeUuid = vol.getFsUuid();
15518                    if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
15519                    mInstaller.removeUserDataDirs(volumeUuid, userHandle);
15520                }
15521            }
15522        }
15523        mUserNeedsBadging.delete(userHandle);
15524        removeUnusedPackagesLILPw(userManager, userHandle);
15525    }
15526
15527    /**
15528     * We're removing userHandle and would like to remove any downloaded packages
15529     * that are no longer in use by any other user.
15530     * @param userHandle the user being removed
15531     */
15532    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
15533        final boolean DEBUG_CLEAN_APKS = false;
15534        int [] users = userManager.getUserIdsLPr();
15535        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
15536        while (psit.hasNext()) {
15537            PackageSetting ps = psit.next();
15538            if (ps.pkg == null) {
15539                continue;
15540            }
15541            final String packageName = ps.pkg.packageName;
15542            // Skip over if system app
15543            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15544                continue;
15545            }
15546            if (DEBUG_CLEAN_APKS) {
15547                Slog.i(TAG, "Checking package " + packageName);
15548            }
15549            boolean keep = false;
15550            for (int i = 0; i < users.length; i++) {
15551                if (users[i] != userHandle && ps.getInstalled(users[i])) {
15552                    keep = true;
15553                    if (DEBUG_CLEAN_APKS) {
15554                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
15555                                + users[i]);
15556                    }
15557                    break;
15558                }
15559            }
15560            if (!keep) {
15561                if (DEBUG_CLEAN_APKS) {
15562                    Slog.i(TAG, "  Removing package " + packageName);
15563                }
15564                mHandler.post(new Runnable() {
15565                    public void run() {
15566                        deletePackageX(packageName, userHandle, 0);
15567                    } //end run
15568                });
15569            }
15570        }
15571    }
15572
15573    /** Called by UserManagerService */
15574    void createNewUserLILPw(int userHandle, File path) {
15575        if (mInstaller != null) {
15576            mInstaller.createUserConfig(userHandle);
15577            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
15578            applyFactoryDefaultBrowserLPw(userHandle);
15579        }
15580    }
15581
15582    void newUserCreatedLILPw(final int userHandle) {
15583        // We cannot grant the default permissions with a lock held as
15584        // we query providers from other components for default handlers
15585        // such as enabled IMEs, etc.
15586        mHandler.post(new Runnable() {
15587            @Override
15588            public void run() {
15589                mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
15590            }
15591        });
15592    }
15593
15594    @Override
15595    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
15596        mContext.enforceCallingOrSelfPermission(
15597                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15598                "Only package verification agents can read the verifier device identity");
15599
15600        synchronized (mPackages) {
15601            return mSettings.getVerifierDeviceIdentityLPw();
15602        }
15603    }
15604
15605    @Override
15606    public void setPermissionEnforced(String permission, boolean enforced) {
15607        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
15608        if (READ_EXTERNAL_STORAGE.equals(permission)) {
15609            synchronized (mPackages) {
15610                if (mSettings.mReadExternalStorageEnforced == null
15611                        || mSettings.mReadExternalStorageEnforced != enforced) {
15612                    mSettings.mReadExternalStorageEnforced = enforced;
15613                    mSettings.writeLPr();
15614                }
15615            }
15616            // kill any non-foreground processes so we restart them and
15617            // grant/revoke the GID.
15618            final IActivityManager am = ActivityManagerNative.getDefault();
15619            if (am != null) {
15620                final long token = Binder.clearCallingIdentity();
15621                try {
15622                    am.killProcessesBelowForeground("setPermissionEnforcement");
15623                } catch (RemoteException e) {
15624                } finally {
15625                    Binder.restoreCallingIdentity(token);
15626                }
15627            }
15628        } else {
15629            throw new IllegalArgumentException("No selective enforcement for " + permission);
15630        }
15631    }
15632
15633    @Override
15634    @Deprecated
15635    public boolean isPermissionEnforced(String permission) {
15636        return true;
15637    }
15638
15639    @Override
15640    public boolean isStorageLow() {
15641        final long token = Binder.clearCallingIdentity();
15642        try {
15643            final DeviceStorageMonitorInternal
15644                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
15645            if (dsm != null) {
15646                return dsm.isMemoryLow();
15647            } else {
15648                return false;
15649            }
15650        } finally {
15651            Binder.restoreCallingIdentity(token);
15652        }
15653    }
15654
15655    @Override
15656    public IPackageInstaller getPackageInstaller() {
15657        return mInstallerService;
15658    }
15659
15660    private boolean userNeedsBadging(int userId) {
15661        int index = mUserNeedsBadging.indexOfKey(userId);
15662        if (index < 0) {
15663            final UserInfo userInfo;
15664            final long token = Binder.clearCallingIdentity();
15665            try {
15666                userInfo = sUserManager.getUserInfo(userId);
15667            } finally {
15668                Binder.restoreCallingIdentity(token);
15669            }
15670            final boolean b;
15671            if (userInfo != null && userInfo.isManagedProfile()) {
15672                b = true;
15673            } else {
15674                b = false;
15675            }
15676            mUserNeedsBadging.put(userId, b);
15677            return b;
15678        }
15679        return mUserNeedsBadging.valueAt(index);
15680    }
15681
15682    @Override
15683    public KeySet getKeySetByAlias(String packageName, String alias) {
15684        if (packageName == null || alias == null) {
15685            return null;
15686        }
15687        synchronized(mPackages) {
15688            final PackageParser.Package pkg = mPackages.get(packageName);
15689            if (pkg == null) {
15690                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15691                throw new IllegalArgumentException("Unknown package: " + packageName);
15692            }
15693            KeySetManagerService ksms = mSettings.mKeySetManagerService;
15694            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
15695        }
15696    }
15697
15698    @Override
15699    public KeySet getSigningKeySet(String packageName) {
15700        if (packageName == null) {
15701            return null;
15702        }
15703        synchronized(mPackages) {
15704            final PackageParser.Package pkg = mPackages.get(packageName);
15705            if (pkg == null) {
15706                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15707                throw new IllegalArgumentException("Unknown package: " + packageName);
15708            }
15709            if (pkg.applicationInfo.uid != Binder.getCallingUid()
15710                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
15711                throw new SecurityException("May not access signing KeySet of other apps.");
15712            }
15713            KeySetManagerService ksms = mSettings.mKeySetManagerService;
15714            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
15715        }
15716    }
15717
15718    @Override
15719    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
15720        if (packageName == null || ks == null) {
15721            return false;
15722        }
15723        synchronized(mPackages) {
15724            final PackageParser.Package pkg = mPackages.get(packageName);
15725            if (pkg == null) {
15726                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15727                throw new IllegalArgumentException("Unknown package: " + packageName);
15728            }
15729            IBinder ksh = ks.getToken();
15730            if (ksh instanceof KeySetHandle) {
15731                KeySetManagerService ksms = mSettings.mKeySetManagerService;
15732                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
15733            }
15734            return false;
15735        }
15736    }
15737
15738    @Override
15739    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
15740        if (packageName == null || ks == null) {
15741            return false;
15742        }
15743        synchronized(mPackages) {
15744            final PackageParser.Package pkg = mPackages.get(packageName);
15745            if (pkg == null) {
15746                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15747                throw new IllegalArgumentException("Unknown package: " + packageName);
15748            }
15749            IBinder ksh = ks.getToken();
15750            if (ksh instanceof KeySetHandle) {
15751                KeySetManagerService ksms = mSettings.mKeySetManagerService;
15752                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
15753            }
15754            return false;
15755        }
15756    }
15757
15758    public void getUsageStatsIfNoPackageUsageInfo() {
15759        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
15760            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
15761            if (usm == null) {
15762                throw new IllegalStateException("UsageStatsManager must be initialized");
15763            }
15764            long now = System.currentTimeMillis();
15765            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
15766            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
15767                String packageName = entry.getKey();
15768                PackageParser.Package pkg = mPackages.get(packageName);
15769                if (pkg == null) {
15770                    continue;
15771                }
15772                UsageStats usage = entry.getValue();
15773                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
15774                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
15775            }
15776        }
15777    }
15778
15779    /**
15780     * Check and throw if the given before/after packages would be considered a
15781     * downgrade.
15782     */
15783    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
15784            throws PackageManagerException {
15785        if (after.versionCode < before.mVersionCode) {
15786            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15787                    "Update version code " + after.versionCode + " is older than current "
15788                    + before.mVersionCode);
15789        } else if (after.versionCode == before.mVersionCode) {
15790            if (after.baseRevisionCode < before.baseRevisionCode) {
15791                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15792                        "Update base revision code " + after.baseRevisionCode
15793                        + " is older than current " + before.baseRevisionCode);
15794            }
15795
15796            if (!ArrayUtils.isEmpty(after.splitNames)) {
15797                for (int i = 0; i < after.splitNames.length; i++) {
15798                    final String splitName = after.splitNames[i];
15799                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
15800                    if (j != -1) {
15801                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
15802                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15803                                    "Update split " + splitName + " revision code "
15804                                    + after.splitRevisionCodes[i] + " is older than current "
15805                                    + before.splitRevisionCodes[j]);
15806                        }
15807                    }
15808                }
15809            }
15810        }
15811    }
15812
15813    private static class MoveCallbacks extends Handler {
15814        private static final int MSG_CREATED = 1;
15815        private static final int MSG_STATUS_CHANGED = 2;
15816
15817        private final RemoteCallbackList<IPackageMoveObserver>
15818                mCallbacks = new RemoteCallbackList<>();
15819
15820        private final SparseIntArray mLastStatus = new SparseIntArray();
15821
15822        public MoveCallbacks(Looper looper) {
15823            super(looper);
15824        }
15825
15826        public void register(IPackageMoveObserver callback) {
15827            mCallbacks.register(callback);
15828        }
15829
15830        public void unregister(IPackageMoveObserver callback) {
15831            mCallbacks.unregister(callback);
15832        }
15833
15834        @Override
15835        public void handleMessage(Message msg) {
15836            final SomeArgs args = (SomeArgs) msg.obj;
15837            final int n = mCallbacks.beginBroadcast();
15838            for (int i = 0; i < n; i++) {
15839                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
15840                try {
15841                    invokeCallback(callback, msg.what, args);
15842                } catch (RemoteException ignored) {
15843                }
15844            }
15845            mCallbacks.finishBroadcast();
15846            args.recycle();
15847        }
15848
15849        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
15850                throws RemoteException {
15851            switch (what) {
15852                case MSG_CREATED: {
15853                    callback.onCreated(args.argi1, (Bundle) args.arg2);
15854                    break;
15855                }
15856                case MSG_STATUS_CHANGED: {
15857                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
15858                    break;
15859                }
15860            }
15861        }
15862
15863        private void notifyCreated(int moveId, Bundle extras) {
15864            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
15865
15866            final SomeArgs args = SomeArgs.obtain();
15867            args.argi1 = moveId;
15868            args.arg2 = extras;
15869            obtainMessage(MSG_CREATED, args).sendToTarget();
15870        }
15871
15872        private void notifyStatusChanged(int moveId, int status) {
15873            notifyStatusChanged(moveId, status, -1);
15874        }
15875
15876        private void notifyStatusChanged(int moveId, int status, long estMillis) {
15877            Slog.v(TAG, "Move " + moveId + " status " + status);
15878
15879            final SomeArgs args = SomeArgs.obtain();
15880            args.argi1 = moveId;
15881            args.argi2 = status;
15882            args.arg3 = estMillis;
15883            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
15884
15885            synchronized (mLastStatus) {
15886                mLastStatus.put(moveId, status);
15887            }
15888        }
15889    }
15890
15891    private final class OnPermissionChangeListeners extends Handler {
15892        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
15893
15894        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
15895                new RemoteCallbackList<>();
15896
15897        public OnPermissionChangeListeners(Looper looper) {
15898            super(looper);
15899        }
15900
15901        @Override
15902        public void handleMessage(Message msg) {
15903            switch (msg.what) {
15904                case MSG_ON_PERMISSIONS_CHANGED: {
15905                    final int uid = msg.arg1;
15906                    handleOnPermissionsChanged(uid);
15907                } break;
15908            }
15909        }
15910
15911        public void addListenerLocked(IOnPermissionsChangeListener listener) {
15912            mPermissionListeners.register(listener);
15913
15914        }
15915
15916        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
15917            mPermissionListeners.unregister(listener);
15918        }
15919
15920        public void onPermissionsChanged(int uid) {
15921            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
15922                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
15923            }
15924        }
15925
15926        private void handleOnPermissionsChanged(int uid) {
15927            final int count = mPermissionListeners.beginBroadcast();
15928            try {
15929                for (int i = 0; i < count; i++) {
15930                    IOnPermissionsChangeListener callback = mPermissionListeners
15931                            .getBroadcastItem(i);
15932                    try {
15933                        callback.onPermissionsChanged(uid);
15934                    } catch (RemoteException e) {
15935                        Log.e(TAG, "Permission listener is dead", e);
15936                    }
15937                }
15938            } finally {
15939                mPermissionListeners.finishBroadcast();
15940            }
15941        }
15942    }
15943
15944    private class PackageManagerInternalImpl extends PackageManagerInternal {
15945        @Override
15946        public void setLocationPackagesProvider(PackagesProvider provider) {
15947            synchronized (mPackages) {
15948                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
15949            }
15950        }
15951
15952        @Override
15953        public void setImePackagesProvider(PackagesProvider provider) {
15954            synchronized (mPackages) {
15955                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
15956            }
15957        }
15958
15959        @Override
15960        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
15961            synchronized (mPackages) {
15962                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
15963            }
15964        }
15965
15966        @Override
15967        public void setSmsAppPackagesProvider(PackagesProvider provider) {
15968            synchronized (mPackages) {
15969                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
15970            }
15971        }
15972
15973        @Override
15974        public void setDialerAppPackagesProvider(PackagesProvider provider) {
15975            synchronized (mPackages) {
15976                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
15977            }
15978        }
15979
15980        @Override
15981        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
15982            synchronized (mPackages) {
15983                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
15984                        packageName, userId);
15985            }
15986        }
15987
15988        @Override
15989        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
15990            synchronized (mPackages) {
15991                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
15992                        packageName, userId);
15993            }
15994        }
15995    }
15996
15997    @Override
15998    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
15999        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
16000        synchronized (mPackages) {
16001            mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
16002                    packageNames, userId);
16003        }
16004    }
16005
16006    private static void enforceSystemOrPhoneCaller(String tag) {
16007        int callingUid = Binder.getCallingUid();
16008        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
16009            throw new SecurityException(
16010                    "Cannot call " + tag + " from UID " + callingUid);
16011        }
16012    }
16013}
16014