PackageManagerService.java revision 99b6043dad9d215cf15810b885b6b8c215dd5b5a
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_DEVELOPMENT) != 0) {
8359            // For development permissions, a development permission
8360            // is granted only if it was already granted.
8361            allowed = origPermissions.hasInstallPermission(perm);
8362        }
8363        return allowed;
8364    }
8365
8366    final class ActivityIntentResolver
8367            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8368        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8369                boolean defaultOnly, int userId) {
8370            if (!sUserManager.exists(userId)) return null;
8371            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8372            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8373        }
8374
8375        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8376                int userId) {
8377            if (!sUserManager.exists(userId)) return null;
8378            mFlags = flags;
8379            return super.queryIntent(intent, resolvedType,
8380                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8381        }
8382
8383        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8384                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8385            if (!sUserManager.exists(userId)) return null;
8386            if (packageActivities == null) {
8387                return null;
8388            }
8389            mFlags = flags;
8390            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8391            final int N = packageActivities.size();
8392            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8393                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8394
8395            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8396            for (int i = 0; i < N; ++i) {
8397                intentFilters = packageActivities.get(i).intents;
8398                if (intentFilters != null && intentFilters.size() > 0) {
8399                    PackageParser.ActivityIntentInfo[] array =
8400                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
8401                    intentFilters.toArray(array);
8402                    listCut.add(array);
8403                }
8404            }
8405            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8406        }
8407
8408        public final void addActivity(PackageParser.Activity a, String type) {
8409            final boolean systemApp = a.info.applicationInfo.isSystemApp();
8410            mActivities.put(a.getComponentName(), a);
8411            if (DEBUG_SHOW_INFO)
8412                Log.v(
8413                TAG, "  " + type + " " +
8414                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8415            if (DEBUG_SHOW_INFO)
8416                Log.v(TAG, "    Class=" + a.info.name);
8417            final int NI = a.intents.size();
8418            for (int j=0; j<NI; j++) {
8419                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8420                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
8421                    intent.setPriority(0);
8422                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
8423                            + a.className + " with priority > 0, forcing to 0");
8424                }
8425                if (DEBUG_SHOW_INFO) {
8426                    Log.v(TAG, "    IntentFilter:");
8427                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8428                }
8429                if (!intent.debugCheck()) {
8430                    Log.w(TAG, "==> For Activity " + a.info.name);
8431                }
8432                addFilter(intent);
8433            }
8434        }
8435
8436        public final void removeActivity(PackageParser.Activity a, String type) {
8437            mActivities.remove(a.getComponentName());
8438            if (DEBUG_SHOW_INFO) {
8439                Log.v(TAG, "  " + type + " "
8440                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
8441                                : a.info.name) + ":");
8442                Log.v(TAG, "    Class=" + a.info.name);
8443            }
8444            final int NI = a.intents.size();
8445            for (int j=0; j<NI; j++) {
8446                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8447                if (DEBUG_SHOW_INFO) {
8448                    Log.v(TAG, "    IntentFilter:");
8449                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8450                }
8451                removeFilter(intent);
8452            }
8453        }
8454
8455        @Override
8456        protected boolean allowFilterResult(
8457                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
8458            ActivityInfo filterAi = filter.activity.info;
8459            for (int i=dest.size()-1; i>=0; i--) {
8460                ActivityInfo destAi = dest.get(i).activityInfo;
8461                if (destAi.name == filterAi.name
8462                        && destAi.packageName == filterAi.packageName) {
8463                    return false;
8464                }
8465            }
8466            return true;
8467        }
8468
8469        @Override
8470        protected ActivityIntentInfo[] newArray(int size) {
8471            return new ActivityIntentInfo[size];
8472        }
8473
8474        @Override
8475        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
8476            if (!sUserManager.exists(userId)) return true;
8477            PackageParser.Package p = filter.activity.owner;
8478            if (p != null) {
8479                PackageSetting ps = (PackageSetting)p.mExtras;
8480                if (ps != null) {
8481                    // System apps are never considered stopped for purposes of
8482                    // filtering, because there may be no way for the user to
8483                    // actually re-launch them.
8484                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
8485                            && ps.getStopped(userId);
8486                }
8487            }
8488            return false;
8489        }
8490
8491        @Override
8492        protected boolean isPackageForFilter(String packageName,
8493                PackageParser.ActivityIntentInfo info) {
8494            return packageName.equals(info.activity.owner.packageName);
8495        }
8496
8497        @Override
8498        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
8499                int match, int userId) {
8500            if (!sUserManager.exists(userId)) return null;
8501            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
8502                return null;
8503            }
8504            final PackageParser.Activity activity = info.activity;
8505            if (mSafeMode && (activity.info.applicationInfo.flags
8506                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8507                return null;
8508            }
8509            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
8510            if (ps == null) {
8511                return null;
8512            }
8513            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
8514                    ps.readUserState(userId), userId);
8515            if (ai == null) {
8516                return null;
8517            }
8518            final ResolveInfo res = new ResolveInfo();
8519            res.activityInfo = ai;
8520            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8521                res.filter = info;
8522            }
8523            if (info != null) {
8524                res.handleAllWebDataURI = info.handleAllWebDataURI();
8525            }
8526            res.priority = info.getPriority();
8527            res.preferredOrder = activity.owner.mPreferredOrder;
8528            //System.out.println("Result: " + res.activityInfo.className +
8529            //                   " = " + res.priority);
8530            res.match = match;
8531            res.isDefault = info.hasDefault;
8532            res.labelRes = info.labelRes;
8533            res.nonLocalizedLabel = info.nonLocalizedLabel;
8534            if (userNeedsBadging(userId)) {
8535                res.noResourceId = true;
8536            } else {
8537                res.icon = info.icon;
8538            }
8539            res.iconResourceId = info.icon;
8540            res.system = res.activityInfo.applicationInfo.isSystemApp();
8541            return res;
8542        }
8543
8544        @Override
8545        protected void sortResults(List<ResolveInfo> results) {
8546            Collections.sort(results, mResolvePrioritySorter);
8547        }
8548
8549        @Override
8550        protected void dumpFilter(PrintWriter out, String prefix,
8551                PackageParser.ActivityIntentInfo filter) {
8552            out.print(prefix); out.print(
8553                    Integer.toHexString(System.identityHashCode(filter.activity)));
8554                    out.print(' ');
8555                    filter.activity.printComponentShortName(out);
8556                    out.print(" filter ");
8557                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8558        }
8559
8560        @Override
8561        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
8562            return filter.activity;
8563        }
8564
8565        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8566            PackageParser.Activity activity = (PackageParser.Activity)label;
8567            out.print(prefix); out.print(
8568                    Integer.toHexString(System.identityHashCode(activity)));
8569                    out.print(' ');
8570                    activity.printComponentShortName(out);
8571            if (count > 1) {
8572                out.print(" ("); out.print(count); out.print(" filters)");
8573            }
8574            out.println();
8575        }
8576
8577//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8578//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8579//            final List<ResolveInfo> retList = Lists.newArrayList();
8580//            while (i.hasNext()) {
8581//                final ResolveInfo resolveInfo = i.next();
8582//                if (isEnabledLP(resolveInfo.activityInfo)) {
8583//                    retList.add(resolveInfo);
8584//                }
8585//            }
8586//            return retList;
8587//        }
8588
8589        // Keys are String (activity class name), values are Activity.
8590        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
8591                = new ArrayMap<ComponentName, PackageParser.Activity>();
8592        private int mFlags;
8593    }
8594
8595    private final class ServiceIntentResolver
8596            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
8597        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8598                boolean defaultOnly, int userId) {
8599            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8600            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8601        }
8602
8603        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8604                int userId) {
8605            if (!sUserManager.exists(userId)) return null;
8606            mFlags = flags;
8607            return super.queryIntent(intent, resolvedType,
8608                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8609        }
8610
8611        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8612                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
8613            if (!sUserManager.exists(userId)) return null;
8614            if (packageServices == null) {
8615                return null;
8616            }
8617            mFlags = flags;
8618            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8619            final int N = packageServices.size();
8620            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
8621                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
8622
8623            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
8624            for (int i = 0; i < N; ++i) {
8625                intentFilters = packageServices.get(i).intents;
8626                if (intentFilters != null && intentFilters.size() > 0) {
8627                    PackageParser.ServiceIntentInfo[] array =
8628                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
8629                    intentFilters.toArray(array);
8630                    listCut.add(array);
8631                }
8632            }
8633            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8634        }
8635
8636        public final void addService(PackageParser.Service s) {
8637            mServices.put(s.getComponentName(), s);
8638            if (DEBUG_SHOW_INFO) {
8639                Log.v(TAG, "  "
8640                        + (s.info.nonLocalizedLabel != null
8641                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8642                Log.v(TAG, "    Class=" + s.info.name);
8643            }
8644            final int NI = s.intents.size();
8645            int j;
8646            for (j=0; j<NI; j++) {
8647                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8648                if (DEBUG_SHOW_INFO) {
8649                    Log.v(TAG, "    IntentFilter:");
8650                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8651                }
8652                if (!intent.debugCheck()) {
8653                    Log.w(TAG, "==> For Service " + s.info.name);
8654                }
8655                addFilter(intent);
8656            }
8657        }
8658
8659        public final void removeService(PackageParser.Service s) {
8660            mServices.remove(s.getComponentName());
8661            if (DEBUG_SHOW_INFO) {
8662                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
8663                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8664                Log.v(TAG, "    Class=" + s.info.name);
8665            }
8666            final int NI = s.intents.size();
8667            int j;
8668            for (j=0; j<NI; j++) {
8669                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8670                if (DEBUG_SHOW_INFO) {
8671                    Log.v(TAG, "    IntentFilter:");
8672                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8673                }
8674                removeFilter(intent);
8675            }
8676        }
8677
8678        @Override
8679        protected boolean allowFilterResult(
8680                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
8681            ServiceInfo filterSi = filter.service.info;
8682            for (int i=dest.size()-1; i>=0; i--) {
8683                ServiceInfo destAi = dest.get(i).serviceInfo;
8684                if (destAi.name == filterSi.name
8685                        && destAi.packageName == filterSi.packageName) {
8686                    return false;
8687                }
8688            }
8689            return true;
8690        }
8691
8692        @Override
8693        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
8694            return new PackageParser.ServiceIntentInfo[size];
8695        }
8696
8697        @Override
8698        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
8699            if (!sUserManager.exists(userId)) return true;
8700            PackageParser.Package p = filter.service.owner;
8701            if (p != null) {
8702                PackageSetting ps = (PackageSetting)p.mExtras;
8703                if (ps != null) {
8704                    // System apps are never considered stopped for purposes of
8705                    // filtering, because there may be no way for the user to
8706                    // actually re-launch them.
8707                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8708                            && ps.getStopped(userId);
8709                }
8710            }
8711            return false;
8712        }
8713
8714        @Override
8715        protected boolean isPackageForFilter(String packageName,
8716                PackageParser.ServiceIntentInfo info) {
8717            return packageName.equals(info.service.owner.packageName);
8718        }
8719
8720        @Override
8721        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
8722                int match, int userId) {
8723            if (!sUserManager.exists(userId)) return null;
8724            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
8725            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
8726                return null;
8727            }
8728            final PackageParser.Service service = info.service;
8729            if (mSafeMode && (service.info.applicationInfo.flags
8730                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8731                return null;
8732            }
8733            PackageSetting ps = (PackageSetting) service.owner.mExtras;
8734            if (ps == null) {
8735                return null;
8736            }
8737            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
8738                    ps.readUserState(userId), userId);
8739            if (si == null) {
8740                return null;
8741            }
8742            final ResolveInfo res = new ResolveInfo();
8743            res.serviceInfo = si;
8744            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8745                res.filter = filter;
8746            }
8747            res.priority = info.getPriority();
8748            res.preferredOrder = service.owner.mPreferredOrder;
8749            res.match = match;
8750            res.isDefault = info.hasDefault;
8751            res.labelRes = info.labelRes;
8752            res.nonLocalizedLabel = info.nonLocalizedLabel;
8753            res.icon = info.icon;
8754            res.system = res.serviceInfo.applicationInfo.isSystemApp();
8755            return res;
8756        }
8757
8758        @Override
8759        protected void sortResults(List<ResolveInfo> results) {
8760            Collections.sort(results, mResolvePrioritySorter);
8761        }
8762
8763        @Override
8764        protected void dumpFilter(PrintWriter out, String prefix,
8765                PackageParser.ServiceIntentInfo filter) {
8766            out.print(prefix); out.print(
8767                    Integer.toHexString(System.identityHashCode(filter.service)));
8768                    out.print(' ');
8769                    filter.service.printComponentShortName(out);
8770                    out.print(" filter ");
8771                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8772        }
8773
8774        @Override
8775        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
8776            return filter.service;
8777        }
8778
8779        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8780            PackageParser.Service service = (PackageParser.Service)label;
8781            out.print(prefix); out.print(
8782                    Integer.toHexString(System.identityHashCode(service)));
8783                    out.print(' ');
8784                    service.printComponentShortName(out);
8785            if (count > 1) {
8786                out.print(" ("); out.print(count); out.print(" filters)");
8787            }
8788            out.println();
8789        }
8790
8791//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8792//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8793//            final List<ResolveInfo> retList = Lists.newArrayList();
8794//            while (i.hasNext()) {
8795//                final ResolveInfo resolveInfo = (ResolveInfo) i;
8796//                if (isEnabledLP(resolveInfo.serviceInfo)) {
8797//                    retList.add(resolveInfo);
8798//                }
8799//            }
8800//            return retList;
8801//        }
8802
8803        // Keys are String (activity class name), values are Activity.
8804        private final ArrayMap<ComponentName, PackageParser.Service> mServices
8805                = new ArrayMap<ComponentName, PackageParser.Service>();
8806        private int mFlags;
8807    };
8808
8809    private final class ProviderIntentResolver
8810            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
8811        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8812                boolean defaultOnly, int userId) {
8813            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8814            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8815        }
8816
8817        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8818                int userId) {
8819            if (!sUserManager.exists(userId))
8820                return null;
8821            mFlags = flags;
8822            return super.queryIntent(intent, resolvedType,
8823                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8824        }
8825
8826        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8827                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
8828            if (!sUserManager.exists(userId))
8829                return null;
8830            if (packageProviders == null) {
8831                return null;
8832            }
8833            mFlags = flags;
8834            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
8835            final int N = packageProviders.size();
8836            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
8837                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
8838
8839            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
8840            for (int i = 0; i < N; ++i) {
8841                intentFilters = packageProviders.get(i).intents;
8842                if (intentFilters != null && intentFilters.size() > 0) {
8843                    PackageParser.ProviderIntentInfo[] array =
8844                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
8845                    intentFilters.toArray(array);
8846                    listCut.add(array);
8847                }
8848            }
8849            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8850        }
8851
8852        public final void addProvider(PackageParser.Provider p) {
8853            if (mProviders.containsKey(p.getComponentName())) {
8854                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
8855                return;
8856            }
8857
8858            mProviders.put(p.getComponentName(), p);
8859            if (DEBUG_SHOW_INFO) {
8860                Log.v(TAG, "  "
8861                        + (p.info.nonLocalizedLabel != null
8862                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
8863                Log.v(TAG, "    Class=" + p.info.name);
8864            }
8865            final int NI = p.intents.size();
8866            int j;
8867            for (j = 0; j < NI; j++) {
8868                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
8869                if (DEBUG_SHOW_INFO) {
8870                    Log.v(TAG, "    IntentFilter:");
8871                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8872                }
8873                if (!intent.debugCheck()) {
8874                    Log.w(TAG, "==> For Provider " + p.info.name);
8875                }
8876                addFilter(intent);
8877            }
8878        }
8879
8880        public final void removeProvider(PackageParser.Provider p) {
8881            mProviders.remove(p.getComponentName());
8882            if (DEBUG_SHOW_INFO) {
8883                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
8884                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
8885                Log.v(TAG, "    Class=" + p.info.name);
8886            }
8887            final int NI = p.intents.size();
8888            int j;
8889            for (j = 0; j < NI; j++) {
8890                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
8891                if (DEBUG_SHOW_INFO) {
8892                    Log.v(TAG, "    IntentFilter:");
8893                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8894                }
8895                removeFilter(intent);
8896            }
8897        }
8898
8899        @Override
8900        protected boolean allowFilterResult(
8901                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
8902            ProviderInfo filterPi = filter.provider.info;
8903            for (int i = dest.size() - 1; i >= 0; i--) {
8904                ProviderInfo destPi = dest.get(i).providerInfo;
8905                if (destPi.name == filterPi.name
8906                        && destPi.packageName == filterPi.packageName) {
8907                    return false;
8908                }
8909            }
8910            return true;
8911        }
8912
8913        @Override
8914        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
8915            return new PackageParser.ProviderIntentInfo[size];
8916        }
8917
8918        @Override
8919        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
8920            if (!sUserManager.exists(userId))
8921                return true;
8922            PackageParser.Package p = filter.provider.owner;
8923            if (p != null) {
8924                PackageSetting ps = (PackageSetting) p.mExtras;
8925                if (ps != null) {
8926                    // System apps are never considered stopped for purposes of
8927                    // filtering, because there may be no way for the user to
8928                    // actually re-launch them.
8929                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8930                            && ps.getStopped(userId);
8931                }
8932            }
8933            return false;
8934        }
8935
8936        @Override
8937        protected boolean isPackageForFilter(String packageName,
8938                PackageParser.ProviderIntentInfo info) {
8939            return packageName.equals(info.provider.owner.packageName);
8940        }
8941
8942        @Override
8943        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
8944                int match, int userId) {
8945            if (!sUserManager.exists(userId))
8946                return null;
8947            final PackageParser.ProviderIntentInfo info = filter;
8948            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
8949                return null;
8950            }
8951            final PackageParser.Provider provider = info.provider;
8952            if (mSafeMode && (provider.info.applicationInfo.flags
8953                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
8954                return null;
8955            }
8956            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
8957            if (ps == null) {
8958                return null;
8959            }
8960            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
8961                    ps.readUserState(userId), userId);
8962            if (pi == null) {
8963                return null;
8964            }
8965            final ResolveInfo res = new ResolveInfo();
8966            res.providerInfo = pi;
8967            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
8968                res.filter = filter;
8969            }
8970            res.priority = info.getPriority();
8971            res.preferredOrder = provider.owner.mPreferredOrder;
8972            res.match = match;
8973            res.isDefault = info.hasDefault;
8974            res.labelRes = info.labelRes;
8975            res.nonLocalizedLabel = info.nonLocalizedLabel;
8976            res.icon = info.icon;
8977            res.system = res.providerInfo.applicationInfo.isSystemApp();
8978            return res;
8979        }
8980
8981        @Override
8982        protected void sortResults(List<ResolveInfo> results) {
8983            Collections.sort(results, mResolvePrioritySorter);
8984        }
8985
8986        @Override
8987        protected void dumpFilter(PrintWriter out, String prefix,
8988                PackageParser.ProviderIntentInfo filter) {
8989            out.print(prefix);
8990            out.print(
8991                    Integer.toHexString(System.identityHashCode(filter.provider)));
8992            out.print(' ');
8993            filter.provider.printComponentShortName(out);
8994            out.print(" filter ");
8995            out.println(Integer.toHexString(System.identityHashCode(filter)));
8996        }
8997
8998        @Override
8999        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9000            return filter.provider;
9001        }
9002
9003        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9004            PackageParser.Provider provider = (PackageParser.Provider)label;
9005            out.print(prefix); out.print(
9006                    Integer.toHexString(System.identityHashCode(provider)));
9007                    out.print(' ');
9008                    provider.printComponentShortName(out);
9009            if (count > 1) {
9010                out.print(" ("); out.print(count); out.print(" filters)");
9011            }
9012            out.println();
9013        }
9014
9015        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9016                = new ArrayMap<ComponentName, PackageParser.Provider>();
9017        private int mFlags;
9018    };
9019
9020    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9021            new Comparator<ResolveInfo>() {
9022        public int compare(ResolveInfo r1, ResolveInfo r2) {
9023            int v1 = r1.priority;
9024            int v2 = r2.priority;
9025            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9026            if (v1 != v2) {
9027                return (v1 > v2) ? -1 : 1;
9028            }
9029            v1 = r1.preferredOrder;
9030            v2 = r2.preferredOrder;
9031            if (v1 != v2) {
9032                return (v1 > v2) ? -1 : 1;
9033            }
9034            if (r1.isDefault != r2.isDefault) {
9035                return r1.isDefault ? -1 : 1;
9036            }
9037            v1 = r1.match;
9038            v2 = r2.match;
9039            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9040            if (v1 != v2) {
9041                return (v1 > v2) ? -1 : 1;
9042            }
9043            if (r1.system != r2.system) {
9044                return r1.system ? -1 : 1;
9045            }
9046            return 0;
9047        }
9048    };
9049
9050    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9051            new Comparator<ProviderInfo>() {
9052        public int compare(ProviderInfo p1, ProviderInfo p2) {
9053            final int v1 = p1.initOrder;
9054            final int v2 = p2.initOrder;
9055            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9056        }
9057    };
9058
9059    final void sendPackageBroadcast(final String action, final String pkg,
9060            final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
9061            final int[] userIds) {
9062        mHandler.post(new Runnable() {
9063            @Override
9064            public void run() {
9065                try {
9066                    final IActivityManager am = ActivityManagerNative.getDefault();
9067                    if (am == null) return;
9068                    final int[] resolvedUserIds;
9069                    if (userIds == null) {
9070                        resolvedUserIds = am.getRunningUserIds();
9071                    } else {
9072                        resolvedUserIds = userIds;
9073                    }
9074                    for (int id : resolvedUserIds) {
9075                        final Intent intent = new Intent(action,
9076                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9077                        if (extras != null) {
9078                            intent.putExtras(extras);
9079                        }
9080                        if (targetPkg != null) {
9081                            intent.setPackage(targetPkg);
9082                        }
9083                        // Modify the UID when posting to other users
9084                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9085                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9086                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9087                            intent.putExtra(Intent.EXTRA_UID, uid);
9088                        }
9089                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9090                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
9091                        if (DEBUG_BROADCASTS) {
9092                            RuntimeException here = new RuntimeException("here");
9093                            here.fillInStackTrace();
9094                            Slog.d(TAG, "Sending to user " + id + ": "
9095                                    + intent.toShortString(false, true, false, false)
9096                                    + " " + intent.getExtras(), here);
9097                        }
9098                        am.broadcastIntent(null, intent, null, finishedReceiver,
9099                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9100                                null, finishedReceiver != null, false, id);
9101                    }
9102                } catch (RemoteException ex) {
9103                }
9104            }
9105        });
9106    }
9107
9108    /**
9109     * Check if the external storage media is available. This is true if there
9110     * is a mounted external storage medium or if the external storage is
9111     * emulated.
9112     */
9113    private boolean isExternalMediaAvailable() {
9114        return mMediaMounted || Environment.isExternalStorageEmulated();
9115    }
9116
9117    @Override
9118    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9119        // writer
9120        synchronized (mPackages) {
9121            if (!isExternalMediaAvailable()) {
9122                // If the external storage is no longer mounted at this point,
9123                // the caller may not have been able to delete all of this
9124                // packages files and can not delete any more.  Bail.
9125                return null;
9126            }
9127            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9128            if (lastPackage != null) {
9129                pkgs.remove(lastPackage);
9130            }
9131            if (pkgs.size() > 0) {
9132                return pkgs.get(0);
9133            }
9134        }
9135        return null;
9136    }
9137
9138    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9139        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9140                userId, andCode ? 1 : 0, packageName);
9141        if (mSystemReady) {
9142            msg.sendToTarget();
9143        } else {
9144            if (mPostSystemReadyMessages == null) {
9145                mPostSystemReadyMessages = new ArrayList<>();
9146            }
9147            mPostSystemReadyMessages.add(msg);
9148        }
9149    }
9150
9151    void startCleaningPackages() {
9152        // reader
9153        synchronized (mPackages) {
9154            if (!isExternalMediaAvailable()) {
9155                return;
9156            }
9157            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9158                return;
9159            }
9160        }
9161        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9162        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9163        IActivityManager am = ActivityManagerNative.getDefault();
9164        if (am != null) {
9165            try {
9166                am.startService(null, intent, null, mContext.getOpPackageName(),
9167                        UserHandle.USER_OWNER);
9168            } catch (RemoteException e) {
9169            }
9170        }
9171    }
9172
9173    @Override
9174    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9175            int installFlags, String installerPackageName, VerificationParams verificationParams,
9176            String packageAbiOverride) {
9177        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9178                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9179    }
9180
9181    @Override
9182    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9183            int installFlags, String installerPackageName, VerificationParams verificationParams,
9184            String packageAbiOverride, int userId) {
9185        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9186
9187        final int callingUid = Binder.getCallingUid();
9188        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9189
9190        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9191            try {
9192                if (observer != null) {
9193                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9194                }
9195            } catch (RemoteException re) {
9196            }
9197            return;
9198        }
9199
9200        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9201            installFlags |= PackageManager.INSTALL_FROM_ADB;
9202
9203        } else {
9204            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9205            // about installerPackageName.
9206
9207            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9208            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9209        }
9210
9211        UserHandle user;
9212        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9213            user = UserHandle.ALL;
9214        } else {
9215            user = new UserHandle(userId);
9216        }
9217
9218        // Only system components can circumvent runtime permissions when installing.
9219        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9220                && mContext.checkCallingOrSelfPermission(Manifest.permission
9221                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9222            throw new SecurityException("You need the "
9223                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9224                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9225        }
9226
9227        verificationParams.setInstallerUid(callingUid);
9228
9229        final File originFile = new File(originPath);
9230        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9231
9232        final Message msg = mHandler.obtainMessage(INIT_COPY);
9233        msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName,
9234                null, verificationParams, user, packageAbiOverride);
9235        mHandler.sendMessage(msg);
9236    }
9237
9238    void installStage(String packageName, File stagedDir, String stagedCid,
9239            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
9240            String installerPackageName, int installerUid, UserHandle user) {
9241        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
9242                params.referrerUri, installerUid, null);
9243        verifParams.setInstallerUid(installerUid);
9244
9245        final OriginInfo origin;
9246        if (stagedDir != null) {
9247            origin = OriginInfo.fromStagedFile(stagedDir);
9248        } else {
9249            origin = OriginInfo.fromStagedContainer(stagedCid);
9250        }
9251
9252        final Message msg = mHandler.obtainMessage(INIT_COPY);
9253        msg.obj = new InstallParams(origin, null, observer, params.installFlags,
9254                installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride);
9255        mHandler.sendMessage(msg);
9256    }
9257
9258    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
9259        Bundle extras = new Bundle(1);
9260        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
9261
9262        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
9263                packageName, extras, null, null, new int[] {userId});
9264        try {
9265            IActivityManager am = ActivityManagerNative.getDefault();
9266            final boolean isSystem =
9267                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
9268            if (isSystem && am.isUserRunning(userId, false)) {
9269                // The just-installed/enabled app is bundled on the system, so presumed
9270                // to be able to run automatically without needing an explicit launch.
9271                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
9272                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
9273                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
9274                        .setPackage(packageName);
9275                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
9276                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
9277            }
9278        } catch (RemoteException e) {
9279            // shouldn't happen
9280            Slog.w(TAG, "Unable to bootstrap installed package", e);
9281        }
9282    }
9283
9284    @Override
9285    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9286            int userId) {
9287        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9288        PackageSetting pkgSetting;
9289        final int uid = Binder.getCallingUid();
9290        enforceCrossUserPermission(uid, userId, true, true,
9291                "setApplicationHiddenSetting for user " + userId);
9292
9293        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9294            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9295            return false;
9296        }
9297
9298        long callingId = Binder.clearCallingIdentity();
9299        try {
9300            boolean sendAdded = false;
9301            boolean sendRemoved = false;
9302            // writer
9303            synchronized (mPackages) {
9304                pkgSetting = mSettings.mPackages.get(packageName);
9305                if (pkgSetting == null) {
9306                    return false;
9307                }
9308                if (pkgSetting.getHidden(userId) != hidden) {
9309                    pkgSetting.setHidden(hidden, userId);
9310                    mSettings.writePackageRestrictionsLPr(userId);
9311                    if (hidden) {
9312                        sendRemoved = true;
9313                    } else {
9314                        sendAdded = true;
9315                    }
9316                }
9317            }
9318            if (sendAdded) {
9319                sendPackageAddedForUser(packageName, pkgSetting, userId);
9320                return true;
9321            }
9322            if (sendRemoved) {
9323                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
9324                        "hiding pkg");
9325                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
9326            }
9327        } finally {
9328            Binder.restoreCallingIdentity(callingId);
9329        }
9330        return false;
9331    }
9332
9333    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9334            int userId) {
9335        final PackageRemovedInfo info = new PackageRemovedInfo();
9336        info.removedPackage = packageName;
9337        info.removedUsers = new int[] {userId};
9338        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9339        info.sendBroadcast(false, false, false);
9340    }
9341
9342    /**
9343     * Returns true if application is not found or there was an error. Otherwise it returns
9344     * the hidden state of the package for the given user.
9345     */
9346    @Override
9347    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9348        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9349        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9350                false, "getApplicationHidden for user " + userId);
9351        PackageSetting pkgSetting;
9352        long callingId = Binder.clearCallingIdentity();
9353        try {
9354            // writer
9355            synchronized (mPackages) {
9356                pkgSetting = mSettings.mPackages.get(packageName);
9357                if (pkgSetting == null) {
9358                    return true;
9359                }
9360                return pkgSetting.getHidden(userId);
9361            }
9362        } finally {
9363            Binder.restoreCallingIdentity(callingId);
9364        }
9365    }
9366
9367    /**
9368     * @hide
9369     */
9370    @Override
9371    public int installExistingPackageAsUser(String packageName, int userId) {
9372        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9373                null);
9374        PackageSetting pkgSetting;
9375        final int uid = Binder.getCallingUid();
9376        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9377                + userId);
9378        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9379            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9380        }
9381
9382        long callingId = Binder.clearCallingIdentity();
9383        try {
9384            boolean sendAdded = false;
9385
9386            // writer
9387            synchronized (mPackages) {
9388                pkgSetting = mSettings.mPackages.get(packageName);
9389                if (pkgSetting == null) {
9390                    return PackageManager.INSTALL_FAILED_INVALID_URI;
9391                }
9392                if (!pkgSetting.getInstalled(userId)) {
9393                    pkgSetting.setInstalled(true, userId);
9394                    pkgSetting.setHidden(false, userId);
9395                    mSettings.writePackageRestrictionsLPr(userId);
9396                    sendAdded = true;
9397                }
9398            }
9399
9400            if (sendAdded) {
9401                sendPackageAddedForUser(packageName, pkgSetting, userId);
9402            }
9403        } finally {
9404            Binder.restoreCallingIdentity(callingId);
9405        }
9406
9407        return PackageManager.INSTALL_SUCCEEDED;
9408    }
9409
9410    boolean isUserRestricted(int userId, String restrictionKey) {
9411        Bundle restrictions = sUserManager.getUserRestrictions(userId);
9412        if (restrictions.getBoolean(restrictionKey, false)) {
9413            Log.w(TAG, "User is restricted: " + restrictionKey);
9414            return true;
9415        }
9416        return false;
9417    }
9418
9419    @Override
9420    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
9421        mContext.enforceCallingOrSelfPermission(
9422                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9423                "Only package verification agents can verify applications");
9424
9425        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9426        final PackageVerificationResponse response = new PackageVerificationResponse(
9427                verificationCode, Binder.getCallingUid());
9428        msg.arg1 = id;
9429        msg.obj = response;
9430        mHandler.sendMessage(msg);
9431    }
9432
9433    @Override
9434    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
9435            long millisecondsToDelay) {
9436        mContext.enforceCallingOrSelfPermission(
9437                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9438                "Only package verification agents can extend verification timeouts");
9439
9440        final PackageVerificationState state = mPendingVerification.get(id);
9441        final PackageVerificationResponse response = new PackageVerificationResponse(
9442                verificationCodeAtTimeout, Binder.getCallingUid());
9443
9444        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
9445            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
9446        }
9447        if (millisecondsToDelay < 0) {
9448            millisecondsToDelay = 0;
9449        }
9450        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9451                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9452            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9453        }
9454
9455        if ((state != null) && !state.timeoutExtended()) {
9456            state.extendTimeout();
9457
9458            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9459            msg.arg1 = id;
9460            msg.obj = response;
9461            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
9462        }
9463    }
9464
9465    private void broadcastPackageVerified(int verificationId, Uri packageUri,
9466            int verificationCode, UserHandle user) {
9467        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
9468        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
9469        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9470        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9471        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
9472
9473        mContext.sendBroadcastAsUser(intent, user,
9474                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
9475    }
9476
9477    private ComponentName matchComponentForVerifier(String packageName,
9478            List<ResolveInfo> receivers) {
9479        ActivityInfo targetReceiver = null;
9480
9481        final int NR = receivers.size();
9482        for (int i = 0; i < NR; i++) {
9483            final ResolveInfo info = receivers.get(i);
9484            if (info.activityInfo == null) {
9485                continue;
9486            }
9487
9488            if (packageName.equals(info.activityInfo.packageName)) {
9489                targetReceiver = info.activityInfo;
9490                break;
9491            }
9492        }
9493
9494        if (targetReceiver == null) {
9495            return null;
9496        }
9497
9498        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
9499    }
9500
9501    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
9502            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
9503        if (pkgInfo.verifiers.length == 0) {
9504            return null;
9505        }
9506
9507        final int N = pkgInfo.verifiers.length;
9508        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
9509        for (int i = 0; i < N; i++) {
9510            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
9511
9512            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
9513                    receivers);
9514            if (comp == null) {
9515                continue;
9516            }
9517
9518            final int verifierUid = getUidForVerifier(verifierInfo);
9519            if (verifierUid == -1) {
9520                continue;
9521            }
9522
9523            if (DEBUG_VERIFY) {
9524                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
9525                        + " with the correct signature");
9526            }
9527            sufficientVerifiers.add(comp);
9528            verificationState.addSufficientVerifier(verifierUid);
9529        }
9530
9531        return sufficientVerifiers;
9532    }
9533
9534    private int getUidForVerifier(VerifierInfo verifierInfo) {
9535        synchronized (mPackages) {
9536            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
9537            if (pkg == null) {
9538                return -1;
9539            } else if (pkg.mSignatures.length != 1) {
9540                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9541                        + " has more than one signature; ignoring");
9542                return -1;
9543            }
9544
9545            /*
9546             * If the public key of the package's signature does not match
9547             * our expected public key, then this is a different package and
9548             * we should skip.
9549             */
9550
9551            final byte[] expectedPublicKey;
9552            try {
9553                final Signature verifierSig = pkg.mSignatures[0];
9554                final PublicKey publicKey = verifierSig.getPublicKey();
9555                expectedPublicKey = publicKey.getEncoded();
9556            } catch (CertificateException e) {
9557                return -1;
9558            }
9559
9560            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
9561
9562            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
9563                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9564                        + " does not have the expected public key; ignoring");
9565                return -1;
9566            }
9567
9568            return pkg.applicationInfo.uid;
9569        }
9570    }
9571
9572    @Override
9573    public void finishPackageInstall(int token) {
9574        enforceSystemOrRoot("Only the system is allowed to finish installs");
9575
9576        if (DEBUG_INSTALL) {
9577            Slog.v(TAG, "BM finishing package install for " + token);
9578        }
9579
9580        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9581        mHandler.sendMessage(msg);
9582    }
9583
9584    /**
9585     * Get the verification agent timeout.
9586     *
9587     * @return verification timeout in milliseconds
9588     */
9589    private long getVerificationTimeout() {
9590        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
9591                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
9592                DEFAULT_VERIFICATION_TIMEOUT);
9593    }
9594
9595    /**
9596     * Get the default verification agent response code.
9597     *
9598     * @return default verification response code
9599     */
9600    private int getDefaultVerificationResponse() {
9601        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9602                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
9603                DEFAULT_VERIFICATION_RESPONSE);
9604    }
9605
9606    /**
9607     * Check whether or not package verification has been enabled.
9608     *
9609     * @return true if verification should be performed
9610     */
9611    private boolean isVerificationEnabled(int userId, int installFlags) {
9612        if (!DEFAULT_VERIFY_ENABLE) {
9613            return false;
9614        }
9615
9616        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
9617
9618        // Check if installing from ADB
9619        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
9620            // Do not run verification in a test harness environment
9621            if (ActivityManager.isRunningInTestHarness()) {
9622                return false;
9623            }
9624            if (ensureVerifyAppsEnabled) {
9625                return true;
9626            }
9627            // Check if the developer does not want package verification for ADB installs
9628            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9629                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
9630                return false;
9631            }
9632        }
9633
9634        if (ensureVerifyAppsEnabled) {
9635            return true;
9636        }
9637
9638        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9639                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9640    }
9641
9642    @Override
9643    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9644            throws RemoteException {
9645        mContext.enforceCallingOrSelfPermission(
9646                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9647                "Only intentfilter verification agents can verify applications");
9648
9649        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9650        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9651                Binder.getCallingUid(), verificationCode, failedDomains);
9652        msg.arg1 = id;
9653        msg.obj = response;
9654        mHandler.sendMessage(msg);
9655    }
9656
9657    @Override
9658    public int getIntentVerificationStatus(String packageName, int userId) {
9659        synchronized (mPackages) {
9660            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
9661        }
9662    }
9663
9664    @Override
9665    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
9666        mContext.enforceCallingOrSelfPermission(
9667                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9668
9669        boolean result = false;
9670        synchronized (mPackages) {
9671            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
9672        }
9673        if (result) {
9674            scheduleWritePackageRestrictionsLocked(userId);
9675        }
9676        return result;
9677    }
9678
9679    @Override
9680    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
9681        synchronized (mPackages) {
9682            return mSettings.getIntentFilterVerificationsLPr(packageName);
9683        }
9684    }
9685
9686    @Override
9687    public List<IntentFilter> getAllIntentFilters(String packageName) {
9688        if (TextUtils.isEmpty(packageName)) {
9689            return Collections.<IntentFilter>emptyList();
9690        }
9691        synchronized (mPackages) {
9692            PackageParser.Package pkg = mPackages.get(packageName);
9693            if (pkg == null || pkg.activities == null) {
9694                return Collections.<IntentFilter>emptyList();
9695            }
9696            final int count = pkg.activities.size();
9697            ArrayList<IntentFilter> result = new ArrayList<>();
9698            for (int n=0; n<count; n++) {
9699                PackageParser.Activity activity = pkg.activities.get(n);
9700                if (activity.intents != null || activity.intents.size() > 0) {
9701                    result.addAll(activity.intents);
9702                }
9703            }
9704            return result;
9705        }
9706    }
9707
9708    @Override
9709    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
9710        mContext.enforceCallingOrSelfPermission(
9711                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9712
9713        synchronized (mPackages) {
9714            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
9715            if (packageName != null) {
9716                result |= updateIntentVerificationStatus(packageName,
9717                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
9718                        UserHandle.myUserId());
9719                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
9720                        packageName, userId);
9721            }
9722            return result;
9723        }
9724    }
9725
9726    @Override
9727    public String getDefaultBrowserPackageName(int userId) {
9728        synchronized (mPackages) {
9729            return mSettings.getDefaultBrowserPackageNameLPw(userId);
9730        }
9731    }
9732
9733    /**
9734     * Get the "allow unknown sources" setting.
9735     *
9736     * @return the current "allow unknown sources" setting
9737     */
9738    private int getUnknownSourcesSettings() {
9739        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9740                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
9741                -1);
9742    }
9743
9744    @Override
9745    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
9746        final int uid = Binder.getCallingUid();
9747        // writer
9748        synchronized (mPackages) {
9749            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
9750            if (targetPackageSetting == null) {
9751                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
9752            }
9753
9754            PackageSetting installerPackageSetting;
9755            if (installerPackageName != null) {
9756                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
9757                if (installerPackageSetting == null) {
9758                    throw new IllegalArgumentException("Unknown installer package: "
9759                            + installerPackageName);
9760                }
9761            } else {
9762                installerPackageSetting = null;
9763            }
9764
9765            Signature[] callerSignature;
9766            Object obj = mSettings.getUserIdLPr(uid);
9767            if (obj != null) {
9768                if (obj instanceof SharedUserSetting) {
9769                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
9770                } else if (obj instanceof PackageSetting) {
9771                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
9772                } else {
9773                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
9774                }
9775            } else {
9776                throw new SecurityException("Unknown calling uid " + uid);
9777            }
9778
9779            // Verify: can't set installerPackageName to a package that is
9780            // not signed with the same cert as the caller.
9781            if (installerPackageSetting != null) {
9782                if (compareSignatures(callerSignature,
9783                        installerPackageSetting.signatures.mSignatures)
9784                        != PackageManager.SIGNATURE_MATCH) {
9785                    throw new SecurityException(
9786                            "Caller does not have same cert as new installer package "
9787                            + installerPackageName);
9788                }
9789            }
9790
9791            // Verify: if target already has an installer package, it must
9792            // be signed with the same cert as the caller.
9793            if (targetPackageSetting.installerPackageName != null) {
9794                PackageSetting setting = mSettings.mPackages.get(
9795                        targetPackageSetting.installerPackageName);
9796                // If the currently set package isn't valid, then it's always
9797                // okay to change it.
9798                if (setting != null) {
9799                    if (compareSignatures(callerSignature,
9800                            setting.signatures.mSignatures)
9801                            != PackageManager.SIGNATURE_MATCH) {
9802                        throw new SecurityException(
9803                                "Caller does not have same cert as old installer package "
9804                                + targetPackageSetting.installerPackageName);
9805                    }
9806                }
9807            }
9808
9809            // Okay!
9810            targetPackageSetting.installerPackageName = installerPackageName;
9811            scheduleWriteSettingsLocked();
9812        }
9813    }
9814
9815    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
9816        // Queue up an async operation since the package installation may take a little while.
9817        mHandler.post(new Runnable() {
9818            public void run() {
9819                mHandler.removeCallbacks(this);
9820                 // Result object to be returned
9821                PackageInstalledInfo res = new PackageInstalledInfo();
9822                res.returnCode = currentStatus;
9823                res.uid = -1;
9824                res.pkg = null;
9825                res.removedInfo = new PackageRemovedInfo();
9826                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
9827                    args.doPreInstall(res.returnCode);
9828                    synchronized (mInstallLock) {
9829                        installPackageLI(args, res);
9830                    }
9831                    args.doPostInstall(res.returnCode, res.uid);
9832                }
9833
9834                // A restore should be performed at this point if (a) the install
9835                // succeeded, (b) the operation is not an update, and (c) the new
9836                // package has not opted out of backup participation.
9837                final boolean update = res.removedInfo.removedPackage != null;
9838                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
9839                boolean doRestore = !update
9840                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
9841
9842                // Set up the post-install work request bookkeeping.  This will be used
9843                // and cleaned up by the post-install event handling regardless of whether
9844                // there's a restore pass performed.  Token values are >= 1.
9845                int token;
9846                if (mNextInstallToken < 0) mNextInstallToken = 1;
9847                token = mNextInstallToken++;
9848
9849                PostInstallData data = new PostInstallData(args, res);
9850                mRunningInstalls.put(token, data);
9851                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
9852
9853                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
9854                    // Pass responsibility to the Backup Manager.  It will perform a
9855                    // restore if appropriate, then pass responsibility back to the
9856                    // Package Manager to run the post-install observer callbacks
9857                    // and broadcasts.
9858                    IBackupManager bm = IBackupManager.Stub.asInterface(
9859                            ServiceManager.getService(Context.BACKUP_SERVICE));
9860                    if (bm != null) {
9861                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
9862                                + " to BM for possible restore");
9863                        try {
9864                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
9865                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
9866                            } else {
9867                                doRestore = false;
9868                            }
9869                        } catch (RemoteException e) {
9870                            // can't happen; the backup manager is local
9871                        } catch (Exception e) {
9872                            Slog.e(TAG, "Exception trying to enqueue restore", e);
9873                            doRestore = false;
9874                        }
9875                    } else {
9876                        Slog.e(TAG, "Backup Manager not found!");
9877                        doRestore = false;
9878                    }
9879                }
9880
9881                if (!doRestore) {
9882                    // No restore possible, or the Backup Manager was mysteriously not
9883                    // available -- just fire the post-install work request directly.
9884                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
9885                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9886                    mHandler.sendMessage(msg);
9887                }
9888            }
9889        });
9890    }
9891
9892    private abstract class HandlerParams {
9893        private static final int MAX_RETRIES = 4;
9894
9895        /**
9896         * Number of times startCopy() has been attempted and had a non-fatal
9897         * error.
9898         */
9899        private int mRetries = 0;
9900
9901        /** User handle for the user requesting the information or installation. */
9902        private final UserHandle mUser;
9903
9904        HandlerParams(UserHandle user) {
9905            mUser = user;
9906        }
9907
9908        UserHandle getUser() {
9909            return mUser;
9910        }
9911
9912        final boolean startCopy() {
9913            boolean res;
9914            try {
9915                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
9916
9917                if (++mRetries > MAX_RETRIES) {
9918                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
9919                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
9920                    handleServiceError();
9921                    return false;
9922                } else {
9923                    handleStartCopy();
9924                    res = true;
9925                }
9926            } catch (RemoteException e) {
9927                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
9928                mHandler.sendEmptyMessage(MCS_RECONNECT);
9929                res = false;
9930            }
9931            handleReturnCode();
9932            return res;
9933        }
9934
9935        final void serviceError() {
9936            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
9937            handleServiceError();
9938            handleReturnCode();
9939        }
9940
9941        abstract void handleStartCopy() throws RemoteException;
9942        abstract void handleServiceError();
9943        abstract void handleReturnCode();
9944    }
9945
9946    class MeasureParams extends HandlerParams {
9947        private final PackageStats mStats;
9948        private boolean mSuccess;
9949
9950        private final IPackageStatsObserver mObserver;
9951
9952        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
9953            super(new UserHandle(stats.userHandle));
9954            mObserver = observer;
9955            mStats = stats;
9956        }
9957
9958        @Override
9959        public String toString() {
9960            return "MeasureParams{"
9961                + Integer.toHexString(System.identityHashCode(this))
9962                + " " + mStats.packageName + "}";
9963        }
9964
9965        @Override
9966        void handleStartCopy() throws RemoteException {
9967            synchronized (mInstallLock) {
9968                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
9969            }
9970
9971            if (mSuccess) {
9972                final boolean mounted;
9973                if (Environment.isExternalStorageEmulated()) {
9974                    mounted = true;
9975                } else {
9976                    final String status = Environment.getExternalStorageState();
9977                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
9978                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
9979                }
9980
9981                if (mounted) {
9982                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
9983
9984                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
9985                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
9986
9987                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
9988                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
9989
9990                    // Always subtract cache size, since it's a subdirectory
9991                    mStats.externalDataSize -= mStats.externalCacheSize;
9992
9993                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
9994                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
9995
9996                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
9997                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
9998                }
9999            }
10000        }
10001
10002        @Override
10003        void handleReturnCode() {
10004            if (mObserver != null) {
10005                try {
10006                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10007                } catch (RemoteException e) {
10008                    Slog.i(TAG, "Observer no longer exists.");
10009                }
10010            }
10011        }
10012
10013        @Override
10014        void handleServiceError() {
10015            Slog.e(TAG, "Could not measure application " + mStats.packageName
10016                            + " external storage");
10017        }
10018    }
10019
10020    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10021            throws RemoteException {
10022        long result = 0;
10023        for (File path : paths) {
10024            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10025        }
10026        return result;
10027    }
10028
10029    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10030        for (File path : paths) {
10031            try {
10032                mcs.clearDirectory(path.getAbsolutePath());
10033            } catch (RemoteException e) {
10034            }
10035        }
10036    }
10037
10038    static class OriginInfo {
10039        /**
10040         * Location where install is coming from, before it has been
10041         * copied/renamed into place. This could be a single monolithic APK
10042         * file, or a cluster directory. This location may be untrusted.
10043         */
10044        final File file;
10045        final String cid;
10046
10047        /**
10048         * Flag indicating that {@link #file} or {@link #cid} has already been
10049         * staged, meaning downstream users don't need to defensively copy the
10050         * contents.
10051         */
10052        final boolean staged;
10053
10054        /**
10055         * Flag indicating that {@link #file} or {@link #cid} is an already
10056         * installed app that is being moved.
10057         */
10058        final boolean existing;
10059
10060        final String resolvedPath;
10061        final File resolvedFile;
10062
10063        static OriginInfo fromNothing() {
10064            return new OriginInfo(null, null, false, false);
10065        }
10066
10067        static OriginInfo fromUntrustedFile(File file) {
10068            return new OriginInfo(file, null, false, false);
10069        }
10070
10071        static OriginInfo fromExistingFile(File file) {
10072            return new OriginInfo(file, null, false, true);
10073        }
10074
10075        static OriginInfo fromStagedFile(File file) {
10076            return new OriginInfo(file, null, true, false);
10077        }
10078
10079        static OriginInfo fromStagedContainer(String cid) {
10080            return new OriginInfo(null, cid, true, false);
10081        }
10082
10083        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10084            this.file = file;
10085            this.cid = cid;
10086            this.staged = staged;
10087            this.existing = existing;
10088
10089            if (cid != null) {
10090                resolvedPath = PackageHelper.getSdDir(cid);
10091                resolvedFile = new File(resolvedPath);
10092            } else if (file != null) {
10093                resolvedPath = file.getAbsolutePath();
10094                resolvedFile = file;
10095            } else {
10096                resolvedPath = null;
10097                resolvedFile = null;
10098            }
10099        }
10100    }
10101
10102    class MoveInfo {
10103        final int moveId;
10104        final String fromUuid;
10105        final String toUuid;
10106        final String packageName;
10107        final String dataAppName;
10108        final int appId;
10109        final String seinfo;
10110
10111        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10112                String dataAppName, int appId, String seinfo) {
10113            this.moveId = moveId;
10114            this.fromUuid = fromUuid;
10115            this.toUuid = toUuid;
10116            this.packageName = packageName;
10117            this.dataAppName = dataAppName;
10118            this.appId = appId;
10119            this.seinfo = seinfo;
10120        }
10121    }
10122
10123    class InstallParams extends HandlerParams {
10124        final OriginInfo origin;
10125        final MoveInfo move;
10126        final IPackageInstallObserver2 observer;
10127        int installFlags;
10128        final String installerPackageName;
10129        final String volumeUuid;
10130        final VerificationParams verificationParams;
10131        private InstallArgs mArgs;
10132        private int mRet;
10133        final String packageAbiOverride;
10134
10135        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10136                int installFlags, String installerPackageName, String volumeUuid,
10137                VerificationParams verificationParams, UserHandle user, String packageAbiOverride) {
10138            super(user);
10139            this.origin = origin;
10140            this.move = move;
10141            this.observer = observer;
10142            this.installFlags = installFlags;
10143            this.installerPackageName = installerPackageName;
10144            this.volumeUuid = volumeUuid;
10145            this.verificationParams = verificationParams;
10146            this.packageAbiOverride = packageAbiOverride;
10147        }
10148
10149        @Override
10150        public String toString() {
10151            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10152                    + " file=" + origin.file + " cid=" + origin.cid + "}";
10153        }
10154
10155        public ManifestDigest getManifestDigest() {
10156            if (verificationParams == null) {
10157                return null;
10158            }
10159            return verificationParams.getManifestDigest();
10160        }
10161
10162        private int installLocationPolicy(PackageInfoLite pkgLite) {
10163            String packageName = pkgLite.packageName;
10164            int installLocation = pkgLite.installLocation;
10165            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10166            // reader
10167            synchronized (mPackages) {
10168                PackageParser.Package pkg = mPackages.get(packageName);
10169                if (pkg != null) {
10170                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10171                        // Check for downgrading.
10172                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10173                            try {
10174                                checkDowngrade(pkg, pkgLite);
10175                            } catch (PackageManagerException e) {
10176                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10177                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
10178                            }
10179                        }
10180                        // Check for updated system application.
10181                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10182                            if (onSd) {
10183                                Slog.w(TAG, "Cannot install update to system app on sdcard");
10184                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
10185                            }
10186                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10187                        } else {
10188                            if (onSd) {
10189                                // Install flag overrides everything.
10190                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10191                            }
10192                            // If current upgrade specifies particular preference
10193                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
10194                                // Application explicitly specified internal.
10195                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10196                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
10197                                // App explictly prefers external. Let policy decide
10198                            } else {
10199                                // Prefer previous location
10200                                if (isExternal(pkg)) {
10201                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10202                                }
10203                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10204                            }
10205                        }
10206                    } else {
10207                        // Invalid install. Return error code
10208                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
10209                    }
10210                }
10211            }
10212            // All the special cases have been taken care of.
10213            // Return result based on recommended install location.
10214            if (onSd) {
10215                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10216            }
10217            return pkgLite.recommendedInstallLocation;
10218        }
10219
10220        /*
10221         * Invoke remote method to get package information and install
10222         * location values. Override install location based on default
10223         * policy if needed and then create install arguments based
10224         * on the install location.
10225         */
10226        public void handleStartCopy() throws RemoteException {
10227            int ret = PackageManager.INSTALL_SUCCEEDED;
10228
10229            // If we're already staged, we've firmly committed to an install location
10230            if (origin.staged) {
10231                if (origin.file != null) {
10232                    installFlags |= PackageManager.INSTALL_INTERNAL;
10233                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10234                } else if (origin.cid != null) {
10235                    installFlags |= PackageManager.INSTALL_EXTERNAL;
10236                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
10237                } else {
10238                    throw new IllegalStateException("Invalid stage location");
10239                }
10240            }
10241
10242            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10243            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
10244
10245            PackageInfoLite pkgLite = null;
10246
10247            if (onInt && onSd) {
10248                // Check if both bits are set.
10249                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
10250                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10251            } else {
10252                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
10253                        packageAbiOverride);
10254
10255                /*
10256                 * If we have too little free space, try to free cache
10257                 * before giving up.
10258                 */
10259                if (!origin.staged && pkgLite.recommendedInstallLocation
10260                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10261                    // TODO: focus freeing disk space on the target device
10262                    final StorageManager storage = StorageManager.from(mContext);
10263                    final long lowThreshold = storage.getStorageLowBytes(
10264                            Environment.getDataDirectory());
10265
10266                    final long sizeBytes = mContainerService.calculateInstalledSize(
10267                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
10268
10269                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
10270                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
10271                                installFlags, packageAbiOverride);
10272                    }
10273
10274                    /*
10275                     * The cache free must have deleted the file we
10276                     * downloaded to install.
10277                     *
10278                     * TODO: fix the "freeCache" call to not delete
10279                     *       the file we care about.
10280                     */
10281                    if (pkgLite.recommendedInstallLocation
10282                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10283                        pkgLite.recommendedInstallLocation
10284                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
10285                    }
10286                }
10287            }
10288
10289            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10290                int loc = pkgLite.recommendedInstallLocation;
10291                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
10292                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10293                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
10294                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
10295                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10296                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10297                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
10298                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
10299                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10300                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
10301                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
10302                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
10303                } else {
10304                    // Override with defaults if needed.
10305                    loc = installLocationPolicy(pkgLite);
10306                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
10307                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
10308                    } else if (!onSd && !onInt) {
10309                        // Override install location with flags
10310                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
10311                            // Set the flag to install on external media.
10312                            installFlags |= PackageManager.INSTALL_EXTERNAL;
10313                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
10314                        } else {
10315                            // Make sure the flag for installing on external
10316                            // media is unset
10317                            installFlags |= PackageManager.INSTALL_INTERNAL;
10318                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10319                        }
10320                    }
10321                }
10322            }
10323
10324            final InstallArgs args = createInstallArgs(this);
10325            mArgs = args;
10326
10327            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10328                 /*
10329                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
10330                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
10331                 */
10332                int userIdentifier = getUser().getIdentifier();
10333                if (userIdentifier == UserHandle.USER_ALL
10334                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
10335                    userIdentifier = UserHandle.USER_OWNER;
10336                }
10337
10338                /*
10339                 * Determine if we have any installed package verifiers. If we
10340                 * do, then we'll defer to them to verify the packages.
10341                 */
10342                final int requiredUid = mRequiredVerifierPackage == null ? -1
10343                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
10344                if (!origin.existing && requiredUid != -1
10345                        && isVerificationEnabled(userIdentifier, installFlags)) {
10346                    final Intent verification = new Intent(
10347                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
10348                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10349                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
10350                            PACKAGE_MIME_TYPE);
10351                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10352
10353                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
10354                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10355                            0 /* TODO: Which userId? */);
10356
10357                    if (DEBUG_VERIFY) {
10358                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10359                                + verification.toString() + " with " + pkgLite.verifiers.length
10360                                + " optional verifiers");
10361                    }
10362
10363                    final int verificationId = mPendingVerificationToken++;
10364
10365                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10366
10367                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10368                            installerPackageName);
10369
10370                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10371                            installFlags);
10372
10373                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10374                            pkgLite.packageName);
10375
10376                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10377                            pkgLite.versionCode);
10378
10379                    if (verificationParams != null) {
10380                        if (verificationParams.getVerificationURI() != null) {
10381                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10382                                 verificationParams.getVerificationURI());
10383                        }
10384                        if (verificationParams.getOriginatingURI() != null) {
10385                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10386                                  verificationParams.getOriginatingURI());
10387                        }
10388                        if (verificationParams.getReferrer() != null) {
10389                            verification.putExtra(Intent.EXTRA_REFERRER,
10390                                  verificationParams.getReferrer());
10391                        }
10392                        if (verificationParams.getOriginatingUid() >= 0) {
10393                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
10394                                  verificationParams.getOriginatingUid());
10395                        }
10396                        if (verificationParams.getInstallerUid() >= 0) {
10397                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
10398                                  verificationParams.getInstallerUid());
10399                        }
10400                    }
10401
10402                    final PackageVerificationState verificationState = new PackageVerificationState(
10403                            requiredUid, args);
10404
10405                    mPendingVerification.append(verificationId, verificationState);
10406
10407                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
10408                            receivers, verificationState);
10409
10410                    /*
10411                     * If any sufficient verifiers were listed in the package
10412                     * manifest, attempt to ask them.
10413                     */
10414                    if (sufficientVerifiers != null) {
10415                        final int N = sufficientVerifiers.size();
10416                        if (N == 0) {
10417                            Slog.i(TAG, "Additional verifiers required, but none installed.");
10418                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
10419                        } else {
10420                            for (int i = 0; i < N; i++) {
10421                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
10422
10423                                final Intent sufficientIntent = new Intent(verification);
10424                                sufficientIntent.setComponent(verifierComponent);
10425
10426                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
10427                            }
10428                        }
10429                    }
10430
10431                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
10432                            mRequiredVerifierPackage, receivers);
10433                    if (ret == PackageManager.INSTALL_SUCCEEDED
10434                            && mRequiredVerifierPackage != null) {
10435                        /*
10436                         * Send the intent to the required verification agent,
10437                         * but only start the verification timeout after the
10438                         * target BroadcastReceivers have run.
10439                         */
10440                        verification.setComponent(requiredVerifierComponent);
10441                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
10442                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10443                                new BroadcastReceiver() {
10444                                    @Override
10445                                    public void onReceive(Context context, Intent intent) {
10446                                        final Message msg = mHandler
10447                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
10448                                        msg.arg1 = verificationId;
10449                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
10450                                    }
10451                                }, null, 0, null, null);
10452
10453                        /*
10454                         * We don't want the copy to proceed until verification
10455                         * succeeds, so null out this field.
10456                         */
10457                        mArgs = null;
10458                    }
10459                } else {
10460                    /*
10461                     * No package verification is enabled, so immediately start
10462                     * the remote call to initiate copy using temporary file.
10463                     */
10464                    ret = args.copyApk(mContainerService, true);
10465                }
10466            }
10467
10468            mRet = ret;
10469        }
10470
10471        @Override
10472        void handleReturnCode() {
10473            // If mArgs is null, then MCS couldn't be reached. When it
10474            // reconnects, it will try again to install. At that point, this
10475            // will succeed.
10476            if (mArgs != null) {
10477                processPendingInstall(mArgs, mRet);
10478            }
10479        }
10480
10481        @Override
10482        void handleServiceError() {
10483            mArgs = createInstallArgs(this);
10484            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10485        }
10486
10487        public boolean isForwardLocked() {
10488            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10489        }
10490    }
10491
10492    /**
10493     * Used during creation of InstallArgs
10494     *
10495     * @param installFlags package installation flags
10496     * @return true if should be installed on external storage
10497     */
10498    private static boolean installOnExternalAsec(int installFlags) {
10499        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
10500            return false;
10501        }
10502        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
10503            return true;
10504        }
10505        return false;
10506    }
10507
10508    /**
10509     * Used during creation of InstallArgs
10510     *
10511     * @param installFlags package installation flags
10512     * @return true if should be installed as forward locked
10513     */
10514    private static boolean installForwardLocked(int installFlags) {
10515        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10516    }
10517
10518    private InstallArgs createInstallArgs(InstallParams params) {
10519        if (params.move != null) {
10520            return new MoveInstallArgs(params);
10521        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
10522            return new AsecInstallArgs(params);
10523        } else {
10524            return new FileInstallArgs(params);
10525        }
10526    }
10527
10528    /**
10529     * Create args that describe an existing installed package. Typically used
10530     * when cleaning up old installs, or used as a move source.
10531     */
10532    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
10533            String resourcePath, String[] instructionSets) {
10534        final boolean isInAsec;
10535        if (installOnExternalAsec(installFlags)) {
10536            /* Apps on SD card are always in ASEC containers. */
10537            isInAsec = true;
10538        } else if (installForwardLocked(installFlags)
10539                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
10540            /*
10541             * Forward-locked apps are only in ASEC containers if they're the
10542             * new style
10543             */
10544            isInAsec = true;
10545        } else {
10546            isInAsec = false;
10547        }
10548
10549        if (isInAsec) {
10550            return new AsecInstallArgs(codePath, instructionSets,
10551                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
10552        } else {
10553            return new FileInstallArgs(codePath, resourcePath, instructionSets);
10554        }
10555    }
10556
10557    static abstract class InstallArgs {
10558        /** @see InstallParams#origin */
10559        final OriginInfo origin;
10560        /** @see InstallParams#move */
10561        final MoveInfo move;
10562
10563        final IPackageInstallObserver2 observer;
10564        // Always refers to PackageManager flags only
10565        final int installFlags;
10566        final String installerPackageName;
10567        final String volumeUuid;
10568        final ManifestDigest manifestDigest;
10569        final UserHandle user;
10570        final String abiOverride;
10571
10572        // The list of instruction sets supported by this app. This is currently
10573        // only used during the rmdex() phase to clean up resources. We can get rid of this
10574        // if we move dex files under the common app path.
10575        /* nullable */ String[] instructionSets;
10576
10577        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10578                int installFlags, String installerPackageName, String volumeUuid,
10579                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
10580                String abiOverride) {
10581            this.origin = origin;
10582            this.move = move;
10583            this.installFlags = installFlags;
10584            this.observer = observer;
10585            this.installerPackageName = installerPackageName;
10586            this.volumeUuid = volumeUuid;
10587            this.manifestDigest = manifestDigest;
10588            this.user = user;
10589            this.instructionSets = instructionSets;
10590            this.abiOverride = abiOverride;
10591        }
10592
10593        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
10594        abstract int doPreInstall(int status);
10595
10596        /**
10597         * Rename package into final resting place. All paths on the given
10598         * scanned package should be updated to reflect the rename.
10599         */
10600        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
10601        abstract int doPostInstall(int status, int uid);
10602
10603        /** @see PackageSettingBase#codePathString */
10604        abstract String getCodePath();
10605        /** @see PackageSettingBase#resourcePathString */
10606        abstract String getResourcePath();
10607
10608        // Need installer lock especially for dex file removal.
10609        abstract void cleanUpResourcesLI();
10610        abstract boolean doPostDeleteLI(boolean delete);
10611
10612        /**
10613         * Called before the source arguments are copied. This is used mostly
10614         * for MoveParams when it needs to read the source file to put it in the
10615         * destination.
10616         */
10617        int doPreCopy() {
10618            return PackageManager.INSTALL_SUCCEEDED;
10619        }
10620
10621        /**
10622         * Called after the source arguments are copied. This is used mostly for
10623         * MoveParams when it needs to read the source file to put it in the
10624         * destination.
10625         *
10626         * @return
10627         */
10628        int doPostCopy(int uid) {
10629            return PackageManager.INSTALL_SUCCEEDED;
10630        }
10631
10632        protected boolean isFwdLocked() {
10633            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10634        }
10635
10636        protected boolean isExternalAsec() {
10637            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10638        }
10639
10640        UserHandle getUser() {
10641            return user;
10642        }
10643    }
10644
10645    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
10646        if (!allCodePaths.isEmpty()) {
10647            if (instructionSets == null) {
10648                throw new IllegalStateException("instructionSet == null");
10649            }
10650            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
10651            for (String codePath : allCodePaths) {
10652                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
10653                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
10654                    if (retCode < 0) {
10655                        Slog.w(TAG, "Couldn't remove dex file for package: "
10656                                + " at location " + codePath + ", retcode=" + retCode);
10657                        // we don't consider this to be a failure of the core package deletion
10658                    }
10659                }
10660            }
10661        }
10662    }
10663
10664    /**
10665     * Logic to handle installation of non-ASEC applications, including copying
10666     * and renaming logic.
10667     */
10668    class FileInstallArgs extends InstallArgs {
10669        private File codeFile;
10670        private File resourceFile;
10671
10672        // Example topology:
10673        // /data/app/com.example/base.apk
10674        // /data/app/com.example/split_foo.apk
10675        // /data/app/com.example/lib/arm/libfoo.so
10676        // /data/app/com.example/lib/arm64/libfoo.so
10677        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
10678
10679        /** New install */
10680        FileInstallArgs(InstallParams params) {
10681            super(params.origin, params.move, params.observer, params.installFlags,
10682                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10683                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10684            if (isFwdLocked()) {
10685                throw new IllegalArgumentException("Forward locking only supported in ASEC");
10686            }
10687        }
10688
10689        /** Existing install */
10690        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
10691            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
10692                    null);
10693            this.codeFile = (codePath != null) ? new File(codePath) : null;
10694            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
10695        }
10696
10697        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10698            if (origin.staged) {
10699                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
10700                codeFile = origin.file;
10701                resourceFile = origin.file;
10702                return PackageManager.INSTALL_SUCCEEDED;
10703            }
10704
10705            try {
10706                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
10707                codeFile = tempDir;
10708                resourceFile = tempDir;
10709            } catch (IOException e) {
10710                Slog.w(TAG, "Failed to create copy file: " + e);
10711                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10712            }
10713
10714            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
10715                @Override
10716                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
10717                    if (!FileUtils.isValidExtFilename(name)) {
10718                        throw new IllegalArgumentException("Invalid filename: " + name);
10719                    }
10720                    try {
10721                        final File file = new File(codeFile, name);
10722                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
10723                                O_RDWR | O_CREAT, 0644);
10724                        Os.chmod(file.getAbsolutePath(), 0644);
10725                        return new ParcelFileDescriptor(fd);
10726                    } catch (ErrnoException e) {
10727                        throw new RemoteException("Failed to open: " + e.getMessage());
10728                    }
10729                }
10730            };
10731
10732            int ret = PackageManager.INSTALL_SUCCEEDED;
10733            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
10734            if (ret != PackageManager.INSTALL_SUCCEEDED) {
10735                Slog.e(TAG, "Failed to copy package");
10736                return ret;
10737            }
10738
10739            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
10740            NativeLibraryHelper.Handle handle = null;
10741            try {
10742                handle = NativeLibraryHelper.Handle.create(codeFile);
10743                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
10744                        abiOverride);
10745            } catch (IOException e) {
10746                Slog.e(TAG, "Copying native libraries failed", e);
10747                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10748            } finally {
10749                IoUtils.closeQuietly(handle);
10750            }
10751
10752            return ret;
10753        }
10754
10755        int doPreInstall(int status) {
10756            if (status != PackageManager.INSTALL_SUCCEEDED) {
10757                cleanUp();
10758            }
10759            return status;
10760        }
10761
10762        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10763            if (status != PackageManager.INSTALL_SUCCEEDED) {
10764                cleanUp();
10765                return false;
10766            }
10767
10768            final File targetDir = codeFile.getParentFile();
10769            final File beforeCodeFile = codeFile;
10770            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
10771
10772            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
10773            try {
10774                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
10775            } catch (ErrnoException e) {
10776                Slog.w(TAG, "Failed to rename", e);
10777                return false;
10778            }
10779
10780            if (!SELinux.restoreconRecursive(afterCodeFile)) {
10781                Slog.w(TAG, "Failed to restorecon");
10782                return false;
10783            }
10784
10785            // Reflect the rename internally
10786            codeFile = afterCodeFile;
10787            resourceFile = afterCodeFile;
10788
10789            // Reflect the rename in scanned details
10790            pkg.codePath = afterCodeFile.getAbsolutePath();
10791            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10792                    pkg.baseCodePath);
10793            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10794                    pkg.splitCodePaths);
10795
10796            // Reflect the rename in app info
10797            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10798            pkg.applicationInfo.setCodePath(pkg.codePath);
10799            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10800            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10801            pkg.applicationInfo.setResourcePath(pkg.codePath);
10802            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10803            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10804
10805            return true;
10806        }
10807
10808        int doPostInstall(int status, int uid) {
10809            if (status != PackageManager.INSTALL_SUCCEEDED) {
10810                cleanUp();
10811            }
10812            return status;
10813        }
10814
10815        @Override
10816        String getCodePath() {
10817            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
10818        }
10819
10820        @Override
10821        String getResourcePath() {
10822            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
10823        }
10824
10825        private boolean cleanUp() {
10826            if (codeFile == null || !codeFile.exists()) {
10827                return false;
10828            }
10829
10830            if (codeFile.isDirectory()) {
10831                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
10832            } else {
10833                codeFile.delete();
10834            }
10835
10836            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
10837                resourceFile.delete();
10838            }
10839
10840            return true;
10841        }
10842
10843        void cleanUpResourcesLI() {
10844            // Try enumerating all code paths before deleting
10845            List<String> allCodePaths = Collections.EMPTY_LIST;
10846            if (codeFile != null && codeFile.exists()) {
10847                try {
10848                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
10849                    allCodePaths = pkg.getAllCodePaths();
10850                } catch (PackageParserException e) {
10851                    // Ignored; we tried our best
10852                }
10853            }
10854
10855            cleanUp();
10856            removeDexFiles(allCodePaths, instructionSets);
10857        }
10858
10859        boolean doPostDeleteLI(boolean delete) {
10860            // XXX err, shouldn't we respect the delete flag?
10861            cleanUpResourcesLI();
10862            return true;
10863        }
10864    }
10865
10866    private boolean isAsecExternal(String cid) {
10867        final String asecPath = PackageHelper.getSdFilesystem(cid);
10868        return !asecPath.startsWith(mAsecInternalPath);
10869    }
10870
10871    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
10872            PackageManagerException {
10873        if (copyRet < 0) {
10874            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
10875                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
10876                throw new PackageManagerException(copyRet, message);
10877            }
10878        }
10879    }
10880
10881    /**
10882     * Extract the MountService "container ID" from the full code path of an
10883     * .apk.
10884     */
10885    static String cidFromCodePath(String fullCodePath) {
10886        int eidx = fullCodePath.lastIndexOf("/");
10887        String subStr1 = fullCodePath.substring(0, eidx);
10888        int sidx = subStr1.lastIndexOf("/");
10889        return subStr1.substring(sidx+1, eidx);
10890    }
10891
10892    /**
10893     * Logic to handle installation of ASEC applications, including copying and
10894     * renaming logic.
10895     */
10896    class AsecInstallArgs extends InstallArgs {
10897        static final String RES_FILE_NAME = "pkg.apk";
10898        static final String PUBLIC_RES_FILE_NAME = "res.zip";
10899
10900        String cid;
10901        String packagePath;
10902        String resourcePath;
10903
10904        /** New install */
10905        AsecInstallArgs(InstallParams params) {
10906            super(params.origin, params.move, params.observer, params.installFlags,
10907                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10908                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10909        }
10910
10911        /** Existing install */
10912        AsecInstallArgs(String fullCodePath, String[] instructionSets,
10913                        boolean isExternal, boolean isForwardLocked) {
10914            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
10915                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
10916                    instructionSets, null);
10917            // Hackily pretend we're still looking at a full code path
10918            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
10919                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
10920            }
10921
10922            // Extract cid from fullCodePath
10923            int eidx = fullCodePath.lastIndexOf("/");
10924            String subStr1 = fullCodePath.substring(0, eidx);
10925            int sidx = subStr1.lastIndexOf("/");
10926            cid = subStr1.substring(sidx+1, eidx);
10927            setMountPath(subStr1);
10928        }
10929
10930        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
10931            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
10932                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
10933                    instructionSets, null);
10934            this.cid = cid;
10935            setMountPath(PackageHelper.getSdDir(cid));
10936        }
10937
10938        void createCopyFile() {
10939            cid = mInstallerService.allocateExternalStageCidLegacy();
10940        }
10941
10942        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10943            if (origin.staged) {
10944                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
10945                cid = origin.cid;
10946                setMountPath(PackageHelper.getSdDir(cid));
10947                return PackageManager.INSTALL_SUCCEEDED;
10948            }
10949
10950            if (temp) {
10951                createCopyFile();
10952            } else {
10953                /*
10954                 * Pre-emptively destroy the container since it's destroyed if
10955                 * copying fails due to it existing anyway.
10956                 */
10957                PackageHelper.destroySdDir(cid);
10958            }
10959
10960            final String newMountPath = imcs.copyPackageToContainer(
10961                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
10962                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
10963
10964            if (newMountPath != null) {
10965                setMountPath(newMountPath);
10966                return PackageManager.INSTALL_SUCCEEDED;
10967            } else {
10968                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10969            }
10970        }
10971
10972        @Override
10973        String getCodePath() {
10974            return packagePath;
10975        }
10976
10977        @Override
10978        String getResourcePath() {
10979            return resourcePath;
10980        }
10981
10982        int doPreInstall(int status) {
10983            if (status != PackageManager.INSTALL_SUCCEEDED) {
10984                // Destroy container
10985                PackageHelper.destroySdDir(cid);
10986            } else {
10987                boolean mounted = PackageHelper.isContainerMounted(cid);
10988                if (!mounted) {
10989                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
10990                            Process.SYSTEM_UID);
10991                    if (newMountPath != null) {
10992                        setMountPath(newMountPath);
10993                    } else {
10994                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10995                    }
10996                }
10997            }
10998            return status;
10999        }
11000
11001        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11002            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11003            String newMountPath = null;
11004            if (PackageHelper.isContainerMounted(cid)) {
11005                // Unmount the container
11006                if (!PackageHelper.unMountSdDir(cid)) {
11007                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11008                    return false;
11009                }
11010            }
11011            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11012                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11013                        " which might be stale. Will try to clean up.");
11014                // Clean up the stale container and proceed to recreate.
11015                if (!PackageHelper.destroySdDir(newCacheId)) {
11016                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11017                    return false;
11018                }
11019                // Successfully cleaned up stale container. Try to rename again.
11020                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11021                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11022                            + " inspite of cleaning it up.");
11023                    return false;
11024                }
11025            }
11026            if (!PackageHelper.isContainerMounted(newCacheId)) {
11027                Slog.w(TAG, "Mounting container " + newCacheId);
11028                newMountPath = PackageHelper.mountSdDir(newCacheId,
11029                        getEncryptKey(), Process.SYSTEM_UID);
11030            } else {
11031                newMountPath = PackageHelper.getSdDir(newCacheId);
11032            }
11033            if (newMountPath == null) {
11034                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11035                return false;
11036            }
11037            Log.i(TAG, "Succesfully renamed " + cid +
11038                    " to " + newCacheId +
11039                    " at new path: " + newMountPath);
11040            cid = newCacheId;
11041
11042            final File beforeCodeFile = new File(packagePath);
11043            setMountPath(newMountPath);
11044            final File afterCodeFile = new File(packagePath);
11045
11046            // Reflect the rename in scanned details
11047            pkg.codePath = afterCodeFile.getAbsolutePath();
11048            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11049                    pkg.baseCodePath);
11050            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11051                    pkg.splitCodePaths);
11052
11053            // Reflect the rename in app info
11054            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11055            pkg.applicationInfo.setCodePath(pkg.codePath);
11056            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11057            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11058            pkg.applicationInfo.setResourcePath(pkg.codePath);
11059            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11060            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11061
11062            return true;
11063        }
11064
11065        private void setMountPath(String mountPath) {
11066            final File mountFile = new File(mountPath);
11067
11068            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11069            if (monolithicFile.exists()) {
11070                packagePath = monolithicFile.getAbsolutePath();
11071                if (isFwdLocked()) {
11072                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11073                } else {
11074                    resourcePath = packagePath;
11075                }
11076            } else {
11077                packagePath = mountFile.getAbsolutePath();
11078                resourcePath = packagePath;
11079            }
11080        }
11081
11082        int doPostInstall(int status, int uid) {
11083            if (status != PackageManager.INSTALL_SUCCEEDED) {
11084                cleanUp();
11085            } else {
11086                final int groupOwner;
11087                final String protectedFile;
11088                if (isFwdLocked()) {
11089                    groupOwner = UserHandle.getSharedAppGid(uid);
11090                    protectedFile = RES_FILE_NAME;
11091                } else {
11092                    groupOwner = -1;
11093                    protectedFile = null;
11094                }
11095
11096                if (uid < Process.FIRST_APPLICATION_UID
11097                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11098                    Slog.e(TAG, "Failed to finalize " + cid);
11099                    PackageHelper.destroySdDir(cid);
11100                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11101                }
11102
11103                boolean mounted = PackageHelper.isContainerMounted(cid);
11104                if (!mounted) {
11105                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11106                }
11107            }
11108            return status;
11109        }
11110
11111        private void cleanUp() {
11112            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11113
11114            // Destroy secure container
11115            PackageHelper.destroySdDir(cid);
11116        }
11117
11118        private List<String> getAllCodePaths() {
11119            final File codeFile = new File(getCodePath());
11120            if (codeFile != null && codeFile.exists()) {
11121                try {
11122                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11123                    return pkg.getAllCodePaths();
11124                } catch (PackageParserException e) {
11125                    // Ignored; we tried our best
11126                }
11127            }
11128            return Collections.EMPTY_LIST;
11129        }
11130
11131        void cleanUpResourcesLI() {
11132            // Enumerate all code paths before deleting
11133            cleanUpResourcesLI(getAllCodePaths());
11134        }
11135
11136        private void cleanUpResourcesLI(List<String> allCodePaths) {
11137            cleanUp();
11138            removeDexFiles(allCodePaths, instructionSets);
11139        }
11140
11141        String getPackageName() {
11142            return getAsecPackageName(cid);
11143        }
11144
11145        boolean doPostDeleteLI(boolean delete) {
11146            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
11147            final List<String> allCodePaths = getAllCodePaths();
11148            boolean mounted = PackageHelper.isContainerMounted(cid);
11149            if (mounted) {
11150                // Unmount first
11151                if (PackageHelper.unMountSdDir(cid)) {
11152                    mounted = false;
11153                }
11154            }
11155            if (!mounted && delete) {
11156                cleanUpResourcesLI(allCodePaths);
11157            }
11158            return !mounted;
11159        }
11160
11161        @Override
11162        int doPreCopy() {
11163            if (isFwdLocked()) {
11164                if (!PackageHelper.fixSdPermissions(cid,
11165                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
11166                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11167                }
11168            }
11169
11170            return PackageManager.INSTALL_SUCCEEDED;
11171        }
11172
11173        @Override
11174        int doPostCopy(int uid) {
11175            if (isFwdLocked()) {
11176                if (uid < Process.FIRST_APPLICATION_UID
11177                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
11178                                RES_FILE_NAME)) {
11179                    Slog.e(TAG, "Failed to finalize " + cid);
11180                    PackageHelper.destroySdDir(cid);
11181                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11182                }
11183            }
11184
11185            return PackageManager.INSTALL_SUCCEEDED;
11186        }
11187    }
11188
11189    /**
11190     * Logic to handle movement of existing installed applications.
11191     */
11192    class MoveInstallArgs extends InstallArgs {
11193        private File codeFile;
11194        private File resourceFile;
11195
11196        /** New install */
11197        MoveInstallArgs(InstallParams params) {
11198            super(params.origin, params.move, params.observer, params.installFlags,
11199                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11200                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
11201        }
11202
11203        int copyApk(IMediaContainerService imcs, boolean temp) {
11204            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
11205                    + move.fromUuid + " to " + move.toUuid);
11206            synchronized (mInstaller) {
11207                if (mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
11208                        move.dataAppName, move.appId, move.seinfo) != 0) {
11209                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11210                }
11211            }
11212
11213            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
11214            resourceFile = codeFile;
11215            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
11216
11217            return PackageManager.INSTALL_SUCCEEDED;
11218        }
11219
11220        int doPreInstall(int status) {
11221            if (status != PackageManager.INSTALL_SUCCEEDED) {
11222                cleanUp();
11223            }
11224            return status;
11225        }
11226
11227        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11228            if (status != PackageManager.INSTALL_SUCCEEDED) {
11229                cleanUp();
11230                return false;
11231            }
11232
11233            // Reflect the move in app info
11234            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11235            pkg.applicationInfo.setCodePath(pkg.codePath);
11236            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11237            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11238            pkg.applicationInfo.setResourcePath(pkg.codePath);
11239            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11240            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11241
11242            return true;
11243        }
11244
11245        int doPostInstall(int status, int uid) {
11246            if (status != PackageManager.INSTALL_SUCCEEDED) {
11247                cleanUp();
11248            }
11249            return status;
11250        }
11251
11252        @Override
11253        String getCodePath() {
11254            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11255        }
11256
11257        @Override
11258        String getResourcePath() {
11259            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11260        }
11261
11262        private boolean cleanUp() {
11263            if (codeFile == null || !codeFile.exists()) {
11264                return false;
11265            }
11266
11267            if (codeFile.isDirectory()) {
11268                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11269            } else {
11270                codeFile.delete();
11271            }
11272
11273            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11274                resourceFile.delete();
11275            }
11276
11277            return true;
11278        }
11279
11280        void cleanUpResourcesLI() {
11281            cleanUp();
11282        }
11283
11284        boolean doPostDeleteLI(boolean delete) {
11285            // XXX err, shouldn't we respect the delete flag?
11286            cleanUpResourcesLI();
11287            return true;
11288        }
11289    }
11290
11291    static String getAsecPackageName(String packageCid) {
11292        int idx = packageCid.lastIndexOf("-");
11293        if (idx == -1) {
11294            return packageCid;
11295        }
11296        return packageCid.substring(0, idx);
11297    }
11298
11299    // Utility method used to create code paths based on package name and available index.
11300    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
11301        String idxStr = "";
11302        int idx = 1;
11303        // Fall back to default value of idx=1 if prefix is not
11304        // part of oldCodePath
11305        if (oldCodePath != null) {
11306            String subStr = oldCodePath;
11307            // Drop the suffix right away
11308            if (suffix != null && subStr.endsWith(suffix)) {
11309                subStr = subStr.substring(0, subStr.length() - suffix.length());
11310            }
11311            // If oldCodePath already contains prefix find out the
11312            // ending index to either increment or decrement.
11313            int sidx = subStr.lastIndexOf(prefix);
11314            if (sidx != -1) {
11315                subStr = subStr.substring(sidx + prefix.length());
11316                if (subStr != null) {
11317                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
11318                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
11319                    }
11320                    try {
11321                        idx = Integer.parseInt(subStr);
11322                        if (idx <= 1) {
11323                            idx++;
11324                        } else {
11325                            idx--;
11326                        }
11327                    } catch(NumberFormatException e) {
11328                    }
11329                }
11330            }
11331        }
11332        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
11333        return prefix + idxStr;
11334    }
11335
11336    private File getNextCodePath(File targetDir, String packageName) {
11337        int suffix = 1;
11338        File result;
11339        do {
11340            result = new File(targetDir, packageName + "-" + suffix);
11341            suffix++;
11342        } while (result.exists());
11343        return result;
11344    }
11345
11346    // Utility method that returns the relative package path with respect
11347    // to the installation directory. Like say for /data/data/com.test-1.apk
11348    // string com.test-1 is returned.
11349    static String deriveCodePathName(String codePath) {
11350        if (codePath == null) {
11351            return null;
11352        }
11353        final File codeFile = new File(codePath);
11354        final String name = codeFile.getName();
11355        if (codeFile.isDirectory()) {
11356            return name;
11357        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
11358            final int lastDot = name.lastIndexOf('.');
11359            return name.substring(0, lastDot);
11360        } else {
11361            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11362            return null;
11363        }
11364    }
11365
11366    class PackageInstalledInfo {
11367        String name;
11368        int uid;
11369        // The set of users that originally had this package installed.
11370        int[] origUsers;
11371        // The set of users that now have this package installed.
11372        int[] newUsers;
11373        PackageParser.Package pkg;
11374        int returnCode;
11375        String returnMsg;
11376        PackageRemovedInfo removedInfo;
11377
11378        public void setError(int code, String msg) {
11379            returnCode = code;
11380            returnMsg = msg;
11381            Slog.w(TAG, msg);
11382        }
11383
11384        public void setError(String msg, PackageParserException e) {
11385            returnCode = e.error;
11386            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11387            Slog.w(TAG, msg, e);
11388        }
11389
11390        public void setError(String msg, PackageManagerException e) {
11391            returnCode = e.error;
11392            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11393            Slog.w(TAG, msg, e);
11394        }
11395
11396        // In some error cases we want to convey more info back to the observer
11397        String origPackage;
11398        String origPermission;
11399    }
11400
11401    /*
11402     * Install a non-existing package.
11403     */
11404    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11405            UserHandle user, String installerPackageName, String volumeUuid,
11406            PackageInstalledInfo res) {
11407        // Remember this for later, in case we need to rollback this install
11408        String pkgName = pkg.packageName;
11409
11410        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
11411        final boolean dataDirExists = PackageManager.getDataDirForUser(volumeUuid, pkgName,
11412                UserHandle.USER_OWNER).exists();
11413        synchronized(mPackages) {
11414            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
11415                // A package with the same name is already installed, though
11416                // it has been renamed to an older name.  The package we
11417                // are trying to install should be installed as an update to
11418                // the existing one, but that has not been requested, so bail.
11419                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11420                        + " without first uninstalling package running as "
11421                        + mSettings.mRenamedPackages.get(pkgName));
11422                return;
11423            }
11424            if (mPackages.containsKey(pkgName)) {
11425                // Don't allow installation over an existing package with the same name.
11426                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11427                        + " without first uninstalling.");
11428                return;
11429            }
11430        }
11431
11432        try {
11433            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
11434                    System.currentTimeMillis(), user);
11435
11436            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
11437            // delete the partially installed application. the data directory will have to be
11438            // restored if it was already existing
11439            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11440                // remove package from internal structures.  Note that we want deletePackageX to
11441                // delete the package data and cache directories that it created in
11442                // scanPackageLocked, unless those directories existed before we even tried to
11443                // install.
11444                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
11445                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
11446                                res.removedInfo, true);
11447            }
11448
11449        } catch (PackageManagerException e) {
11450            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11451        }
11452    }
11453
11454    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
11455        // Can't rotate keys during boot or if sharedUser.
11456        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
11457                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
11458            return false;
11459        }
11460        // app is using upgradeKeySets; make sure all are valid
11461        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11462        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
11463        for (int i = 0; i < upgradeKeySets.length; i++) {
11464            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
11465                Slog.wtf(TAG, "Package "
11466                         + (oldPs.name != null ? oldPs.name : "<null>")
11467                         + " contains upgrade-key-set reference to unknown key-set: "
11468                         + upgradeKeySets[i]
11469                         + " reverting to signatures check.");
11470                return false;
11471            }
11472        }
11473        return true;
11474    }
11475
11476    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
11477        // Upgrade keysets are being used.  Determine if new package has a superset of the
11478        // required keys.
11479        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
11480        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11481        for (int i = 0; i < upgradeKeySets.length; i++) {
11482            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
11483            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
11484                return true;
11485            }
11486        }
11487        return false;
11488    }
11489
11490    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11491            UserHandle user, String installerPackageName, String volumeUuid,
11492            PackageInstalledInfo res) {
11493        final PackageParser.Package oldPackage;
11494        final String pkgName = pkg.packageName;
11495        final int[] allUsers;
11496        final boolean[] perUserInstalled;
11497        final boolean weFroze;
11498
11499        // First find the old package info and check signatures
11500        synchronized(mPackages) {
11501            oldPackage = mPackages.get(pkgName);
11502            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
11503            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11504            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11505                if(!checkUpgradeKeySetLP(ps, pkg)) {
11506                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11507                            "New package not signed by keys specified by upgrade-keysets: "
11508                            + pkgName);
11509                    return;
11510                }
11511            } else {
11512                // default to original signature matching
11513                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
11514                    != PackageManager.SIGNATURE_MATCH) {
11515                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11516                            "New package has a different signature: " + pkgName);
11517                    return;
11518                }
11519            }
11520
11521            // In case of rollback, remember per-user/profile install state
11522            allUsers = sUserManager.getUserIds();
11523            perUserInstalled = new boolean[allUsers.length];
11524            for (int i = 0; i < allUsers.length; i++) {
11525                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11526            }
11527
11528            // Mark the app as frozen to prevent launching during the upgrade
11529            // process, and then kill all running instances
11530            if (!ps.frozen) {
11531                ps.frozen = true;
11532                weFroze = true;
11533            } else {
11534                weFroze = false;
11535            }
11536        }
11537
11538        // Now that we're guarded by frozen state, kill app during upgrade
11539        killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg");
11540
11541        try {
11542            boolean sysPkg = (isSystemApp(oldPackage));
11543            if (sysPkg) {
11544                replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11545                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11546            } else {
11547                replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11548                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11549            }
11550        } finally {
11551            // Regardless of success or failure of upgrade steps above, always
11552            // unfreeze the package if we froze it
11553            if (weFroze) {
11554                unfreezePackage(pkgName);
11555            }
11556        }
11557    }
11558
11559    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
11560            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11561            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11562            String volumeUuid, PackageInstalledInfo res) {
11563        String pkgName = deletedPackage.packageName;
11564        boolean deletedPkg = true;
11565        boolean updatedSettings = false;
11566
11567        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
11568                + deletedPackage);
11569        long origUpdateTime;
11570        if (pkg.mExtras != null) {
11571            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
11572        } else {
11573            origUpdateTime = 0;
11574        }
11575
11576        // First delete the existing package while retaining the data directory
11577        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
11578                res.removedInfo, true)) {
11579            // If the existing package wasn't successfully deleted
11580            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
11581            deletedPkg = false;
11582        } else {
11583            // Successfully deleted the old package; proceed with replace.
11584
11585            // If deleted package lived in a container, give users a chance to
11586            // relinquish resources before killing.
11587            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
11588                if (DEBUG_INSTALL) {
11589                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
11590                }
11591                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
11592                final ArrayList<String> pkgList = new ArrayList<String>(1);
11593                pkgList.add(deletedPackage.applicationInfo.packageName);
11594                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
11595            }
11596
11597            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
11598            try {
11599                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
11600                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
11601                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11602                        perUserInstalled, res, user);
11603                updatedSettings = true;
11604            } catch (PackageManagerException e) {
11605                res.setError("Package couldn't be installed in " + pkg.codePath, e);
11606            }
11607        }
11608
11609        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11610            // remove package from internal structures.  Note that we want deletePackageX to
11611            // delete the package data and cache directories that it created in
11612            // scanPackageLocked, unless those directories existed before we even tried to
11613            // install.
11614            if(updatedSettings) {
11615                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
11616                deletePackageLI(
11617                        pkgName, null, true, allUsers, perUserInstalled,
11618                        PackageManager.DELETE_KEEP_DATA,
11619                                res.removedInfo, true);
11620            }
11621            // Since we failed to install the new package we need to restore the old
11622            // package that we deleted.
11623            if (deletedPkg) {
11624                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
11625                File restoreFile = new File(deletedPackage.codePath);
11626                // Parse old package
11627                boolean oldExternal = isExternal(deletedPackage);
11628                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
11629                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
11630                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11631                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
11632                try {
11633                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
11634                } catch (PackageManagerException e) {
11635                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
11636                            + e.getMessage());
11637                    return;
11638                }
11639                // Restore of old package succeeded. Update permissions.
11640                // writer
11641                synchronized (mPackages) {
11642                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
11643                            UPDATE_PERMISSIONS_ALL);
11644                    // can downgrade to reader
11645                    mSettings.writeLPr();
11646                }
11647                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
11648            }
11649        }
11650    }
11651
11652    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
11653            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11654            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11655            String volumeUuid, PackageInstalledInfo res) {
11656        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
11657                + ", old=" + deletedPackage);
11658        boolean disabledSystem = false;
11659        boolean updatedSettings = false;
11660        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
11661        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
11662                != 0) {
11663            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11664        }
11665        String packageName = deletedPackage.packageName;
11666        if (packageName == null) {
11667            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11668                    "Attempt to delete null packageName.");
11669            return;
11670        }
11671        PackageParser.Package oldPkg;
11672        PackageSetting oldPkgSetting;
11673        // reader
11674        synchronized (mPackages) {
11675            oldPkg = mPackages.get(packageName);
11676            oldPkgSetting = mSettings.mPackages.get(packageName);
11677            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
11678                    (oldPkgSetting == null)) {
11679                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11680                        "Couldn't find package:" + packageName + " information");
11681                return;
11682            }
11683        }
11684
11685        res.removedInfo.uid = oldPkg.applicationInfo.uid;
11686        res.removedInfo.removedPackage = packageName;
11687        // Remove existing system package
11688        removePackageLI(oldPkgSetting, true);
11689        // writer
11690        synchronized (mPackages) {
11691            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
11692            if (!disabledSystem && deletedPackage != null) {
11693                // We didn't need to disable the .apk as a current system package,
11694                // which means we are replacing another update that is already
11695                // installed.  We need to make sure to delete the older one's .apk.
11696                res.removedInfo.args = createInstallArgsForExisting(0,
11697                        deletedPackage.applicationInfo.getCodePath(),
11698                        deletedPackage.applicationInfo.getResourcePath(),
11699                        getAppDexInstructionSets(deletedPackage.applicationInfo));
11700            } else {
11701                res.removedInfo.args = null;
11702            }
11703        }
11704
11705        // Successfully disabled the old package. Now proceed with re-installation
11706        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
11707
11708        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11709        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
11710
11711        PackageParser.Package newPackage = null;
11712        try {
11713            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
11714            if (newPackage.mExtras != null) {
11715                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
11716                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
11717                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
11718
11719                // is the update attempting to change shared user? that isn't going to work...
11720                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
11721                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
11722                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
11723                            + " to " + newPkgSetting.sharedUser);
11724                    updatedSettings = true;
11725                }
11726            }
11727
11728            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11729                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11730                        perUserInstalled, res, user);
11731                updatedSettings = true;
11732            }
11733
11734        } catch (PackageManagerException e) {
11735            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11736        }
11737
11738        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11739            // Re installation failed. Restore old information
11740            // Remove new pkg information
11741            if (newPackage != null) {
11742                removeInstalledPackageLI(newPackage, true);
11743            }
11744            // Add back the old system package
11745            try {
11746                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
11747            } catch (PackageManagerException e) {
11748                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
11749            }
11750            // Restore the old system information in Settings
11751            synchronized (mPackages) {
11752                if (disabledSystem) {
11753                    mSettings.enableSystemPackageLPw(packageName);
11754                }
11755                if (updatedSettings) {
11756                    mSettings.setInstallerPackageName(packageName,
11757                            oldPkgSetting.installerPackageName);
11758                }
11759                mSettings.writeLPr();
11760            }
11761        }
11762    }
11763
11764    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
11765            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
11766            UserHandle user) {
11767        String pkgName = newPackage.packageName;
11768        synchronized (mPackages) {
11769            //write settings. the installStatus will be incomplete at this stage.
11770            //note that the new package setting would have already been
11771            //added to mPackages. It hasn't been persisted yet.
11772            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
11773            mSettings.writeLPr();
11774        }
11775
11776        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
11777
11778        synchronized (mPackages) {
11779            updatePermissionsLPw(newPackage.packageName, newPackage,
11780                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
11781                            ? UPDATE_PERMISSIONS_ALL : 0));
11782            // For system-bundled packages, we assume that installing an upgraded version
11783            // of the package implies that the user actually wants to run that new code,
11784            // so we enable the package.
11785            PackageSetting ps = mSettings.mPackages.get(pkgName);
11786            if (ps != null) {
11787                if (isSystemApp(newPackage)) {
11788                    // NB: implicit assumption that system package upgrades apply to all users
11789                    if (DEBUG_INSTALL) {
11790                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
11791                    }
11792                    if (res.origUsers != null) {
11793                        for (int userHandle : res.origUsers) {
11794                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
11795                                    userHandle, installerPackageName);
11796                        }
11797                    }
11798                    // Also convey the prior install/uninstall state
11799                    if (allUsers != null && perUserInstalled != null) {
11800                        for (int i = 0; i < allUsers.length; i++) {
11801                            if (DEBUG_INSTALL) {
11802                                Slog.d(TAG, "    user " + allUsers[i]
11803                                        + " => " + perUserInstalled[i]);
11804                            }
11805                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
11806                        }
11807                        // these install state changes will be persisted in the
11808                        // upcoming call to mSettings.writeLPr().
11809                    }
11810                }
11811                // It's implied that when a user requests installation, they want the app to be
11812                // installed and enabled.
11813                int userId = user.getIdentifier();
11814                if (userId != UserHandle.USER_ALL) {
11815                    ps.setInstalled(true, userId);
11816                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
11817                }
11818            }
11819            res.name = pkgName;
11820            res.uid = newPackage.applicationInfo.uid;
11821            res.pkg = newPackage;
11822            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
11823            mSettings.setInstallerPackageName(pkgName, installerPackageName);
11824            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11825            //to update install status
11826            mSettings.writeLPr();
11827        }
11828    }
11829
11830    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
11831        final int installFlags = args.installFlags;
11832        final String installerPackageName = args.installerPackageName;
11833        final String volumeUuid = args.volumeUuid;
11834        final File tmpPackageFile = new File(args.getCodePath());
11835        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
11836        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
11837                || (args.volumeUuid != null));
11838        boolean replace = false;
11839        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
11840        if (args.move != null) {
11841            // moving a complete application; perfom an initial scan on the new install location
11842            scanFlags |= SCAN_INITIAL;
11843        }
11844        // Result object to be returned
11845        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11846
11847        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
11848        // Retrieve PackageSettings and parse package
11849        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
11850                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
11851                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11852        PackageParser pp = new PackageParser();
11853        pp.setSeparateProcesses(mSeparateProcesses);
11854        pp.setDisplayMetrics(mMetrics);
11855
11856        final PackageParser.Package pkg;
11857        try {
11858            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
11859        } catch (PackageParserException e) {
11860            res.setError("Failed parse during installPackageLI", e);
11861            return;
11862        }
11863
11864        // Mark that we have an install time CPU ABI override.
11865        pkg.cpuAbiOverride = args.abiOverride;
11866
11867        String pkgName = res.name = pkg.packageName;
11868        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
11869            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
11870                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
11871                return;
11872            }
11873        }
11874
11875        try {
11876            pp.collectCertificates(pkg, parseFlags);
11877            pp.collectManifestDigest(pkg);
11878        } catch (PackageParserException e) {
11879            res.setError("Failed collect during installPackageLI", e);
11880            return;
11881        }
11882
11883        /* If the installer passed in a manifest digest, compare it now. */
11884        if (args.manifestDigest != null) {
11885            if (DEBUG_INSTALL) {
11886                final String parsedManifest = pkg.manifestDigest == null ? "null"
11887                        : pkg.manifestDigest.toString();
11888                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
11889                        + parsedManifest);
11890            }
11891
11892            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
11893                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
11894                return;
11895            }
11896        } else if (DEBUG_INSTALL) {
11897            final String parsedManifest = pkg.manifestDigest == null
11898                    ? "null" : pkg.manifestDigest.toString();
11899            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
11900        }
11901
11902        // Get rid of all references to package scan path via parser.
11903        pp = null;
11904        String oldCodePath = null;
11905        boolean systemApp = false;
11906        synchronized (mPackages) {
11907            // Check if installing already existing package
11908            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
11909                String oldName = mSettings.mRenamedPackages.get(pkgName);
11910                if (pkg.mOriginalPackages != null
11911                        && pkg.mOriginalPackages.contains(oldName)
11912                        && mPackages.containsKey(oldName)) {
11913                    // This package is derived from an original package,
11914                    // and this device has been updating from that original
11915                    // name.  We must continue using the original name, so
11916                    // rename the new package here.
11917                    pkg.setPackageName(oldName);
11918                    pkgName = pkg.packageName;
11919                    replace = true;
11920                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
11921                            + oldName + " pkgName=" + pkgName);
11922                } else if (mPackages.containsKey(pkgName)) {
11923                    // This package, under its official name, already exists
11924                    // on the device; we should replace it.
11925                    replace = true;
11926                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
11927                }
11928
11929                // Prevent apps opting out from runtime permissions
11930                if (replace) {
11931                    PackageParser.Package oldPackage = mPackages.get(pkgName);
11932                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
11933                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
11934                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
11935                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
11936                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
11937                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
11938                                        + " doesn't support runtime permissions but the old"
11939                                        + " target SDK " + oldTargetSdk + " does.");
11940                        return;
11941                    }
11942                }
11943            }
11944
11945            PackageSetting ps = mSettings.mPackages.get(pkgName);
11946            if (ps != null) {
11947                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
11948
11949                // Quick sanity check that we're signed correctly if updating;
11950                // we'll check this again later when scanning, but we want to
11951                // bail early here before tripping over redefined permissions.
11952                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11953                    if (!checkUpgradeKeySetLP(ps, pkg)) {
11954                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
11955                                + pkg.packageName + " upgrade keys do not match the "
11956                                + "previously installed version");
11957                        return;
11958                    }
11959                } else {
11960                    try {
11961                        verifySignaturesLP(ps, pkg);
11962                    } catch (PackageManagerException e) {
11963                        res.setError(e.error, e.getMessage());
11964                        return;
11965                    }
11966                }
11967
11968                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
11969                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
11970                    systemApp = (ps.pkg.applicationInfo.flags &
11971                            ApplicationInfo.FLAG_SYSTEM) != 0;
11972                }
11973                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
11974            }
11975
11976            // Check whether the newly-scanned package wants to define an already-defined perm
11977            int N = pkg.permissions.size();
11978            for (int i = N-1; i >= 0; i--) {
11979                PackageParser.Permission perm = pkg.permissions.get(i);
11980                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
11981                if (bp != null) {
11982                    // If the defining package is signed with our cert, it's okay.  This
11983                    // also includes the "updating the same package" case, of course.
11984                    // "updating same package" could also involve key-rotation.
11985                    final boolean sigsOk;
11986                    if (bp.sourcePackage.equals(pkg.packageName)
11987                            && (bp.packageSetting instanceof PackageSetting)
11988                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
11989                                    scanFlags))) {
11990                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
11991                    } else {
11992                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
11993                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
11994                    }
11995                    if (!sigsOk) {
11996                        // If the owning package is the system itself, we log but allow
11997                        // install to proceed; we fail the install on all other permission
11998                        // redefinitions.
11999                        if (!bp.sourcePackage.equals("android")) {
12000                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12001                                    + pkg.packageName + " attempting to redeclare permission "
12002                                    + perm.info.name + " already owned by " + bp.sourcePackage);
12003                            res.origPermission = perm.info.name;
12004                            res.origPackage = bp.sourcePackage;
12005                            return;
12006                        } else {
12007                            Slog.w(TAG, "Package " + pkg.packageName
12008                                    + " attempting to redeclare system permission "
12009                                    + perm.info.name + "; ignoring new declaration");
12010                            pkg.permissions.remove(i);
12011                        }
12012                    }
12013                }
12014            }
12015
12016        }
12017
12018        if (systemApp && onExternal) {
12019            // Disable updates to system apps on sdcard
12020            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12021                    "Cannot install updates to system apps on sdcard");
12022            return;
12023        }
12024
12025        if (args.move != null) {
12026            // We did an in-place move, so dex is ready to roll
12027            scanFlags |= SCAN_NO_DEX;
12028            scanFlags |= SCAN_MOVE;
12029        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
12030            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
12031            scanFlags |= SCAN_NO_DEX;
12032
12033            try {
12034                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
12035                        true /* extract libs */);
12036            } catch (PackageManagerException pme) {
12037                Slog.e(TAG, "Error deriving application ABI", pme);
12038                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
12039                return;
12040            }
12041
12042            // Run dexopt before old package gets removed, to minimize time when app is unavailable
12043            int result = mPackageDexOptimizer
12044                    .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */,
12045                            false /* defer */, false /* inclDependencies */);
12046            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
12047                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
12048                return;
12049            }
12050        }
12051
12052        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
12053            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
12054            return;
12055        }
12056
12057        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
12058
12059        if (replace) {
12060            replacePackageLI(pkg, parseFlags, scanFlags, args.user,
12061                    installerPackageName, volumeUuid, res);
12062        } else {
12063            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
12064                    args.user, installerPackageName, volumeUuid, res);
12065        }
12066        synchronized (mPackages) {
12067            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12068            if (ps != null) {
12069                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12070            }
12071        }
12072    }
12073
12074    private void startIntentFilterVerifications(int userId, boolean replacing,
12075            PackageParser.Package pkg) {
12076        if (mIntentFilterVerifierComponent == null) {
12077            Slog.w(TAG, "No IntentFilter verification will not be done as "
12078                    + "there is no IntentFilterVerifier available!");
12079            return;
12080        }
12081
12082        final int verifierUid = getPackageUid(
12083                mIntentFilterVerifierComponent.getPackageName(),
12084                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
12085
12086        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
12087        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
12088        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
12089        mHandler.sendMessage(msg);
12090    }
12091
12092    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
12093            PackageParser.Package pkg) {
12094        int size = pkg.activities.size();
12095        if (size == 0) {
12096            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12097                    "No activity, so no need to verify any IntentFilter!");
12098            return;
12099        }
12100
12101        final boolean hasDomainURLs = hasDomainURLs(pkg);
12102        if (!hasDomainURLs) {
12103            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12104                    "No domain URLs, so no need to verify any IntentFilter!");
12105            return;
12106        }
12107
12108        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
12109                + " if any IntentFilter from the " + size
12110                + " Activities needs verification ...");
12111
12112        int count = 0;
12113        final String packageName = pkg.packageName;
12114
12115        synchronized (mPackages) {
12116            // If this is a new install and we see that we've already run verification for this
12117            // package, we have nothing to do: it means the state was restored from backup.
12118            if (!replacing) {
12119                IntentFilterVerificationInfo ivi =
12120                        mSettings.getIntentFilterVerificationLPr(packageName);
12121                if (ivi != null) {
12122                    if (DEBUG_DOMAIN_VERIFICATION) {
12123                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
12124                                + ivi.getStatusString());
12125                    }
12126                    return;
12127                }
12128            }
12129
12130            // If any filters need to be verified, then all need to be.
12131            boolean needToVerify = false;
12132            for (PackageParser.Activity a : pkg.activities) {
12133                for (ActivityIntentInfo filter : a.intents) {
12134                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
12135                        if (DEBUG_DOMAIN_VERIFICATION) {
12136                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
12137                        }
12138                        needToVerify = true;
12139                        break;
12140                    }
12141                }
12142            }
12143
12144            if (needToVerify) {
12145                final int verificationId = mIntentFilterVerificationToken++;
12146                for (PackageParser.Activity a : pkg.activities) {
12147                    for (ActivityIntentInfo filter : a.intents) {
12148                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
12149                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12150                                    "Verification needed for IntentFilter:" + filter.toString());
12151                            mIntentFilterVerifier.addOneIntentFilterVerification(
12152                                    verifierUid, userId, verificationId, filter, packageName);
12153                            count++;
12154                        }
12155                    }
12156                }
12157            }
12158        }
12159
12160        if (count > 0) {
12161            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
12162                    + " IntentFilter verification" + (count > 1 ? "s" : "")
12163                    +  " for userId:" + userId);
12164            mIntentFilterVerifier.startVerifications(userId);
12165        } else {
12166            if (DEBUG_DOMAIN_VERIFICATION) {
12167                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
12168            }
12169        }
12170    }
12171
12172    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
12173        final ComponentName cn  = filter.activity.getComponentName();
12174        final String packageName = cn.getPackageName();
12175
12176        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
12177                packageName);
12178        if (ivi == null) {
12179            return true;
12180        }
12181        int status = ivi.getStatus();
12182        switch (status) {
12183            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
12184            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
12185                return true;
12186
12187            default:
12188                // Nothing to do
12189                return false;
12190        }
12191    }
12192
12193    private static boolean isMultiArch(PackageSetting ps) {
12194        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12195    }
12196
12197    private static boolean isMultiArch(ApplicationInfo info) {
12198        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12199    }
12200
12201    private static boolean isExternal(PackageParser.Package pkg) {
12202        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12203    }
12204
12205    private static boolean isExternal(PackageSetting ps) {
12206        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12207    }
12208
12209    private static boolean isExternal(ApplicationInfo info) {
12210        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12211    }
12212
12213    private static boolean isSystemApp(PackageParser.Package pkg) {
12214        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
12215    }
12216
12217    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
12218        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
12219    }
12220
12221    private static boolean hasDomainURLs(PackageParser.Package pkg) {
12222        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
12223    }
12224
12225    private static boolean isSystemApp(PackageSetting ps) {
12226        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
12227    }
12228
12229    private static boolean isUpdatedSystemApp(PackageSetting ps) {
12230        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
12231    }
12232
12233    private int packageFlagsToInstallFlags(PackageSetting ps) {
12234        int installFlags = 0;
12235        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
12236            // This existing package was an external ASEC install when we have
12237            // the external flag without a UUID
12238            installFlags |= PackageManager.INSTALL_EXTERNAL;
12239        }
12240        if (ps.isForwardLocked()) {
12241            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12242        }
12243        return installFlags;
12244    }
12245
12246    private void deleteTempPackageFiles() {
12247        final FilenameFilter filter = new FilenameFilter() {
12248            public boolean accept(File dir, String name) {
12249                return name.startsWith("vmdl") && name.endsWith(".tmp");
12250            }
12251        };
12252        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
12253            file.delete();
12254        }
12255    }
12256
12257    @Override
12258    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
12259            int flags) {
12260        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
12261                flags);
12262    }
12263
12264    @Override
12265    public void deletePackage(final String packageName,
12266            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
12267        mContext.enforceCallingOrSelfPermission(
12268                android.Manifest.permission.DELETE_PACKAGES, null);
12269        final int uid = Binder.getCallingUid();
12270        if (UserHandle.getUserId(uid) != userId) {
12271            mContext.enforceCallingPermission(
12272                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
12273                    "deletePackage for user " + userId);
12274        }
12275        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
12276            try {
12277                observer.onPackageDeleted(packageName,
12278                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
12279            } catch (RemoteException re) {
12280            }
12281            return;
12282        }
12283
12284        boolean uninstallBlocked = false;
12285        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
12286            int[] users = sUserManager.getUserIds();
12287            for (int i = 0; i < users.length; ++i) {
12288                if (getBlockUninstallForUser(packageName, users[i])) {
12289                    uninstallBlocked = true;
12290                    break;
12291                }
12292            }
12293        } else {
12294            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
12295        }
12296        if (uninstallBlocked) {
12297            try {
12298                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
12299                        null);
12300            } catch (RemoteException re) {
12301            }
12302            return;
12303        }
12304
12305        if (DEBUG_REMOVE) {
12306            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
12307        }
12308        // Queue up an async operation since the package deletion may take a little while.
12309        mHandler.post(new Runnable() {
12310            public void run() {
12311                mHandler.removeCallbacks(this);
12312                final int returnCode = deletePackageX(packageName, userId, flags);
12313                if (observer != null) {
12314                    try {
12315                        observer.onPackageDeleted(packageName, returnCode, null);
12316                    } catch (RemoteException e) {
12317                        Log.i(TAG, "Observer no longer exists.");
12318                    } //end catch
12319                } //end if
12320            } //end run
12321        });
12322    }
12323
12324    private boolean isPackageDeviceAdmin(String packageName, int userId) {
12325        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12326                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12327        try {
12328            if (dpm != null) {
12329                if (dpm.isDeviceOwner(packageName)) {
12330                    return true;
12331                }
12332                int[] users;
12333                if (userId == UserHandle.USER_ALL) {
12334                    users = sUserManager.getUserIds();
12335                } else {
12336                    users = new int[]{userId};
12337                }
12338                for (int i = 0; i < users.length; ++i) {
12339                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
12340                        return true;
12341                    }
12342                }
12343            }
12344        } catch (RemoteException e) {
12345        }
12346        return false;
12347    }
12348
12349    /**
12350     *  This method is an internal method that could be get invoked either
12351     *  to delete an installed package or to clean up a failed installation.
12352     *  After deleting an installed package, a broadcast is sent to notify any
12353     *  listeners that the package has been installed. For cleaning up a failed
12354     *  installation, the broadcast is not necessary since the package's
12355     *  installation wouldn't have sent the initial broadcast either
12356     *  The key steps in deleting a package are
12357     *  deleting the package information in internal structures like mPackages,
12358     *  deleting the packages base directories through installd
12359     *  updating mSettings to reflect current status
12360     *  persisting settings for later use
12361     *  sending a broadcast if necessary
12362     */
12363    private int deletePackageX(String packageName, int userId, int flags) {
12364        final PackageRemovedInfo info = new PackageRemovedInfo();
12365        final boolean res;
12366
12367        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
12368                ? UserHandle.ALL : new UserHandle(userId);
12369
12370        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
12371            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
12372            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
12373        }
12374
12375        boolean removedForAllUsers = false;
12376        boolean systemUpdate = false;
12377
12378        // for the uninstall-updates case and restricted profiles, remember the per-
12379        // userhandle installed state
12380        int[] allUsers;
12381        boolean[] perUserInstalled;
12382        synchronized (mPackages) {
12383            PackageSetting ps = mSettings.mPackages.get(packageName);
12384            allUsers = sUserManager.getUserIds();
12385            perUserInstalled = new boolean[allUsers.length];
12386            for (int i = 0; i < allUsers.length; i++) {
12387                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12388            }
12389        }
12390
12391        synchronized (mInstallLock) {
12392            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
12393            res = deletePackageLI(packageName, removeForUser,
12394                    true, allUsers, perUserInstalled,
12395                    flags | REMOVE_CHATTY, info, true);
12396            systemUpdate = info.isRemovedPackageSystemUpdate;
12397            if (res && !systemUpdate && mPackages.get(packageName) == null) {
12398                removedForAllUsers = true;
12399            }
12400            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
12401                    + " removedForAllUsers=" + removedForAllUsers);
12402        }
12403
12404        if (res) {
12405            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
12406
12407            // If the removed package was a system update, the old system package
12408            // was re-enabled; we need to broadcast this information
12409            if (systemUpdate) {
12410                Bundle extras = new Bundle(1);
12411                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
12412                        ? info.removedAppId : info.uid);
12413                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12414
12415                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
12416                        extras, null, null, null);
12417                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
12418                        extras, null, null, null);
12419                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
12420                        null, packageName, null, null);
12421            }
12422        }
12423        // Force a gc here.
12424        Runtime.getRuntime().gc();
12425        // Delete the resources here after sending the broadcast to let
12426        // other processes clean up before deleting resources.
12427        if (info.args != null) {
12428            synchronized (mInstallLock) {
12429                info.args.doPostDeleteLI(true);
12430            }
12431        }
12432
12433        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
12434    }
12435
12436    class PackageRemovedInfo {
12437        String removedPackage;
12438        int uid = -1;
12439        int removedAppId = -1;
12440        int[] removedUsers = null;
12441        boolean isRemovedPackageSystemUpdate = false;
12442        // Clean up resources deleted packages.
12443        InstallArgs args = null;
12444
12445        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
12446            Bundle extras = new Bundle(1);
12447            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
12448            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
12449            if (replacing) {
12450                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12451            }
12452            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
12453            if (removedPackage != null) {
12454                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
12455                        extras, null, null, removedUsers);
12456                if (fullRemove && !replacing) {
12457                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
12458                            extras, null, null, removedUsers);
12459                }
12460            }
12461            if (removedAppId >= 0) {
12462                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
12463                        removedUsers);
12464            }
12465        }
12466    }
12467
12468    /*
12469     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
12470     * flag is not set, the data directory is removed as well.
12471     * make sure this flag is set for partially installed apps. If not its meaningless to
12472     * delete a partially installed application.
12473     */
12474    private void removePackageDataLI(PackageSetting ps,
12475            int[] allUserHandles, boolean[] perUserInstalled,
12476            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
12477        String packageName = ps.name;
12478        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
12479        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
12480        // Retrieve object to delete permissions for shared user later on
12481        final PackageSetting deletedPs;
12482        // reader
12483        synchronized (mPackages) {
12484            deletedPs = mSettings.mPackages.get(packageName);
12485            if (outInfo != null) {
12486                outInfo.removedPackage = packageName;
12487                outInfo.removedUsers = deletedPs != null
12488                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
12489                        : null;
12490            }
12491        }
12492        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12493            removeDataDirsLI(ps.volumeUuid, packageName);
12494            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
12495        }
12496        // writer
12497        synchronized (mPackages) {
12498            if (deletedPs != null) {
12499                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12500                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
12501                    clearDefaultBrowserIfNeeded(packageName);
12502                    if (outInfo != null) {
12503                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
12504                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
12505                    }
12506                    updatePermissionsLPw(deletedPs.name, null, 0);
12507                    if (deletedPs.sharedUser != null) {
12508                        // Remove permissions associated with package. Since runtime
12509                        // permissions are per user we have to kill the removed package
12510                        // or packages running under the shared user of the removed
12511                        // package if revoking the permissions requested only by the removed
12512                        // package is successful and this causes a change in gids.
12513                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12514                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
12515                                    userId);
12516                            if (userIdToKill == UserHandle.USER_ALL
12517                                    || userIdToKill >= UserHandle.USER_OWNER) {
12518                                // If gids changed for this user, kill all affected packages.
12519                                mHandler.post(new Runnable() {
12520                                    @Override
12521                                    public void run() {
12522                                        // This has to happen with no lock held.
12523                                        killSettingPackagesForUser(deletedPs, userIdToKill,
12524                                                KILL_APP_REASON_GIDS_CHANGED);
12525                                    }
12526                                });
12527                            break;
12528                            }
12529                        }
12530                    }
12531                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
12532                }
12533                // make sure to preserve per-user disabled state if this removal was just
12534                // a downgrade of a system app to the factory package
12535                if (allUserHandles != null && perUserInstalled != null) {
12536                    if (DEBUG_REMOVE) {
12537                        Slog.d(TAG, "Propagating install state across downgrade");
12538                    }
12539                    for (int i = 0; i < allUserHandles.length; i++) {
12540                        if (DEBUG_REMOVE) {
12541                            Slog.d(TAG, "    user " + allUserHandles[i]
12542                                    + " => " + perUserInstalled[i]);
12543                        }
12544                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12545                    }
12546                }
12547            }
12548            // can downgrade to reader
12549            if (writeSettings) {
12550                // Save settings now
12551                mSettings.writeLPr();
12552            }
12553        }
12554        if (outInfo != null) {
12555            // A user ID was deleted here. Go through all users and remove it
12556            // from KeyStore.
12557            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
12558        }
12559    }
12560
12561    static boolean locationIsPrivileged(File path) {
12562        try {
12563            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
12564                    .getCanonicalPath();
12565            return path.getCanonicalPath().startsWith(privilegedAppDir);
12566        } catch (IOException e) {
12567            Slog.e(TAG, "Unable to access code path " + path);
12568        }
12569        return false;
12570    }
12571
12572    /*
12573     * Tries to delete system package.
12574     */
12575    private boolean deleteSystemPackageLI(PackageSetting newPs,
12576            int[] allUserHandles, boolean[] perUserInstalled,
12577            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
12578        final boolean applyUserRestrictions
12579                = (allUserHandles != null) && (perUserInstalled != null);
12580        PackageSetting disabledPs = null;
12581        // Confirm if the system package has been updated
12582        // An updated system app can be deleted. This will also have to restore
12583        // the system pkg from system partition
12584        // reader
12585        synchronized (mPackages) {
12586            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
12587        }
12588        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
12589                + " disabledPs=" + disabledPs);
12590        if (disabledPs == null) {
12591            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
12592            return false;
12593        } else if (DEBUG_REMOVE) {
12594            Slog.d(TAG, "Deleting system pkg from data partition");
12595        }
12596        if (DEBUG_REMOVE) {
12597            if (applyUserRestrictions) {
12598                Slog.d(TAG, "Remembering install states:");
12599                for (int i = 0; i < allUserHandles.length; i++) {
12600                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
12601                }
12602            }
12603        }
12604        // Delete the updated package
12605        outInfo.isRemovedPackageSystemUpdate = true;
12606        if (disabledPs.versionCode < newPs.versionCode) {
12607            // Delete data for downgrades
12608            flags &= ~PackageManager.DELETE_KEEP_DATA;
12609        } else {
12610            // Preserve data by setting flag
12611            flags |= PackageManager.DELETE_KEEP_DATA;
12612        }
12613        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
12614                allUserHandles, perUserInstalled, outInfo, writeSettings);
12615        if (!ret) {
12616            return false;
12617        }
12618        // writer
12619        synchronized (mPackages) {
12620            // Reinstate the old system package
12621            mSettings.enableSystemPackageLPw(newPs.name);
12622            // Remove any native libraries from the upgraded package.
12623            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
12624        }
12625        // Install the system package
12626        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
12627        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
12628        if (locationIsPrivileged(disabledPs.codePath)) {
12629            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12630        }
12631
12632        final PackageParser.Package newPkg;
12633        try {
12634            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
12635        } catch (PackageManagerException e) {
12636            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
12637            return false;
12638        }
12639
12640        // writer
12641        synchronized (mPackages) {
12642            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
12643            updatePermissionsLPw(newPkg.packageName, newPkg,
12644                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
12645            if (applyUserRestrictions) {
12646                if (DEBUG_REMOVE) {
12647                    Slog.d(TAG, "Propagating install state across reinstall");
12648                }
12649                for (int i = 0; i < allUserHandles.length; i++) {
12650                    if (DEBUG_REMOVE) {
12651                        Slog.d(TAG, "    user " + allUserHandles[i]
12652                                + " => " + perUserInstalled[i]);
12653                    }
12654                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12655                }
12656                // Regardless of writeSettings we need to ensure that this restriction
12657                // state propagation is persisted
12658                mSettings.writeAllUsersPackageRestrictionsLPr();
12659            }
12660            // can downgrade to reader here
12661            if (writeSettings) {
12662                mSettings.writeLPr();
12663            }
12664        }
12665        return true;
12666    }
12667
12668    private boolean deleteInstalledPackageLI(PackageSetting ps,
12669            boolean deleteCodeAndResources, int flags,
12670            int[] allUserHandles, boolean[] perUserInstalled,
12671            PackageRemovedInfo outInfo, boolean writeSettings) {
12672        if (outInfo != null) {
12673            outInfo.uid = ps.appId;
12674        }
12675
12676        // Delete package data from internal structures and also remove data if flag is set
12677        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
12678
12679        // Delete application code and resources
12680        if (deleteCodeAndResources && (outInfo != null)) {
12681            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
12682                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
12683            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
12684        }
12685        return true;
12686    }
12687
12688    @Override
12689    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
12690            int userId) {
12691        mContext.enforceCallingOrSelfPermission(
12692                android.Manifest.permission.DELETE_PACKAGES, null);
12693        synchronized (mPackages) {
12694            PackageSetting ps = mSettings.mPackages.get(packageName);
12695            if (ps == null) {
12696                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
12697                return false;
12698            }
12699            if (!ps.getInstalled(userId)) {
12700                // Can't block uninstall for an app that is not installed or enabled.
12701                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
12702                return false;
12703            }
12704            ps.setBlockUninstall(blockUninstall, userId);
12705            mSettings.writePackageRestrictionsLPr(userId);
12706        }
12707        return true;
12708    }
12709
12710    @Override
12711    public boolean getBlockUninstallForUser(String packageName, int userId) {
12712        synchronized (mPackages) {
12713            PackageSetting ps = mSettings.mPackages.get(packageName);
12714            if (ps == null) {
12715                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
12716                return false;
12717            }
12718            return ps.getBlockUninstall(userId);
12719        }
12720    }
12721
12722    /*
12723     * This method handles package deletion in general
12724     */
12725    private boolean deletePackageLI(String packageName, UserHandle user,
12726            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
12727            int flags, PackageRemovedInfo outInfo,
12728            boolean writeSettings) {
12729        if (packageName == null) {
12730            Slog.w(TAG, "Attempt to delete null packageName.");
12731            return false;
12732        }
12733        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
12734        PackageSetting ps;
12735        boolean dataOnly = false;
12736        int removeUser = -1;
12737        int appId = -1;
12738        synchronized (mPackages) {
12739            ps = mSettings.mPackages.get(packageName);
12740            if (ps == null) {
12741                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12742                return false;
12743            }
12744            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
12745                    && user.getIdentifier() != UserHandle.USER_ALL) {
12746                // The caller is asking that the package only be deleted for a single
12747                // user.  To do this, we just mark its uninstalled state and delete
12748                // its data.  If this is a system app, we only allow this to happen if
12749                // they have set the special DELETE_SYSTEM_APP which requests different
12750                // semantics than normal for uninstalling system apps.
12751                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
12752                ps.setUserState(user.getIdentifier(),
12753                        COMPONENT_ENABLED_STATE_DEFAULT,
12754                        false, //installed
12755                        true,  //stopped
12756                        true,  //notLaunched
12757                        false, //hidden
12758                        null, null, null,
12759                        false, // blockUninstall
12760                        INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
12761                if (!isSystemApp(ps)) {
12762                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
12763                        // Other user still have this package installed, so all
12764                        // we need to do is clear this user's data and save that
12765                        // it is uninstalled.
12766                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
12767                        removeUser = user.getIdentifier();
12768                        appId = ps.appId;
12769                        scheduleWritePackageRestrictionsLocked(removeUser);
12770                    } else {
12771                        // We need to set it back to 'installed' so the uninstall
12772                        // broadcasts will be sent correctly.
12773                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
12774                        ps.setInstalled(true, user.getIdentifier());
12775                    }
12776                } else {
12777                    // This is a system app, so we assume that the
12778                    // other users still have this package installed, so all
12779                    // we need to do is clear this user's data and save that
12780                    // it is uninstalled.
12781                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
12782                    removeUser = user.getIdentifier();
12783                    appId = ps.appId;
12784                    scheduleWritePackageRestrictionsLocked(removeUser);
12785                }
12786            }
12787        }
12788
12789        if (removeUser >= 0) {
12790            // From above, we determined that we are deleting this only
12791            // for a single user.  Continue the work here.
12792            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
12793            if (outInfo != null) {
12794                outInfo.removedPackage = packageName;
12795                outInfo.removedAppId = appId;
12796                outInfo.removedUsers = new int[] {removeUser};
12797            }
12798            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
12799            removeKeystoreDataIfNeeded(removeUser, appId);
12800            schedulePackageCleaning(packageName, removeUser, false);
12801            synchronized (mPackages) {
12802                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
12803                    scheduleWritePackageRestrictionsLocked(removeUser);
12804                }
12805                revokeRuntimePermissionsAndClearAllFlagsLocked(ps.getPermissionsState(),
12806                        removeUser);
12807            }
12808            return true;
12809        }
12810
12811        if (dataOnly) {
12812            // Delete application data first
12813            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
12814            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
12815            return true;
12816        }
12817
12818        boolean ret = false;
12819        if (isSystemApp(ps)) {
12820            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
12821            // When an updated system application is deleted we delete the existing resources as well and
12822            // fall back to existing code in system partition
12823            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
12824                    flags, outInfo, writeSettings);
12825        } else {
12826            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
12827            // Kill application pre-emptively especially for apps on sd.
12828            killApplication(packageName, ps.appId, "uninstall pkg");
12829            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
12830                    allUserHandles, perUserInstalled,
12831                    outInfo, writeSettings);
12832        }
12833
12834        return ret;
12835    }
12836
12837    private final class ClearStorageConnection implements ServiceConnection {
12838        IMediaContainerService mContainerService;
12839
12840        @Override
12841        public void onServiceConnected(ComponentName name, IBinder service) {
12842            synchronized (this) {
12843                mContainerService = IMediaContainerService.Stub.asInterface(service);
12844                notifyAll();
12845            }
12846        }
12847
12848        @Override
12849        public void onServiceDisconnected(ComponentName name) {
12850        }
12851    }
12852
12853    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
12854        final boolean mounted;
12855        if (Environment.isExternalStorageEmulated()) {
12856            mounted = true;
12857        } else {
12858            final String status = Environment.getExternalStorageState();
12859
12860            mounted = status.equals(Environment.MEDIA_MOUNTED)
12861                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
12862        }
12863
12864        if (!mounted) {
12865            return;
12866        }
12867
12868        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
12869        int[] users;
12870        if (userId == UserHandle.USER_ALL) {
12871            users = sUserManager.getUserIds();
12872        } else {
12873            users = new int[] { userId };
12874        }
12875        final ClearStorageConnection conn = new ClearStorageConnection();
12876        if (mContext.bindServiceAsUser(
12877                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
12878            try {
12879                for (int curUser : users) {
12880                    long timeout = SystemClock.uptimeMillis() + 5000;
12881                    synchronized (conn) {
12882                        long now = SystemClock.uptimeMillis();
12883                        while (conn.mContainerService == null && now < timeout) {
12884                            try {
12885                                conn.wait(timeout - now);
12886                            } catch (InterruptedException e) {
12887                            }
12888                        }
12889                    }
12890                    if (conn.mContainerService == null) {
12891                        return;
12892                    }
12893
12894                    final UserEnvironment userEnv = new UserEnvironment(curUser);
12895                    clearDirectory(conn.mContainerService,
12896                            userEnv.buildExternalStorageAppCacheDirs(packageName));
12897                    if (allData) {
12898                        clearDirectory(conn.mContainerService,
12899                                userEnv.buildExternalStorageAppDataDirs(packageName));
12900                        clearDirectory(conn.mContainerService,
12901                                userEnv.buildExternalStorageAppMediaDirs(packageName));
12902                    }
12903                }
12904            } finally {
12905                mContext.unbindService(conn);
12906            }
12907        }
12908    }
12909
12910    @Override
12911    public void clearApplicationUserData(final String packageName,
12912            final IPackageDataObserver observer, final int userId) {
12913        mContext.enforceCallingOrSelfPermission(
12914                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
12915        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
12916        // Queue up an async operation since the package deletion may take a little while.
12917        mHandler.post(new Runnable() {
12918            public void run() {
12919                mHandler.removeCallbacks(this);
12920                final boolean succeeded;
12921                synchronized (mInstallLock) {
12922                    succeeded = clearApplicationUserDataLI(packageName, userId);
12923                }
12924                clearExternalStorageDataSync(packageName, userId, true);
12925                if (succeeded) {
12926                    // invoke DeviceStorageMonitor's update method to clear any notifications
12927                    DeviceStorageMonitorInternal
12928                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
12929                    if (dsm != null) {
12930                        dsm.checkMemory();
12931                    }
12932                }
12933                if(observer != null) {
12934                    try {
12935                        observer.onRemoveCompleted(packageName, succeeded);
12936                    } catch (RemoteException e) {
12937                        Log.i(TAG, "Observer no longer exists.");
12938                    }
12939                } //end if observer
12940            } //end run
12941        });
12942    }
12943
12944    private boolean clearApplicationUserDataLI(String packageName, int userId) {
12945        if (packageName == null) {
12946            Slog.w(TAG, "Attempt to delete null packageName.");
12947            return false;
12948        }
12949
12950        // Try finding details about the requested package
12951        PackageParser.Package pkg;
12952        synchronized (mPackages) {
12953            pkg = mPackages.get(packageName);
12954            if (pkg == null) {
12955                final PackageSetting ps = mSettings.mPackages.get(packageName);
12956                if (ps != null) {
12957                    pkg = ps.pkg;
12958                }
12959            }
12960
12961            if (pkg == null) {
12962                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12963                return false;
12964            }
12965
12966            PackageSetting ps = (PackageSetting) pkg.mExtras;
12967            PermissionsState permissionsState = ps.getPermissionsState();
12968            revokeRuntimePermissionsAndClearUserSetFlagsLocked(permissionsState, userId);
12969        }
12970
12971        // Always delete data directories for package, even if we found no other
12972        // record of app. This helps users recover from UID mismatches without
12973        // resorting to a full data wipe.
12974        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
12975        if (retCode < 0) {
12976            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
12977            return false;
12978        }
12979
12980        final int appId = pkg.applicationInfo.uid;
12981        removeKeystoreDataIfNeeded(userId, appId);
12982
12983        // Create a native library symlink only if we have native libraries
12984        // and if the native libraries are 32 bit libraries. We do not provide
12985        // this symlink for 64 bit libraries.
12986        if (pkg.applicationInfo.primaryCpuAbi != null &&
12987                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
12988            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
12989            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
12990                    nativeLibPath, userId) < 0) {
12991                Slog.w(TAG, "Failed linking native library dir");
12992                return false;
12993            }
12994        }
12995
12996        return true;
12997    }
12998
12999
13000    /**
13001     * Revokes granted runtime permissions and clears resettable flags
13002     * which are flags that can be set by a user interaction.
13003     *
13004     * @param permissionsState The permission state to reset.
13005     * @param userId The device user for which to do a reset.
13006     */
13007    private void revokeRuntimePermissionsAndClearUserSetFlagsLocked(
13008            PermissionsState permissionsState, int userId) {
13009        final int userSetFlags = PackageManager.FLAG_PERMISSION_USER_SET
13010                | PackageManager.FLAG_PERMISSION_USER_FIXED
13011                | PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13012
13013        revokeRuntimePermissionsAndClearFlagsLocked(permissionsState, userId, userSetFlags);
13014    }
13015
13016    /**
13017     * Revokes granted runtime permissions and clears all flags.
13018     *
13019     * @param permissionsState The permission state to reset.
13020     * @param userId The device user for which to do a reset.
13021     */
13022    private void revokeRuntimePermissionsAndClearAllFlagsLocked(
13023            PermissionsState permissionsState, int userId) {
13024        revokeRuntimePermissionsAndClearFlagsLocked(permissionsState, userId,
13025                PackageManager.MASK_PERMISSION_FLAGS);
13026    }
13027
13028    /**
13029     * Revokes granted runtime permissions and clears certain flags.
13030     *
13031     * @param permissionsState The permission state to reset.
13032     * @param userId The device user for which to do a reset.
13033     * @param flags The flags that is going to be reset.
13034     */
13035    private void revokeRuntimePermissionsAndClearFlagsLocked(
13036            PermissionsState permissionsState, final int userId, int flags) {
13037        boolean needsWrite = false;
13038
13039        for (PermissionState state : permissionsState.getRuntimePermissionStates(userId)) {
13040            BasePermission bp = mSettings.mPermissions.get(state.getName());
13041            if (bp != null) {
13042                permissionsState.revokeRuntimePermission(bp, userId);
13043                permissionsState.updatePermissionFlags(bp, userId, flags, 0);
13044                needsWrite = true;
13045            }
13046        }
13047
13048        // Ensure default permissions are never cleared.
13049        mHandler.post(new Runnable() {
13050            @Override
13051            public void run() {
13052                mDefaultPermissionPolicy.grantDefaultPermissions(userId);
13053            }
13054        });
13055
13056        if (needsWrite) {
13057            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
13058        }
13059    }
13060
13061    /**
13062     * Remove entries from the keystore daemon. Will only remove it if the
13063     * {@code appId} is valid.
13064     */
13065    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
13066        if (appId < 0) {
13067            return;
13068        }
13069
13070        final KeyStore keyStore = KeyStore.getInstance();
13071        if (keyStore != null) {
13072            if (userId == UserHandle.USER_ALL) {
13073                for (final int individual : sUserManager.getUserIds()) {
13074                    keyStore.clearUid(UserHandle.getUid(individual, appId));
13075                }
13076            } else {
13077                keyStore.clearUid(UserHandle.getUid(userId, appId));
13078            }
13079        } else {
13080            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
13081        }
13082    }
13083
13084    @Override
13085    public void deleteApplicationCacheFiles(final String packageName,
13086            final IPackageDataObserver observer) {
13087        mContext.enforceCallingOrSelfPermission(
13088                android.Manifest.permission.DELETE_CACHE_FILES, null);
13089        // Queue up an async operation since the package deletion may take a little while.
13090        final int userId = UserHandle.getCallingUserId();
13091        mHandler.post(new Runnable() {
13092            public void run() {
13093                mHandler.removeCallbacks(this);
13094                final boolean succeded;
13095                synchronized (mInstallLock) {
13096                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
13097                }
13098                clearExternalStorageDataSync(packageName, userId, false);
13099                if (observer != null) {
13100                    try {
13101                        observer.onRemoveCompleted(packageName, succeded);
13102                    } catch (RemoteException e) {
13103                        Log.i(TAG, "Observer no longer exists.");
13104                    }
13105                } //end if observer
13106            } //end run
13107        });
13108    }
13109
13110    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
13111        if (packageName == null) {
13112            Slog.w(TAG, "Attempt to delete null packageName.");
13113            return false;
13114        }
13115        PackageParser.Package p;
13116        synchronized (mPackages) {
13117            p = mPackages.get(packageName);
13118        }
13119        if (p == null) {
13120            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13121            return false;
13122        }
13123        final ApplicationInfo applicationInfo = p.applicationInfo;
13124        if (applicationInfo == null) {
13125            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13126            return false;
13127        }
13128        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
13129        if (retCode < 0) {
13130            Slog.w(TAG, "Couldn't remove cache files for package: "
13131                       + packageName + " u" + userId);
13132            return false;
13133        }
13134        return true;
13135    }
13136
13137    @Override
13138    public void getPackageSizeInfo(final String packageName, int userHandle,
13139            final IPackageStatsObserver observer) {
13140        mContext.enforceCallingOrSelfPermission(
13141                android.Manifest.permission.GET_PACKAGE_SIZE, null);
13142        if (packageName == null) {
13143            throw new IllegalArgumentException("Attempt to get size of null packageName");
13144        }
13145
13146        PackageStats stats = new PackageStats(packageName, userHandle);
13147
13148        /*
13149         * Queue up an async operation since the package measurement may take a
13150         * little while.
13151         */
13152        Message msg = mHandler.obtainMessage(INIT_COPY);
13153        msg.obj = new MeasureParams(stats, observer);
13154        mHandler.sendMessage(msg);
13155    }
13156
13157    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
13158            PackageStats pStats) {
13159        if (packageName == null) {
13160            Slog.w(TAG, "Attempt to get size of null packageName.");
13161            return false;
13162        }
13163        PackageParser.Package p;
13164        boolean dataOnly = false;
13165        String libDirRoot = null;
13166        String asecPath = null;
13167        PackageSetting ps = null;
13168        synchronized (mPackages) {
13169            p = mPackages.get(packageName);
13170            ps = mSettings.mPackages.get(packageName);
13171            if(p == null) {
13172                dataOnly = true;
13173                if((ps == null) || (ps.pkg == null)) {
13174                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13175                    return false;
13176                }
13177                p = ps.pkg;
13178            }
13179            if (ps != null) {
13180                libDirRoot = ps.legacyNativeLibraryPathString;
13181            }
13182            if (p != null && (isExternal(p) || p.isForwardLocked())) {
13183                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
13184                if (secureContainerId != null) {
13185                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
13186                }
13187            }
13188        }
13189        String publicSrcDir = null;
13190        if(!dataOnly) {
13191            final ApplicationInfo applicationInfo = p.applicationInfo;
13192            if (applicationInfo == null) {
13193                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13194                return false;
13195            }
13196            if (p.isForwardLocked()) {
13197                publicSrcDir = applicationInfo.getBaseResourcePath();
13198            }
13199        }
13200        // TODO: extend to measure size of split APKs
13201        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
13202        // not just the first level.
13203        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
13204        // just the primary.
13205        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
13206        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath,
13207                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
13208        if (res < 0) {
13209            return false;
13210        }
13211
13212        // Fix-up for forward-locked applications in ASEC containers.
13213        if (!isExternal(p)) {
13214            pStats.codeSize += pStats.externalCodeSize;
13215            pStats.externalCodeSize = 0L;
13216        }
13217
13218        return true;
13219    }
13220
13221
13222    @Override
13223    public void addPackageToPreferred(String packageName) {
13224        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
13225    }
13226
13227    @Override
13228    public void removePackageFromPreferred(String packageName) {
13229        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
13230    }
13231
13232    @Override
13233    public List<PackageInfo> getPreferredPackages(int flags) {
13234        return new ArrayList<PackageInfo>();
13235    }
13236
13237    private int getUidTargetSdkVersionLockedLPr(int uid) {
13238        Object obj = mSettings.getUserIdLPr(uid);
13239        if (obj instanceof SharedUserSetting) {
13240            final SharedUserSetting sus = (SharedUserSetting) obj;
13241            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
13242            final Iterator<PackageSetting> it = sus.packages.iterator();
13243            while (it.hasNext()) {
13244                final PackageSetting ps = it.next();
13245                if (ps.pkg != null) {
13246                    int v = ps.pkg.applicationInfo.targetSdkVersion;
13247                    if (v < vers) vers = v;
13248                }
13249            }
13250            return vers;
13251        } else if (obj instanceof PackageSetting) {
13252            final PackageSetting ps = (PackageSetting) obj;
13253            if (ps.pkg != null) {
13254                return ps.pkg.applicationInfo.targetSdkVersion;
13255            }
13256        }
13257        return Build.VERSION_CODES.CUR_DEVELOPMENT;
13258    }
13259
13260    @Override
13261    public void addPreferredActivity(IntentFilter filter, int match,
13262            ComponentName[] set, ComponentName activity, int userId) {
13263        addPreferredActivityInternal(filter, match, set, activity, true, userId,
13264                "Adding preferred");
13265    }
13266
13267    private void addPreferredActivityInternal(IntentFilter filter, int match,
13268            ComponentName[] set, ComponentName activity, boolean always, int userId,
13269            String opname) {
13270        // writer
13271        int callingUid = Binder.getCallingUid();
13272        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
13273        if (filter.countActions() == 0) {
13274            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13275            return;
13276        }
13277        synchronized (mPackages) {
13278            if (mContext.checkCallingOrSelfPermission(
13279                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13280                    != PackageManager.PERMISSION_GRANTED) {
13281                if (getUidTargetSdkVersionLockedLPr(callingUid)
13282                        < Build.VERSION_CODES.FROYO) {
13283                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
13284                            + callingUid);
13285                    return;
13286                }
13287                mContext.enforceCallingOrSelfPermission(
13288                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13289            }
13290
13291            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
13292            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
13293                    + userId + ":");
13294            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13295            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
13296            scheduleWritePackageRestrictionsLocked(userId);
13297        }
13298    }
13299
13300    @Override
13301    public void replacePreferredActivity(IntentFilter filter, int match,
13302            ComponentName[] set, ComponentName activity, int userId) {
13303        if (filter.countActions() != 1) {
13304            throw new IllegalArgumentException(
13305                    "replacePreferredActivity expects filter to have only 1 action.");
13306        }
13307        if (filter.countDataAuthorities() != 0
13308                || filter.countDataPaths() != 0
13309                || filter.countDataSchemes() > 1
13310                || filter.countDataTypes() != 0) {
13311            throw new IllegalArgumentException(
13312                    "replacePreferredActivity expects filter to have no data authorities, " +
13313                    "paths, or types; and at most one scheme.");
13314        }
13315
13316        final int callingUid = Binder.getCallingUid();
13317        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
13318        synchronized (mPackages) {
13319            if (mContext.checkCallingOrSelfPermission(
13320                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13321                    != PackageManager.PERMISSION_GRANTED) {
13322                if (getUidTargetSdkVersionLockedLPr(callingUid)
13323                        < Build.VERSION_CODES.FROYO) {
13324                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
13325                            + Binder.getCallingUid());
13326                    return;
13327                }
13328                mContext.enforceCallingOrSelfPermission(
13329                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13330            }
13331
13332            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13333            if (pir != null) {
13334                // Get all of the existing entries that exactly match this filter.
13335                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
13336                if (existing != null && existing.size() == 1) {
13337                    PreferredActivity cur = existing.get(0);
13338                    if (DEBUG_PREFERRED) {
13339                        Slog.i(TAG, "Checking replace of preferred:");
13340                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13341                        if (!cur.mPref.mAlways) {
13342                            Slog.i(TAG, "  -- CUR; not mAlways!");
13343                        } else {
13344                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
13345                            Slog.i(TAG, "  -- CUR: mSet="
13346                                    + Arrays.toString(cur.mPref.mSetComponents));
13347                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
13348                            Slog.i(TAG, "  -- NEW: mMatch="
13349                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
13350                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
13351                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
13352                        }
13353                    }
13354                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
13355                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
13356                            && cur.mPref.sameSet(set)) {
13357                        // Setting the preferred activity to what it happens to be already
13358                        if (DEBUG_PREFERRED) {
13359                            Slog.i(TAG, "Replacing with same preferred activity "
13360                                    + cur.mPref.mShortComponent + " for user "
13361                                    + userId + ":");
13362                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13363                        }
13364                        return;
13365                    }
13366                }
13367
13368                if (existing != null) {
13369                    if (DEBUG_PREFERRED) {
13370                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
13371                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13372                    }
13373                    for (int i = 0; i < existing.size(); i++) {
13374                        PreferredActivity pa = existing.get(i);
13375                        if (DEBUG_PREFERRED) {
13376                            Slog.i(TAG, "Removing existing preferred activity "
13377                                    + pa.mPref.mComponent + ":");
13378                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
13379                        }
13380                        pir.removeFilter(pa);
13381                    }
13382                }
13383            }
13384            addPreferredActivityInternal(filter, match, set, activity, true, userId,
13385                    "Replacing preferred");
13386        }
13387    }
13388
13389    @Override
13390    public void clearPackagePreferredActivities(String packageName) {
13391        final int uid = Binder.getCallingUid();
13392        // writer
13393        synchronized (mPackages) {
13394            PackageParser.Package pkg = mPackages.get(packageName);
13395            if (pkg == null || pkg.applicationInfo.uid != uid) {
13396                if (mContext.checkCallingOrSelfPermission(
13397                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13398                        != PackageManager.PERMISSION_GRANTED) {
13399                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
13400                            < Build.VERSION_CODES.FROYO) {
13401                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
13402                                + Binder.getCallingUid());
13403                        return;
13404                    }
13405                    mContext.enforceCallingOrSelfPermission(
13406                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13407                }
13408            }
13409
13410            int user = UserHandle.getCallingUserId();
13411            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
13412                scheduleWritePackageRestrictionsLocked(user);
13413            }
13414        }
13415    }
13416
13417    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13418    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
13419        ArrayList<PreferredActivity> removed = null;
13420        boolean changed = false;
13421        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13422            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
13423            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13424            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
13425                continue;
13426            }
13427            Iterator<PreferredActivity> it = pir.filterIterator();
13428            while (it.hasNext()) {
13429                PreferredActivity pa = it.next();
13430                // Mark entry for removal only if it matches the package name
13431                // and the entry is of type "always".
13432                if (packageName == null ||
13433                        (pa.mPref.mComponent.getPackageName().equals(packageName)
13434                                && pa.mPref.mAlways)) {
13435                    if (removed == null) {
13436                        removed = new ArrayList<PreferredActivity>();
13437                    }
13438                    removed.add(pa);
13439                }
13440            }
13441            if (removed != null) {
13442                for (int j=0; j<removed.size(); j++) {
13443                    PreferredActivity pa = removed.get(j);
13444                    pir.removeFilter(pa);
13445                }
13446                changed = true;
13447            }
13448        }
13449        return changed;
13450    }
13451
13452    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13453    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
13454        if (userId == UserHandle.USER_ALL) {
13455            if (mSettings.removeIntentFilterVerificationLPw(packageName,
13456                    sUserManager.getUserIds())) {
13457                for (int oneUserId : sUserManager.getUserIds()) {
13458                    scheduleWritePackageRestrictionsLocked(oneUserId);
13459                }
13460            }
13461        } else {
13462            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
13463                scheduleWritePackageRestrictionsLocked(userId);
13464            }
13465        }
13466    }
13467
13468
13469    void clearDefaultBrowserIfNeeded(String packageName) {
13470        for (int oneUserId : sUserManager.getUserIds()) {
13471            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
13472            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
13473            if (packageName.equals(defaultBrowserPackageName)) {
13474                setDefaultBrowserPackageName(null, oneUserId);
13475            }
13476        }
13477    }
13478
13479    @Override
13480    public void resetPreferredActivities(int userId) {
13481        mContext.enforceCallingOrSelfPermission(
13482                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13483        // writer
13484        synchronized (mPackages) {
13485            clearPackagePreferredActivitiesLPw(null, userId);
13486            mSettings.applyDefaultPreferredAppsLPw(this, userId);
13487            applyFactoryDefaultBrowserLPw(userId);
13488
13489            scheduleWritePackageRestrictionsLocked(userId);
13490        }
13491    }
13492
13493    @Override
13494    public int getPreferredActivities(List<IntentFilter> outFilters,
13495            List<ComponentName> outActivities, String packageName) {
13496
13497        int num = 0;
13498        final int userId = UserHandle.getCallingUserId();
13499        // reader
13500        synchronized (mPackages) {
13501            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13502            if (pir != null) {
13503                final Iterator<PreferredActivity> it = pir.filterIterator();
13504                while (it.hasNext()) {
13505                    final PreferredActivity pa = it.next();
13506                    if (packageName == null
13507                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
13508                                    && pa.mPref.mAlways)) {
13509                        if (outFilters != null) {
13510                            outFilters.add(new IntentFilter(pa));
13511                        }
13512                        if (outActivities != null) {
13513                            outActivities.add(pa.mPref.mComponent);
13514                        }
13515                    }
13516                }
13517            }
13518        }
13519
13520        return num;
13521    }
13522
13523    @Override
13524    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
13525            int userId) {
13526        int callingUid = Binder.getCallingUid();
13527        if (callingUid != Process.SYSTEM_UID) {
13528            throw new SecurityException(
13529                    "addPersistentPreferredActivity can only be run by the system");
13530        }
13531        if (filter.countActions() == 0) {
13532            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13533            return;
13534        }
13535        synchronized (mPackages) {
13536            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
13537                    " :");
13538            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13539            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
13540                    new PersistentPreferredActivity(filter, activity));
13541            scheduleWritePackageRestrictionsLocked(userId);
13542        }
13543    }
13544
13545    @Override
13546    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
13547        int callingUid = Binder.getCallingUid();
13548        if (callingUid != Process.SYSTEM_UID) {
13549            throw new SecurityException(
13550                    "clearPackagePersistentPreferredActivities can only be run by the system");
13551        }
13552        ArrayList<PersistentPreferredActivity> removed = null;
13553        boolean changed = false;
13554        synchronized (mPackages) {
13555            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
13556                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
13557                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
13558                        .valueAt(i);
13559                if (userId != thisUserId) {
13560                    continue;
13561                }
13562                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
13563                while (it.hasNext()) {
13564                    PersistentPreferredActivity ppa = it.next();
13565                    // Mark entry for removal only if it matches the package name.
13566                    if (ppa.mComponent.getPackageName().equals(packageName)) {
13567                        if (removed == null) {
13568                            removed = new ArrayList<PersistentPreferredActivity>();
13569                        }
13570                        removed.add(ppa);
13571                    }
13572                }
13573                if (removed != null) {
13574                    for (int j=0; j<removed.size(); j++) {
13575                        PersistentPreferredActivity ppa = removed.get(j);
13576                        ppir.removeFilter(ppa);
13577                    }
13578                    changed = true;
13579                }
13580            }
13581
13582            if (changed) {
13583                scheduleWritePackageRestrictionsLocked(userId);
13584            }
13585        }
13586    }
13587
13588    /**
13589     * Common machinery for picking apart a restored XML blob and passing
13590     * it to a caller-supplied functor to be applied to the running system.
13591     */
13592    private void restoreFromXml(XmlPullParser parser, int userId,
13593            String expectedStartTag, BlobXmlRestorer functor)
13594            throws IOException, XmlPullParserException {
13595        int type;
13596        while ((type = parser.next()) != XmlPullParser.START_TAG
13597                && type != XmlPullParser.END_DOCUMENT) {
13598        }
13599        if (type != XmlPullParser.START_TAG) {
13600            // oops didn't find a start tag?!
13601            if (DEBUG_BACKUP) {
13602                Slog.e(TAG, "Didn't find start tag during restore");
13603            }
13604            return;
13605        }
13606
13607        // this is supposed to be TAG_PREFERRED_BACKUP
13608        if (!expectedStartTag.equals(parser.getName())) {
13609            if (DEBUG_BACKUP) {
13610                Slog.e(TAG, "Found unexpected tag " + parser.getName());
13611            }
13612            return;
13613        }
13614
13615        // skip interfering stuff, then we're aligned with the backing implementation
13616        while ((type = parser.next()) == XmlPullParser.TEXT) { }
13617        functor.apply(parser, userId);
13618    }
13619
13620    private interface BlobXmlRestorer {
13621        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
13622    }
13623
13624    /**
13625     * Non-Binder method, support for the backup/restore mechanism: write the
13626     * full set of preferred activities in its canonical XML format.  Returns the
13627     * XML output as a byte array, or null if there is none.
13628     */
13629    @Override
13630    public byte[] getPreferredActivityBackup(int userId) {
13631        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13632            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
13633        }
13634
13635        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13636        try {
13637            final XmlSerializer serializer = new FastXmlSerializer();
13638            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13639            serializer.startDocument(null, true);
13640            serializer.startTag(null, TAG_PREFERRED_BACKUP);
13641
13642            synchronized (mPackages) {
13643                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
13644            }
13645
13646            serializer.endTag(null, TAG_PREFERRED_BACKUP);
13647            serializer.endDocument();
13648            serializer.flush();
13649        } catch (Exception e) {
13650            if (DEBUG_BACKUP) {
13651                Slog.e(TAG, "Unable to write preferred activities for backup", e);
13652            }
13653            return null;
13654        }
13655
13656        return dataStream.toByteArray();
13657    }
13658
13659    @Override
13660    public void restorePreferredActivities(byte[] backup, int userId) {
13661        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13662            throw new SecurityException("Only the system may call restorePreferredActivities()");
13663        }
13664
13665        try {
13666            final XmlPullParser parser = Xml.newPullParser();
13667            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13668            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
13669                    new BlobXmlRestorer() {
13670                        @Override
13671                        public void apply(XmlPullParser parser, int userId)
13672                                throws XmlPullParserException, IOException {
13673                            synchronized (mPackages) {
13674                                mSettings.readPreferredActivitiesLPw(parser, userId);
13675                            }
13676                        }
13677                    } );
13678        } catch (Exception e) {
13679            if (DEBUG_BACKUP) {
13680                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
13681            }
13682        }
13683    }
13684
13685    /**
13686     * Non-Binder method, support for the backup/restore mechanism: write the
13687     * default browser (etc) settings in its canonical XML format.  Returns the default
13688     * browser XML representation as a byte array, or null if there is none.
13689     */
13690    @Override
13691    public byte[] getDefaultAppsBackup(int userId) {
13692        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13693            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
13694        }
13695
13696        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13697        try {
13698            final XmlSerializer serializer = new FastXmlSerializer();
13699            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13700            serializer.startDocument(null, true);
13701            serializer.startTag(null, TAG_DEFAULT_APPS);
13702
13703            synchronized (mPackages) {
13704                mSettings.writeDefaultAppsLPr(serializer, userId);
13705            }
13706
13707            serializer.endTag(null, TAG_DEFAULT_APPS);
13708            serializer.endDocument();
13709            serializer.flush();
13710        } catch (Exception e) {
13711            if (DEBUG_BACKUP) {
13712                Slog.e(TAG, "Unable to write default apps for backup", e);
13713            }
13714            return null;
13715        }
13716
13717        return dataStream.toByteArray();
13718    }
13719
13720    @Override
13721    public void restoreDefaultApps(byte[] backup, int userId) {
13722        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13723            throw new SecurityException("Only the system may call restoreDefaultApps()");
13724        }
13725
13726        try {
13727            final XmlPullParser parser = Xml.newPullParser();
13728            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13729            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
13730                    new BlobXmlRestorer() {
13731                        @Override
13732                        public void apply(XmlPullParser parser, int userId)
13733                                throws XmlPullParserException, IOException {
13734                            synchronized (mPackages) {
13735                                mSettings.readDefaultAppsLPw(parser, userId);
13736                            }
13737                        }
13738                    } );
13739        } catch (Exception e) {
13740            if (DEBUG_BACKUP) {
13741                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
13742            }
13743        }
13744    }
13745
13746    @Override
13747    public byte[] getIntentFilterVerificationBackup(int userId) {
13748        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13749            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
13750        }
13751
13752        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13753        try {
13754            final XmlSerializer serializer = new FastXmlSerializer();
13755            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13756            serializer.startDocument(null, true);
13757            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
13758
13759            synchronized (mPackages) {
13760                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
13761            }
13762
13763            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
13764            serializer.endDocument();
13765            serializer.flush();
13766        } catch (Exception e) {
13767            if (DEBUG_BACKUP) {
13768                Slog.e(TAG, "Unable to write default apps for backup", e);
13769            }
13770            return null;
13771        }
13772
13773        return dataStream.toByteArray();
13774    }
13775
13776    @Override
13777    public void restoreIntentFilterVerification(byte[] backup, int userId) {
13778        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13779            throw new SecurityException("Only the system may call restorePreferredActivities()");
13780        }
13781
13782        try {
13783            final XmlPullParser parser = Xml.newPullParser();
13784            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13785            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
13786                    new BlobXmlRestorer() {
13787                        @Override
13788                        public void apply(XmlPullParser parser, int userId)
13789                                throws XmlPullParserException, IOException {
13790                            synchronized (mPackages) {
13791                                mSettings.readAllDomainVerificationsLPr(parser, userId);
13792                                mSettings.writeLPr();
13793                            }
13794                        }
13795                    } );
13796        } catch (Exception e) {
13797            if (DEBUG_BACKUP) {
13798                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
13799            }
13800        }
13801    }
13802
13803    @Override
13804    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
13805            int sourceUserId, int targetUserId, int flags) {
13806        mContext.enforceCallingOrSelfPermission(
13807                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
13808        int callingUid = Binder.getCallingUid();
13809        enforceOwnerRights(ownerPackage, callingUid);
13810        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
13811        if (intentFilter.countActions() == 0) {
13812            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
13813            return;
13814        }
13815        synchronized (mPackages) {
13816            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
13817                    ownerPackage, targetUserId, flags);
13818            CrossProfileIntentResolver resolver =
13819                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
13820            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
13821            // We have all those whose filter is equal. Now checking if the rest is equal as well.
13822            if (existing != null) {
13823                int size = existing.size();
13824                for (int i = 0; i < size; i++) {
13825                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
13826                        return;
13827                    }
13828                }
13829            }
13830            resolver.addFilter(newFilter);
13831            scheduleWritePackageRestrictionsLocked(sourceUserId);
13832        }
13833    }
13834
13835    @Override
13836    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
13837        mContext.enforceCallingOrSelfPermission(
13838                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
13839        int callingUid = Binder.getCallingUid();
13840        enforceOwnerRights(ownerPackage, callingUid);
13841        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
13842        synchronized (mPackages) {
13843            CrossProfileIntentResolver resolver =
13844                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
13845            ArraySet<CrossProfileIntentFilter> set =
13846                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
13847            for (CrossProfileIntentFilter filter : set) {
13848                if (filter.getOwnerPackage().equals(ownerPackage)) {
13849                    resolver.removeFilter(filter);
13850                }
13851            }
13852            scheduleWritePackageRestrictionsLocked(sourceUserId);
13853        }
13854    }
13855
13856    // Enforcing that callingUid is owning pkg on userId
13857    private void enforceOwnerRights(String pkg, int callingUid) {
13858        // The system owns everything.
13859        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
13860            return;
13861        }
13862        int callingUserId = UserHandle.getUserId(callingUid);
13863        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
13864        if (pi == null) {
13865            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
13866                    + callingUserId);
13867        }
13868        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
13869            throw new SecurityException("Calling uid " + callingUid
13870                    + " does not own package " + pkg);
13871        }
13872    }
13873
13874    @Override
13875    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
13876        Intent intent = new Intent(Intent.ACTION_MAIN);
13877        intent.addCategory(Intent.CATEGORY_HOME);
13878
13879        final int callingUserId = UserHandle.getCallingUserId();
13880        List<ResolveInfo> list = queryIntentActivities(intent, null,
13881                PackageManager.GET_META_DATA, callingUserId);
13882        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
13883                true, false, false, callingUserId);
13884
13885        allHomeCandidates.clear();
13886        if (list != null) {
13887            for (ResolveInfo ri : list) {
13888                allHomeCandidates.add(ri);
13889            }
13890        }
13891        return (preferred == null || preferred.activityInfo == null)
13892                ? null
13893                : new ComponentName(preferred.activityInfo.packageName,
13894                        preferred.activityInfo.name);
13895    }
13896
13897    @Override
13898    public void setApplicationEnabledSetting(String appPackageName,
13899            int newState, int flags, int userId, String callingPackage) {
13900        if (!sUserManager.exists(userId)) return;
13901        if (callingPackage == null) {
13902            callingPackage = Integer.toString(Binder.getCallingUid());
13903        }
13904        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
13905    }
13906
13907    @Override
13908    public void setComponentEnabledSetting(ComponentName componentName,
13909            int newState, int flags, int userId) {
13910        if (!sUserManager.exists(userId)) return;
13911        setEnabledSetting(componentName.getPackageName(),
13912                componentName.getClassName(), newState, flags, userId, null);
13913    }
13914
13915    private void setEnabledSetting(final String packageName, String className, int newState,
13916            final int flags, int userId, String callingPackage) {
13917        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
13918              || newState == COMPONENT_ENABLED_STATE_ENABLED
13919              || newState == COMPONENT_ENABLED_STATE_DISABLED
13920              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
13921              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
13922            throw new IllegalArgumentException("Invalid new component state: "
13923                    + newState);
13924        }
13925        PackageSetting pkgSetting;
13926        final int uid = Binder.getCallingUid();
13927        final int permission = mContext.checkCallingOrSelfPermission(
13928                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
13929        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
13930        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
13931        boolean sendNow = false;
13932        boolean isApp = (className == null);
13933        String componentName = isApp ? packageName : className;
13934        int packageUid = -1;
13935        ArrayList<String> components;
13936
13937        // writer
13938        synchronized (mPackages) {
13939            pkgSetting = mSettings.mPackages.get(packageName);
13940            if (pkgSetting == null) {
13941                if (className == null) {
13942                    throw new IllegalArgumentException(
13943                            "Unknown package: " + packageName);
13944                }
13945                throw new IllegalArgumentException(
13946                        "Unknown component: " + packageName
13947                        + "/" + className);
13948            }
13949            // Allow root and verify that userId is not being specified by a different user
13950            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
13951                throw new SecurityException(
13952                        "Permission Denial: attempt to change component state from pid="
13953                        + Binder.getCallingPid()
13954                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
13955            }
13956            if (className == null) {
13957                // We're dealing with an application/package level state change
13958                if (pkgSetting.getEnabled(userId) == newState) {
13959                    // Nothing to do
13960                    return;
13961                }
13962                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
13963                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
13964                    // Don't care about who enables an app.
13965                    callingPackage = null;
13966                }
13967                pkgSetting.setEnabled(newState, userId, callingPackage);
13968                // pkgSetting.pkg.mSetEnabled = newState;
13969            } else {
13970                // We're dealing with a component level state change
13971                // First, verify that this is a valid class name.
13972                PackageParser.Package pkg = pkgSetting.pkg;
13973                if (pkg == null || !pkg.hasComponentClassName(className)) {
13974                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
13975                        throw new IllegalArgumentException("Component class " + className
13976                                + " does not exist in " + packageName);
13977                    } else {
13978                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
13979                                + className + " does not exist in " + packageName);
13980                    }
13981                }
13982                switch (newState) {
13983                case COMPONENT_ENABLED_STATE_ENABLED:
13984                    if (!pkgSetting.enableComponentLPw(className, userId)) {
13985                        return;
13986                    }
13987                    break;
13988                case COMPONENT_ENABLED_STATE_DISABLED:
13989                    if (!pkgSetting.disableComponentLPw(className, userId)) {
13990                        return;
13991                    }
13992                    break;
13993                case COMPONENT_ENABLED_STATE_DEFAULT:
13994                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
13995                        return;
13996                    }
13997                    break;
13998                default:
13999                    Slog.e(TAG, "Invalid new component state: " + newState);
14000                    return;
14001                }
14002            }
14003            scheduleWritePackageRestrictionsLocked(userId);
14004            components = mPendingBroadcasts.get(userId, packageName);
14005            final boolean newPackage = components == null;
14006            if (newPackage) {
14007                components = new ArrayList<String>();
14008            }
14009            if (!components.contains(componentName)) {
14010                components.add(componentName);
14011            }
14012            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
14013                sendNow = true;
14014                // Purge entry from pending broadcast list if another one exists already
14015                // since we are sending one right away.
14016                mPendingBroadcasts.remove(userId, packageName);
14017            } else {
14018                if (newPackage) {
14019                    mPendingBroadcasts.put(userId, packageName, components);
14020                }
14021                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
14022                    // Schedule a message
14023                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
14024                }
14025            }
14026        }
14027
14028        long callingId = Binder.clearCallingIdentity();
14029        try {
14030            if (sendNow) {
14031                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
14032                sendPackageChangedBroadcast(packageName,
14033                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
14034            }
14035        } finally {
14036            Binder.restoreCallingIdentity(callingId);
14037        }
14038    }
14039
14040    private void sendPackageChangedBroadcast(String packageName,
14041            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
14042        if (DEBUG_INSTALL)
14043            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
14044                    + componentNames);
14045        Bundle extras = new Bundle(4);
14046        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
14047        String nameList[] = new String[componentNames.size()];
14048        componentNames.toArray(nameList);
14049        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
14050        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
14051        extras.putInt(Intent.EXTRA_UID, packageUid);
14052        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
14053                new int[] {UserHandle.getUserId(packageUid)});
14054    }
14055
14056    @Override
14057    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
14058        if (!sUserManager.exists(userId)) return;
14059        final int uid = Binder.getCallingUid();
14060        final int permission = mContext.checkCallingOrSelfPermission(
14061                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14062        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14063        enforceCrossUserPermission(uid, userId, true, true, "stop package");
14064        // writer
14065        synchronized (mPackages) {
14066            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
14067                    allowedByPermission, uid, userId)) {
14068                scheduleWritePackageRestrictionsLocked(userId);
14069            }
14070        }
14071    }
14072
14073    @Override
14074    public String getInstallerPackageName(String packageName) {
14075        // reader
14076        synchronized (mPackages) {
14077            return mSettings.getInstallerPackageNameLPr(packageName);
14078        }
14079    }
14080
14081    @Override
14082    public int getApplicationEnabledSetting(String packageName, int userId) {
14083        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14084        int uid = Binder.getCallingUid();
14085        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
14086        // reader
14087        synchronized (mPackages) {
14088            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
14089        }
14090    }
14091
14092    @Override
14093    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
14094        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14095        int uid = Binder.getCallingUid();
14096        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
14097        // reader
14098        synchronized (mPackages) {
14099            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
14100        }
14101    }
14102
14103    @Override
14104    public void enterSafeMode() {
14105        enforceSystemOrRoot("Only the system can request entering safe mode");
14106
14107        if (!mSystemReady) {
14108            mSafeMode = true;
14109        }
14110    }
14111
14112    @Override
14113    public void systemReady() {
14114        mSystemReady = true;
14115
14116        // Read the compatibilty setting when the system is ready.
14117        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
14118                mContext.getContentResolver(),
14119                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
14120        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
14121        if (DEBUG_SETTINGS) {
14122            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
14123        }
14124
14125        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
14126
14127        synchronized (mPackages) {
14128            // Verify that all of the preferred activity components actually
14129            // exist.  It is possible for applications to be updated and at
14130            // that point remove a previously declared activity component that
14131            // had been set as a preferred activity.  We try to clean this up
14132            // the next time we encounter that preferred activity, but it is
14133            // possible for the user flow to never be able to return to that
14134            // situation so here we do a sanity check to make sure we haven't
14135            // left any junk around.
14136            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
14137            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14138                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14139                removed.clear();
14140                for (PreferredActivity pa : pir.filterSet()) {
14141                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
14142                        removed.add(pa);
14143                    }
14144                }
14145                if (removed.size() > 0) {
14146                    for (int r=0; r<removed.size(); r++) {
14147                        PreferredActivity pa = removed.get(r);
14148                        Slog.w(TAG, "Removing dangling preferred activity: "
14149                                + pa.mPref.mComponent);
14150                        pir.removeFilter(pa);
14151                    }
14152                    mSettings.writePackageRestrictionsLPr(
14153                            mSettings.mPreferredActivities.keyAt(i));
14154                }
14155            }
14156
14157            for (int userId : UserManagerService.getInstance().getUserIds()) {
14158                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
14159                    grantPermissionsUserIds = ArrayUtils.appendInt(
14160                            grantPermissionsUserIds, userId);
14161                }
14162            }
14163        }
14164        sUserManager.systemReady();
14165
14166        // If we upgraded grant all default permissions before kicking off.
14167        for (int userId : grantPermissionsUserIds) {
14168            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
14169        }
14170
14171        // Kick off any messages waiting for system ready
14172        if (mPostSystemReadyMessages != null) {
14173            for (Message msg : mPostSystemReadyMessages) {
14174                msg.sendToTarget();
14175            }
14176            mPostSystemReadyMessages = null;
14177        }
14178
14179        // Watch for external volumes that come and go over time
14180        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14181        storage.registerListener(mStorageListener);
14182
14183        mInstallerService.systemReady();
14184        mPackageDexOptimizer.systemReady();
14185    }
14186
14187    @Override
14188    public boolean isSafeMode() {
14189        return mSafeMode;
14190    }
14191
14192    @Override
14193    public boolean hasSystemUidErrors() {
14194        return mHasSystemUidErrors;
14195    }
14196
14197    static String arrayToString(int[] array) {
14198        StringBuffer buf = new StringBuffer(128);
14199        buf.append('[');
14200        if (array != null) {
14201            for (int i=0; i<array.length; i++) {
14202                if (i > 0) buf.append(", ");
14203                buf.append(array[i]);
14204            }
14205        }
14206        buf.append(']');
14207        return buf.toString();
14208    }
14209
14210    static class DumpState {
14211        public static final int DUMP_LIBS = 1 << 0;
14212        public static final int DUMP_FEATURES = 1 << 1;
14213        public static final int DUMP_RESOLVERS = 1 << 2;
14214        public static final int DUMP_PERMISSIONS = 1 << 3;
14215        public static final int DUMP_PACKAGES = 1 << 4;
14216        public static final int DUMP_SHARED_USERS = 1 << 5;
14217        public static final int DUMP_MESSAGES = 1 << 6;
14218        public static final int DUMP_PROVIDERS = 1 << 7;
14219        public static final int DUMP_VERIFIERS = 1 << 8;
14220        public static final int DUMP_PREFERRED = 1 << 9;
14221        public static final int DUMP_PREFERRED_XML = 1 << 10;
14222        public static final int DUMP_KEYSETS = 1 << 11;
14223        public static final int DUMP_VERSION = 1 << 12;
14224        public static final int DUMP_INSTALLS = 1 << 13;
14225        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
14226        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
14227
14228        public static final int OPTION_SHOW_FILTERS = 1 << 0;
14229
14230        private int mTypes;
14231
14232        private int mOptions;
14233
14234        private boolean mTitlePrinted;
14235
14236        private SharedUserSetting mSharedUser;
14237
14238        public boolean isDumping(int type) {
14239            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
14240                return true;
14241            }
14242
14243            return (mTypes & type) != 0;
14244        }
14245
14246        public void setDump(int type) {
14247            mTypes |= type;
14248        }
14249
14250        public boolean isOptionEnabled(int option) {
14251            return (mOptions & option) != 0;
14252        }
14253
14254        public void setOptionEnabled(int option) {
14255            mOptions |= option;
14256        }
14257
14258        public boolean onTitlePrinted() {
14259            final boolean printed = mTitlePrinted;
14260            mTitlePrinted = true;
14261            return printed;
14262        }
14263
14264        public boolean getTitlePrinted() {
14265            return mTitlePrinted;
14266        }
14267
14268        public void setTitlePrinted(boolean enabled) {
14269            mTitlePrinted = enabled;
14270        }
14271
14272        public SharedUserSetting getSharedUser() {
14273            return mSharedUser;
14274        }
14275
14276        public void setSharedUser(SharedUserSetting user) {
14277            mSharedUser = user;
14278        }
14279    }
14280
14281    @Override
14282    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
14283        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
14284                != PackageManager.PERMISSION_GRANTED) {
14285            pw.println("Permission Denial: can't dump ActivityManager from from pid="
14286                    + Binder.getCallingPid()
14287                    + ", uid=" + Binder.getCallingUid()
14288                    + " without permission "
14289                    + android.Manifest.permission.DUMP);
14290            return;
14291        }
14292
14293        DumpState dumpState = new DumpState();
14294        boolean fullPreferred = false;
14295        boolean checkin = false;
14296
14297        String packageName = null;
14298        ArraySet<String> permissionNames = null;
14299
14300        int opti = 0;
14301        while (opti < args.length) {
14302            String opt = args[opti];
14303            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
14304                break;
14305            }
14306            opti++;
14307
14308            if ("-a".equals(opt)) {
14309                // Right now we only know how to print all.
14310            } else if ("-h".equals(opt)) {
14311                pw.println("Package manager dump options:");
14312                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
14313                pw.println("    --checkin: dump for a checkin");
14314                pw.println("    -f: print details of intent filters");
14315                pw.println("    -h: print this help");
14316                pw.println("  cmd may be one of:");
14317                pw.println("    l[ibraries]: list known shared libraries");
14318                pw.println("    f[ibraries]: list device features");
14319                pw.println("    k[eysets]: print known keysets");
14320                pw.println("    r[esolvers]: dump intent resolvers");
14321                pw.println("    perm[issions]: dump permissions");
14322                pw.println("    permission [name ...]: dump declaration and use of given permission");
14323                pw.println("    pref[erred]: print preferred package settings");
14324                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
14325                pw.println("    prov[iders]: dump content providers");
14326                pw.println("    p[ackages]: dump installed packages");
14327                pw.println("    s[hared-users]: dump shared user IDs");
14328                pw.println("    m[essages]: print collected runtime messages");
14329                pw.println("    v[erifiers]: print package verifier info");
14330                pw.println("    version: print database version info");
14331                pw.println("    write: write current settings now");
14332                pw.println("    <package.name>: info about given package");
14333                pw.println("    installs: details about install sessions");
14334                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
14335                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
14336                return;
14337            } else if ("--checkin".equals(opt)) {
14338                checkin = true;
14339            } else if ("-f".equals(opt)) {
14340                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14341            } else {
14342                pw.println("Unknown argument: " + opt + "; use -h for help");
14343            }
14344        }
14345
14346        // Is the caller requesting to dump a particular piece of data?
14347        if (opti < args.length) {
14348            String cmd = args[opti];
14349            opti++;
14350            // Is this a package name?
14351            if ("android".equals(cmd) || cmd.contains(".")) {
14352                packageName = cmd;
14353                // When dumping a single package, we always dump all of its
14354                // filter information since the amount of data will be reasonable.
14355                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14356            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
14357                dumpState.setDump(DumpState.DUMP_LIBS);
14358            } else if ("f".equals(cmd) || "features".equals(cmd)) {
14359                dumpState.setDump(DumpState.DUMP_FEATURES);
14360            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
14361                dumpState.setDump(DumpState.DUMP_RESOLVERS);
14362            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
14363                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
14364            } else if ("permission".equals(cmd)) {
14365                if (opti >= args.length) {
14366                    pw.println("Error: permission requires permission name");
14367                    return;
14368                }
14369                permissionNames = new ArraySet<>();
14370                while (opti < args.length) {
14371                    permissionNames.add(args[opti]);
14372                    opti++;
14373                }
14374                dumpState.setDump(DumpState.DUMP_PERMISSIONS
14375                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
14376            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
14377                dumpState.setDump(DumpState.DUMP_PREFERRED);
14378            } else if ("preferred-xml".equals(cmd)) {
14379                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
14380                if (opti < args.length && "--full".equals(args[opti])) {
14381                    fullPreferred = true;
14382                    opti++;
14383                }
14384            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
14385                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
14386            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
14387                dumpState.setDump(DumpState.DUMP_PACKAGES);
14388            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
14389                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
14390            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
14391                dumpState.setDump(DumpState.DUMP_PROVIDERS);
14392            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
14393                dumpState.setDump(DumpState.DUMP_MESSAGES);
14394            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
14395                dumpState.setDump(DumpState.DUMP_VERIFIERS);
14396            } else if ("i".equals(cmd) || "ifv".equals(cmd)
14397                    || "intent-filter-verifiers".equals(cmd)) {
14398                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
14399            } else if ("version".equals(cmd)) {
14400                dumpState.setDump(DumpState.DUMP_VERSION);
14401            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
14402                dumpState.setDump(DumpState.DUMP_KEYSETS);
14403            } else if ("installs".equals(cmd)) {
14404                dumpState.setDump(DumpState.DUMP_INSTALLS);
14405            } else if ("write".equals(cmd)) {
14406                synchronized (mPackages) {
14407                    mSettings.writeLPr();
14408                    pw.println("Settings written.");
14409                    return;
14410                }
14411            }
14412        }
14413
14414        if (checkin) {
14415            pw.println("vers,1");
14416        }
14417
14418        // reader
14419        synchronized (mPackages) {
14420            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
14421                if (!checkin) {
14422                    if (dumpState.onTitlePrinted())
14423                        pw.println();
14424                    pw.println("Database versions:");
14425                    pw.print("  SDK Version:");
14426                    pw.print(" internal=");
14427                    pw.print(mSettings.mInternalSdkPlatform);
14428                    pw.print(" external=");
14429                    pw.println(mSettings.mExternalSdkPlatform);
14430                    pw.print("  DB Version:");
14431                    pw.print(" internal=");
14432                    pw.print(mSettings.mInternalDatabaseVersion);
14433                    pw.print(" external=");
14434                    pw.println(mSettings.mExternalDatabaseVersion);
14435                }
14436            }
14437
14438            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
14439                if (!checkin) {
14440                    if (dumpState.onTitlePrinted())
14441                        pw.println();
14442                    pw.println("Verifiers:");
14443                    pw.print("  Required: ");
14444                    pw.print(mRequiredVerifierPackage);
14445                    pw.print(" (uid=");
14446                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
14447                    pw.println(")");
14448                } else if (mRequiredVerifierPackage != null) {
14449                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
14450                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
14451                }
14452            }
14453
14454            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
14455                    packageName == null) {
14456                if (mIntentFilterVerifierComponent != null) {
14457                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
14458                    if (!checkin) {
14459                        if (dumpState.onTitlePrinted())
14460                            pw.println();
14461                        pw.println("Intent Filter Verifier:");
14462                        pw.print("  Using: ");
14463                        pw.print(verifierPackageName);
14464                        pw.print(" (uid=");
14465                        pw.print(getPackageUid(verifierPackageName, 0));
14466                        pw.println(")");
14467                    } else if (verifierPackageName != null) {
14468                        pw.print("ifv,"); pw.print(verifierPackageName);
14469                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
14470                    }
14471                } else {
14472                    pw.println();
14473                    pw.println("No Intent Filter Verifier available!");
14474                }
14475            }
14476
14477            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
14478                boolean printedHeader = false;
14479                final Iterator<String> it = mSharedLibraries.keySet().iterator();
14480                while (it.hasNext()) {
14481                    String name = it.next();
14482                    SharedLibraryEntry ent = mSharedLibraries.get(name);
14483                    if (!checkin) {
14484                        if (!printedHeader) {
14485                            if (dumpState.onTitlePrinted())
14486                                pw.println();
14487                            pw.println("Libraries:");
14488                            printedHeader = true;
14489                        }
14490                        pw.print("  ");
14491                    } else {
14492                        pw.print("lib,");
14493                    }
14494                    pw.print(name);
14495                    if (!checkin) {
14496                        pw.print(" -> ");
14497                    }
14498                    if (ent.path != null) {
14499                        if (!checkin) {
14500                            pw.print("(jar) ");
14501                            pw.print(ent.path);
14502                        } else {
14503                            pw.print(",jar,");
14504                            pw.print(ent.path);
14505                        }
14506                    } else {
14507                        if (!checkin) {
14508                            pw.print("(apk) ");
14509                            pw.print(ent.apk);
14510                        } else {
14511                            pw.print(",apk,");
14512                            pw.print(ent.apk);
14513                        }
14514                    }
14515                    pw.println();
14516                }
14517            }
14518
14519            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
14520                if (dumpState.onTitlePrinted())
14521                    pw.println();
14522                if (!checkin) {
14523                    pw.println("Features:");
14524                }
14525                Iterator<String> it = mAvailableFeatures.keySet().iterator();
14526                while (it.hasNext()) {
14527                    String name = it.next();
14528                    if (!checkin) {
14529                        pw.print("  ");
14530                    } else {
14531                        pw.print("feat,");
14532                    }
14533                    pw.println(name);
14534                }
14535            }
14536
14537            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
14538                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
14539                        : "Activity Resolver Table:", "  ", packageName,
14540                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14541                    dumpState.setTitlePrinted(true);
14542                }
14543                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
14544                        : "Receiver Resolver Table:", "  ", packageName,
14545                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14546                    dumpState.setTitlePrinted(true);
14547                }
14548                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
14549                        : "Service Resolver Table:", "  ", packageName,
14550                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14551                    dumpState.setTitlePrinted(true);
14552                }
14553                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
14554                        : "Provider Resolver Table:", "  ", packageName,
14555                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14556                    dumpState.setTitlePrinted(true);
14557                }
14558            }
14559
14560            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
14561                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14562                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14563                    int user = mSettings.mPreferredActivities.keyAt(i);
14564                    if (pir.dump(pw,
14565                            dumpState.getTitlePrinted()
14566                                ? "\nPreferred Activities User " + user + ":"
14567                                : "Preferred Activities User " + user + ":", "  ",
14568                            packageName, true, false)) {
14569                        dumpState.setTitlePrinted(true);
14570                    }
14571                }
14572            }
14573
14574            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
14575                pw.flush();
14576                FileOutputStream fout = new FileOutputStream(fd);
14577                BufferedOutputStream str = new BufferedOutputStream(fout);
14578                XmlSerializer serializer = new FastXmlSerializer();
14579                try {
14580                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
14581                    serializer.startDocument(null, true);
14582                    serializer.setFeature(
14583                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
14584                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
14585                    serializer.endDocument();
14586                    serializer.flush();
14587                } catch (IllegalArgumentException e) {
14588                    pw.println("Failed writing: " + e);
14589                } catch (IllegalStateException e) {
14590                    pw.println("Failed writing: " + e);
14591                } catch (IOException e) {
14592                    pw.println("Failed writing: " + e);
14593                }
14594            }
14595
14596            if (!checkin
14597                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
14598                    && packageName == null) {
14599                pw.println();
14600                int count = mSettings.mPackages.size();
14601                if (count == 0) {
14602                    pw.println("No domain preferred apps!");
14603                    pw.println();
14604                } else {
14605                    final String prefix = "  ";
14606                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
14607                    if (allPackageSettings.size() == 0) {
14608                        pw.println("No domain preferred apps!");
14609                        pw.println();
14610                    } else {
14611                        pw.println("Domain preferred apps status:");
14612                        pw.println();
14613                        count = 0;
14614                        for (PackageSetting ps : allPackageSettings) {
14615                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
14616                            if (ivi == null || ivi.getPackageName() == null) continue;
14617                            pw.println(prefix + "Package Name: " + ivi.getPackageName());
14618                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
14619                            pw.println(prefix + "Status: " + ivi.getStatusString());
14620                            pw.println();
14621                            count++;
14622                        }
14623                        if (count == 0) {
14624                            pw.println(prefix + "No domain preferred app status!");
14625                            pw.println();
14626                        }
14627                        for (int userId : sUserManager.getUserIds()) {
14628                            pw.println("Domain preferred apps for User " + userId + ":");
14629                            pw.println();
14630                            count = 0;
14631                            for (PackageSetting ps : allPackageSettings) {
14632                                IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
14633                                if (ivi == null || ivi.getPackageName() == null) {
14634                                    continue;
14635                                }
14636                                final int status = ps.getDomainVerificationStatusForUser(userId);
14637                                if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
14638                                    continue;
14639                                }
14640                                pw.println(prefix + "Package Name: " + ivi.getPackageName());
14641                                pw.println(prefix + "Domains: " + ivi.getDomainsString());
14642                                String statusStr = IntentFilterVerificationInfo.
14643                                        getStatusStringFromValue(status);
14644                                pw.println(prefix + "Status: " + statusStr);
14645                                pw.println();
14646                                count++;
14647                            }
14648                            if (count == 0) {
14649                                pw.println(prefix + "No domain preferred apps!");
14650                                pw.println();
14651                            }
14652                        }
14653                    }
14654                }
14655            }
14656
14657            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
14658                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
14659                if (packageName == null && permissionNames == null) {
14660                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
14661                        if (iperm == 0) {
14662                            if (dumpState.onTitlePrinted())
14663                                pw.println();
14664                            pw.println("AppOp Permissions:");
14665                        }
14666                        pw.print("  AppOp Permission ");
14667                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
14668                        pw.println(":");
14669                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
14670                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
14671                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
14672                        }
14673                    }
14674                }
14675            }
14676
14677            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
14678                boolean printedSomething = false;
14679                for (PackageParser.Provider p : mProviders.mProviders.values()) {
14680                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14681                        continue;
14682                    }
14683                    if (!printedSomething) {
14684                        if (dumpState.onTitlePrinted())
14685                            pw.println();
14686                        pw.println("Registered ContentProviders:");
14687                        printedSomething = true;
14688                    }
14689                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
14690                    pw.print("    "); pw.println(p.toString());
14691                }
14692                printedSomething = false;
14693                for (Map.Entry<String, PackageParser.Provider> entry :
14694                        mProvidersByAuthority.entrySet()) {
14695                    PackageParser.Provider p = entry.getValue();
14696                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14697                        continue;
14698                    }
14699                    if (!printedSomething) {
14700                        if (dumpState.onTitlePrinted())
14701                            pw.println();
14702                        pw.println("ContentProvider Authorities:");
14703                        printedSomething = true;
14704                    }
14705                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
14706                    pw.print("    "); pw.println(p.toString());
14707                    if (p.info != null && p.info.applicationInfo != null) {
14708                        final String appInfo = p.info.applicationInfo.toString();
14709                        pw.print("      applicationInfo="); pw.println(appInfo);
14710                    }
14711                }
14712            }
14713
14714            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
14715                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
14716            }
14717
14718            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
14719                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
14720            }
14721
14722            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
14723                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
14724            }
14725
14726            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
14727                // XXX should handle packageName != null by dumping only install data that
14728                // the given package is involved with.
14729                if (dumpState.onTitlePrinted()) pw.println();
14730                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
14731            }
14732
14733            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
14734                if (dumpState.onTitlePrinted()) pw.println();
14735                mSettings.dumpReadMessagesLPr(pw, dumpState);
14736
14737                pw.println();
14738                pw.println("Package warning messages:");
14739                BufferedReader in = null;
14740                String line = null;
14741                try {
14742                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
14743                    while ((line = in.readLine()) != null) {
14744                        if (line.contains("ignored: updated version")) continue;
14745                        pw.println(line);
14746                    }
14747                } catch (IOException ignored) {
14748                } finally {
14749                    IoUtils.closeQuietly(in);
14750                }
14751            }
14752
14753            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
14754                BufferedReader in = null;
14755                String line = null;
14756                try {
14757                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
14758                    while ((line = in.readLine()) != null) {
14759                        if (line.contains("ignored: updated version")) continue;
14760                        pw.print("msg,");
14761                        pw.println(line);
14762                    }
14763                } catch (IOException ignored) {
14764                } finally {
14765                    IoUtils.closeQuietly(in);
14766                }
14767            }
14768        }
14769    }
14770
14771    // ------- apps on sdcard specific code -------
14772    static final boolean DEBUG_SD_INSTALL = false;
14773
14774    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
14775
14776    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
14777
14778    private boolean mMediaMounted = false;
14779
14780    static String getEncryptKey() {
14781        try {
14782            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
14783                    SD_ENCRYPTION_KEYSTORE_NAME);
14784            if (sdEncKey == null) {
14785                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
14786                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
14787                if (sdEncKey == null) {
14788                    Slog.e(TAG, "Failed to create encryption keys");
14789                    return null;
14790                }
14791            }
14792            return sdEncKey;
14793        } catch (NoSuchAlgorithmException nsae) {
14794            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
14795            return null;
14796        } catch (IOException ioe) {
14797            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
14798            return null;
14799        }
14800    }
14801
14802    /*
14803     * Update media status on PackageManager.
14804     */
14805    @Override
14806    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
14807        int callingUid = Binder.getCallingUid();
14808        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
14809            throw new SecurityException("Media status can only be updated by the system");
14810        }
14811        // reader; this apparently protects mMediaMounted, but should probably
14812        // be a different lock in that case.
14813        synchronized (mPackages) {
14814            Log.i(TAG, "Updating external media status from "
14815                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
14816                    + (mediaStatus ? "mounted" : "unmounted"));
14817            if (DEBUG_SD_INSTALL)
14818                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
14819                        + ", mMediaMounted=" + mMediaMounted);
14820            if (mediaStatus == mMediaMounted) {
14821                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
14822                        : 0, -1);
14823                mHandler.sendMessage(msg);
14824                return;
14825            }
14826            mMediaMounted = mediaStatus;
14827        }
14828        // Queue up an async operation since the package installation may take a
14829        // little while.
14830        mHandler.post(new Runnable() {
14831            public void run() {
14832                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
14833            }
14834        });
14835    }
14836
14837    /**
14838     * Called by MountService when the initial ASECs to scan are available.
14839     * Should block until all the ASEC containers are finished being scanned.
14840     */
14841    public void scanAvailableAsecs() {
14842        updateExternalMediaStatusInner(true, false, false);
14843        if (mShouldRestoreconData) {
14844            SELinuxMMAC.setRestoreconDone();
14845            mShouldRestoreconData = false;
14846        }
14847    }
14848
14849    /*
14850     * Collect information of applications on external media, map them against
14851     * existing containers and update information based on current mount status.
14852     * Please note that we always have to report status if reportStatus has been
14853     * set to true especially when unloading packages.
14854     */
14855    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
14856            boolean externalStorage) {
14857        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
14858        int[] uidArr = EmptyArray.INT;
14859
14860        final String[] list = PackageHelper.getSecureContainerList();
14861        if (ArrayUtils.isEmpty(list)) {
14862            Log.i(TAG, "No secure containers found");
14863        } else {
14864            // Process list of secure containers and categorize them
14865            // as active or stale based on their package internal state.
14866
14867            // reader
14868            synchronized (mPackages) {
14869                for (String cid : list) {
14870                    // Leave stages untouched for now; installer service owns them
14871                    if (PackageInstallerService.isStageName(cid)) continue;
14872
14873                    if (DEBUG_SD_INSTALL)
14874                        Log.i(TAG, "Processing container " + cid);
14875                    String pkgName = getAsecPackageName(cid);
14876                    if (pkgName == null) {
14877                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
14878                        continue;
14879                    }
14880                    if (DEBUG_SD_INSTALL)
14881                        Log.i(TAG, "Looking for pkg : " + pkgName);
14882
14883                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
14884                    if (ps == null) {
14885                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
14886                        continue;
14887                    }
14888
14889                    /*
14890                     * Skip packages that are not external if we're unmounting
14891                     * external storage.
14892                     */
14893                    if (externalStorage && !isMounted && !isExternal(ps)) {
14894                        continue;
14895                    }
14896
14897                    final AsecInstallArgs args = new AsecInstallArgs(cid,
14898                            getAppDexInstructionSets(ps), ps.isForwardLocked());
14899                    // The package status is changed only if the code path
14900                    // matches between settings and the container id.
14901                    if (ps.codePathString != null
14902                            && ps.codePathString.startsWith(args.getCodePath())) {
14903                        if (DEBUG_SD_INSTALL) {
14904                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
14905                                    + " at code path: " + ps.codePathString);
14906                        }
14907
14908                        // We do have a valid package installed on sdcard
14909                        processCids.put(args, ps.codePathString);
14910                        final int uid = ps.appId;
14911                        if (uid != -1) {
14912                            uidArr = ArrayUtils.appendInt(uidArr, uid);
14913                        }
14914                    } else {
14915                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
14916                                + ps.codePathString);
14917                    }
14918                }
14919            }
14920
14921            Arrays.sort(uidArr);
14922        }
14923
14924        // Process packages with valid entries.
14925        if (isMounted) {
14926            if (DEBUG_SD_INSTALL)
14927                Log.i(TAG, "Loading packages");
14928            loadMediaPackages(processCids, uidArr);
14929            startCleaningPackages();
14930            mInstallerService.onSecureContainersAvailable();
14931        } else {
14932            if (DEBUG_SD_INSTALL)
14933                Log.i(TAG, "Unloading packages");
14934            unloadMediaPackages(processCids, uidArr, reportStatus);
14935        }
14936    }
14937
14938    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14939            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
14940        final int size = infos.size();
14941        final String[] packageNames = new String[size];
14942        final int[] packageUids = new int[size];
14943        for (int i = 0; i < size; i++) {
14944            final ApplicationInfo info = infos.get(i);
14945            packageNames[i] = info.packageName;
14946            packageUids[i] = info.uid;
14947        }
14948        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
14949                finishedReceiver);
14950    }
14951
14952    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14953            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
14954        sendResourcesChangedBroadcast(mediaStatus, replacing,
14955                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
14956    }
14957
14958    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14959            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
14960        int size = pkgList.length;
14961        if (size > 0) {
14962            // Send broadcasts here
14963            Bundle extras = new Bundle();
14964            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14965            if (uidArr != null) {
14966                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
14967            }
14968            if (replacing) {
14969                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
14970            }
14971            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
14972                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
14973            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
14974        }
14975    }
14976
14977   /*
14978     * Look at potentially valid container ids from processCids If package
14979     * information doesn't match the one on record or package scanning fails,
14980     * the cid is added to list of removeCids. We currently don't delete stale
14981     * containers.
14982     */
14983    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
14984        ArrayList<String> pkgList = new ArrayList<String>();
14985        Set<AsecInstallArgs> keys = processCids.keySet();
14986
14987        for (AsecInstallArgs args : keys) {
14988            String codePath = processCids.get(args);
14989            if (DEBUG_SD_INSTALL)
14990                Log.i(TAG, "Loading container : " + args.cid);
14991            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14992            try {
14993                // Make sure there are no container errors first.
14994                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
14995                    Slog.e(TAG, "Failed to mount cid : " + args.cid
14996                            + " when installing from sdcard");
14997                    continue;
14998                }
14999                // Check code path here.
15000                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
15001                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
15002                            + " does not match one in settings " + codePath);
15003                    continue;
15004                }
15005                // Parse package
15006                int parseFlags = mDefParseFlags;
15007                if (args.isExternalAsec()) {
15008                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
15009                }
15010                if (args.isFwdLocked()) {
15011                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
15012                }
15013
15014                synchronized (mInstallLock) {
15015                    PackageParser.Package pkg = null;
15016                    try {
15017                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
15018                    } catch (PackageManagerException e) {
15019                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
15020                    }
15021                    // Scan the package
15022                    if (pkg != null) {
15023                        /*
15024                         * TODO why is the lock being held? doPostInstall is
15025                         * called in other places without the lock. This needs
15026                         * to be straightened out.
15027                         */
15028                        // writer
15029                        synchronized (mPackages) {
15030                            retCode = PackageManager.INSTALL_SUCCEEDED;
15031                            pkgList.add(pkg.packageName);
15032                            // Post process args
15033                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
15034                                    pkg.applicationInfo.uid);
15035                        }
15036                    } else {
15037                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
15038                    }
15039                }
15040
15041            } finally {
15042                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
15043                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
15044                }
15045            }
15046        }
15047        // writer
15048        synchronized (mPackages) {
15049            // If the platform SDK has changed since the last time we booted,
15050            // we need to re-grant app permission to catch any new ones that
15051            // appear. This is really a hack, and means that apps can in some
15052            // cases get permissions that the user didn't initially explicitly
15053            // allow... it would be nice to have some better way to handle
15054            // this situation.
15055            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
15056            if (regrantPermissions)
15057                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
15058                        + mSdkVersion + "; regranting permissions for external storage");
15059            mSettings.mExternalSdkPlatform = mSdkVersion;
15060
15061            // Make sure group IDs have been assigned, and any permission
15062            // changes in other apps are accounted for
15063            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
15064                    | (regrantPermissions
15065                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
15066                            : 0));
15067
15068            mSettings.updateExternalDatabaseVersion();
15069
15070            // can downgrade to reader
15071            // Persist settings
15072            mSettings.writeLPr();
15073        }
15074        // Send a broadcast to let everyone know we are done processing
15075        if (pkgList.size() > 0) {
15076            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
15077        }
15078    }
15079
15080   /*
15081     * Utility method to unload a list of specified containers
15082     */
15083    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
15084        // Just unmount all valid containers.
15085        for (AsecInstallArgs arg : cidArgs) {
15086            synchronized (mInstallLock) {
15087                arg.doPostDeleteLI(false);
15088           }
15089       }
15090   }
15091
15092    /*
15093     * Unload packages mounted on external media. This involves deleting package
15094     * data from internal structures, sending broadcasts about diabled packages,
15095     * gc'ing to free up references, unmounting all secure containers
15096     * corresponding to packages on external media, and posting a
15097     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
15098     * that we always have to post this message if status has been requested no
15099     * matter what.
15100     */
15101    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
15102            final boolean reportStatus) {
15103        if (DEBUG_SD_INSTALL)
15104            Log.i(TAG, "unloading media packages");
15105        ArrayList<String> pkgList = new ArrayList<String>();
15106        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
15107        final Set<AsecInstallArgs> keys = processCids.keySet();
15108        for (AsecInstallArgs args : keys) {
15109            String pkgName = args.getPackageName();
15110            if (DEBUG_SD_INSTALL)
15111                Log.i(TAG, "Trying to unload pkg : " + pkgName);
15112            // Delete package internally
15113            PackageRemovedInfo outInfo = new PackageRemovedInfo();
15114            synchronized (mInstallLock) {
15115                boolean res = deletePackageLI(pkgName, null, false, null, null,
15116                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
15117                if (res) {
15118                    pkgList.add(pkgName);
15119                } else {
15120                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
15121                    failedList.add(args);
15122                }
15123            }
15124        }
15125
15126        // reader
15127        synchronized (mPackages) {
15128            // We didn't update the settings after removing each package;
15129            // write them now for all packages.
15130            mSettings.writeLPr();
15131        }
15132
15133        // We have to absolutely send UPDATED_MEDIA_STATUS only
15134        // after confirming that all the receivers processed the ordered
15135        // broadcast when packages get disabled, force a gc to clean things up.
15136        // and unload all the containers.
15137        if (pkgList.size() > 0) {
15138            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
15139                    new IIntentReceiver.Stub() {
15140                public void performReceive(Intent intent, int resultCode, String data,
15141                        Bundle extras, boolean ordered, boolean sticky,
15142                        int sendingUser) throws RemoteException {
15143                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
15144                            reportStatus ? 1 : 0, 1, keys);
15145                    mHandler.sendMessage(msg);
15146                }
15147            });
15148        } else {
15149            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
15150                    keys);
15151            mHandler.sendMessage(msg);
15152        }
15153    }
15154
15155    private void loadPrivatePackages(VolumeInfo vol) {
15156        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
15157        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
15158        synchronized (mInstallLock) {
15159        synchronized (mPackages) {
15160            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15161            for (PackageSetting ps : packages) {
15162                final PackageParser.Package pkg;
15163                try {
15164                    pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null);
15165                    loaded.add(pkg.applicationInfo);
15166                } catch (PackageManagerException e) {
15167                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
15168                }
15169            }
15170
15171            // TODO: regrant any permissions that changed based since original install
15172
15173            mSettings.writeLPr();
15174        }
15175        }
15176
15177        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
15178        sendResourcesChangedBroadcast(true, false, loaded, null);
15179    }
15180
15181    private void unloadPrivatePackages(VolumeInfo vol) {
15182        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
15183        synchronized (mInstallLock) {
15184        synchronized (mPackages) {
15185            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15186            for (PackageSetting ps : packages) {
15187                if (ps.pkg == null) continue;
15188
15189                final ApplicationInfo info = ps.pkg.applicationInfo;
15190                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
15191                if (deletePackageLI(ps.name, null, false, null, null,
15192                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
15193                    unloaded.add(info);
15194                } else {
15195                    Slog.w(TAG, "Failed to unload " + ps.codePath);
15196                }
15197            }
15198
15199            mSettings.writeLPr();
15200        }
15201        }
15202
15203        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
15204        sendResourcesChangedBroadcast(false, false, unloaded, null);
15205    }
15206
15207    private void unfreezePackage(String packageName) {
15208        synchronized (mPackages) {
15209            final PackageSetting ps = mSettings.mPackages.get(packageName);
15210            if (ps != null) {
15211                ps.frozen = false;
15212            }
15213        }
15214    }
15215
15216    @Override
15217    public int movePackage(final String packageName, final String volumeUuid) {
15218        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15219
15220        final int moveId = mNextMoveId.getAndIncrement();
15221        try {
15222            movePackageInternal(packageName, volumeUuid, moveId);
15223        } catch (PackageManagerException e) {
15224            Slog.w(TAG, "Failed to move " + packageName, e);
15225            mMoveCallbacks.notifyStatusChanged(moveId,
15226                    PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15227        }
15228        return moveId;
15229    }
15230
15231    private void movePackageInternal(final String packageName, final String volumeUuid,
15232            final int moveId) throws PackageManagerException {
15233        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
15234        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15235        final PackageManager pm = mContext.getPackageManager();
15236
15237        final boolean currentAsec;
15238        final String currentVolumeUuid;
15239        final File codeFile;
15240        final String installerPackageName;
15241        final String packageAbiOverride;
15242        final int appId;
15243        final String seinfo;
15244        final String label;
15245
15246        // reader
15247        synchronized (mPackages) {
15248            final PackageParser.Package pkg = mPackages.get(packageName);
15249            final PackageSetting ps = mSettings.mPackages.get(packageName);
15250            if (pkg == null || ps == null) {
15251                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
15252            }
15253
15254            if (pkg.applicationInfo.isSystemApp()) {
15255                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
15256                        "Cannot move system application");
15257            }
15258
15259            if (Objects.equals(ps.volumeUuid, volumeUuid)) {
15260                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15261                        "Package already moved to " + volumeUuid);
15262            }
15263
15264            final File probe = new File(pkg.codePath);
15265            final File probeOat = new File(probe, "oat");
15266            if (!probe.isDirectory() || !probeOat.isDirectory()) {
15267                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15268                        "Move only supported for modern cluster style installs");
15269            }
15270
15271            if (ps.frozen) {
15272                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
15273                        "Failed to move already frozen package");
15274            }
15275            ps.frozen = true;
15276
15277            currentAsec = pkg.applicationInfo.isForwardLocked()
15278                    || pkg.applicationInfo.isExternalAsec();
15279            currentVolumeUuid = ps.volumeUuid;
15280            codeFile = new File(pkg.codePath);
15281            installerPackageName = ps.installerPackageName;
15282            packageAbiOverride = ps.cpuAbiOverrideString;
15283            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
15284            seinfo = pkg.applicationInfo.seinfo;
15285            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
15286        }
15287
15288        // Now that we're guarded by frozen state, kill app during move
15289        killApplication(packageName, appId, "move pkg");
15290
15291        final Bundle extras = new Bundle();
15292        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
15293        extras.putString(Intent.EXTRA_TITLE, label);
15294        mMoveCallbacks.notifyCreated(moveId, extras);
15295
15296        int installFlags;
15297        final boolean moveCompleteApp;
15298        final File measurePath;
15299
15300        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
15301            installFlags = INSTALL_INTERNAL;
15302            moveCompleteApp = !currentAsec;
15303            measurePath = Environment.getDataAppDirectory(volumeUuid);
15304        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
15305            installFlags = INSTALL_EXTERNAL;
15306            moveCompleteApp = false;
15307            measurePath = storage.getPrimaryPhysicalVolume().getPath();
15308        } else {
15309            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
15310            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
15311                    || !volume.isMountedWritable()) {
15312                unfreezePackage(packageName);
15313                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15314                        "Move location not mounted private volume");
15315            }
15316
15317            Preconditions.checkState(!currentAsec);
15318
15319            installFlags = INSTALL_INTERNAL;
15320            moveCompleteApp = true;
15321            measurePath = Environment.getDataAppDirectory(volumeUuid);
15322        }
15323
15324        final PackageStats stats = new PackageStats(null, -1);
15325        synchronized (mInstaller) {
15326            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
15327                unfreezePackage(packageName);
15328                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15329                        "Failed to measure package size");
15330            }
15331        }
15332
15333        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
15334                + stats.dataSize);
15335
15336        final long startFreeBytes = measurePath.getFreeSpace();
15337        final long sizeBytes;
15338        if (moveCompleteApp) {
15339            sizeBytes = stats.codeSize + stats.dataSize;
15340        } else {
15341            sizeBytes = stats.codeSize;
15342        }
15343
15344        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
15345            unfreezePackage(packageName);
15346            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15347                    "Not enough free space to move");
15348        }
15349
15350        mMoveCallbacks.notifyStatusChanged(moveId, 10);
15351
15352        final CountDownLatch installedLatch = new CountDownLatch(1);
15353        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
15354            @Override
15355            public void onUserActionRequired(Intent intent) throws RemoteException {
15356                throw new IllegalStateException();
15357            }
15358
15359            @Override
15360            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
15361                    Bundle extras) throws RemoteException {
15362                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
15363                        + PackageManager.installStatusToString(returnCode, msg));
15364
15365                installedLatch.countDown();
15366
15367                // Regardless of success or failure of the move operation,
15368                // always unfreeze the package
15369                unfreezePackage(packageName);
15370
15371                final int status = PackageManager.installStatusToPublicStatus(returnCode);
15372                switch (status) {
15373                    case PackageInstaller.STATUS_SUCCESS:
15374                        mMoveCallbacks.notifyStatusChanged(moveId,
15375                                PackageManager.MOVE_SUCCEEDED);
15376                        break;
15377                    case PackageInstaller.STATUS_FAILURE_STORAGE:
15378                        mMoveCallbacks.notifyStatusChanged(moveId,
15379                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
15380                        break;
15381                    default:
15382                        mMoveCallbacks.notifyStatusChanged(moveId,
15383                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15384                        break;
15385                }
15386            }
15387        };
15388
15389        final MoveInfo move;
15390        if (moveCompleteApp) {
15391            // Kick off a thread to report progress estimates
15392            new Thread() {
15393                @Override
15394                public void run() {
15395                    while (true) {
15396                        try {
15397                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
15398                                break;
15399                            }
15400                        } catch (InterruptedException ignored) {
15401                        }
15402
15403                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
15404                        final int progress = 10 + (int) MathUtils.constrain(
15405                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
15406                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
15407                    }
15408                }
15409            }.start();
15410
15411            final String dataAppName = codeFile.getName();
15412            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
15413                    dataAppName, appId, seinfo);
15414        } else {
15415            move = null;
15416        }
15417
15418        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
15419
15420        final Message msg = mHandler.obtainMessage(INIT_COPY);
15421        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
15422        msg.obj = new InstallParams(origin, move, installObserver, installFlags,
15423                installerPackageName, volumeUuid, null, user, packageAbiOverride);
15424        mHandler.sendMessage(msg);
15425    }
15426
15427    @Override
15428    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
15429        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15430
15431        final int realMoveId = mNextMoveId.getAndIncrement();
15432        final Bundle extras = new Bundle();
15433        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
15434        mMoveCallbacks.notifyCreated(realMoveId, extras);
15435
15436        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
15437            @Override
15438            public void onCreated(int moveId, Bundle extras) {
15439                // Ignored
15440            }
15441
15442            @Override
15443            public void onStatusChanged(int moveId, int status, long estMillis) {
15444                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
15445            }
15446        };
15447
15448        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15449        storage.setPrimaryStorageUuid(volumeUuid, callback);
15450        return realMoveId;
15451    }
15452
15453    @Override
15454    public int getMoveStatus(int moveId) {
15455        mContext.enforceCallingOrSelfPermission(
15456                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15457        return mMoveCallbacks.mLastStatus.get(moveId);
15458    }
15459
15460    @Override
15461    public void registerMoveCallback(IPackageMoveObserver callback) {
15462        mContext.enforceCallingOrSelfPermission(
15463                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15464        mMoveCallbacks.register(callback);
15465    }
15466
15467    @Override
15468    public void unregisterMoveCallback(IPackageMoveObserver callback) {
15469        mContext.enforceCallingOrSelfPermission(
15470                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15471        mMoveCallbacks.unregister(callback);
15472    }
15473
15474    @Override
15475    public boolean setInstallLocation(int loc) {
15476        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
15477                null);
15478        if (getInstallLocation() == loc) {
15479            return true;
15480        }
15481        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
15482                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
15483            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
15484                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
15485            return true;
15486        }
15487        return false;
15488   }
15489
15490    @Override
15491    public int getInstallLocation() {
15492        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15493                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
15494                PackageHelper.APP_INSTALL_AUTO);
15495    }
15496
15497    /** Called by UserManagerService */
15498    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
15499        mDirtyUsers.remove(userHandle);
15500        mSettings.removeUserLPw(userHandle);
15501        mPendingBroadcasts.remove(userHandle);
15502        if (mInstaller != null) {
15503            // Technically, we shouldn't be doing this with the package lock
15504            // held.  However, this is very rare, and there is already so much
15505            // other disk I/O going on, that we'll let it slide for now.
15506            final StorageManager storage = StorageManager.from(mContext);
15507            final List<VolumeInfo> vols = storage.getVolumes();
15508            for (VolumeInfo vol : vols) {
15509                if (vol.getType() == VolumeInfo.TYPE_PRIVATE && vol.isMountedWritable()) {
15510                    final String volumeUuid = vol.getFsUuid();
15511                    if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
15512                    mInstaller.removeUserDataDirs(volumeUuid, userHandle);
15513                }
15514            }
15515        }
15516        mUserNeedsBadging.delete(userHandle);
15517        removeUnusedPackagesLILPw(userManager, userHandle);
15518    }
15519
15520    /**
15521     * We're removing userHandle and would like to remove any downloaded packages
15522     * that are no longer in use by any other user.
15523     * @param userHandle the user being removed
15524     */
15525    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
15526        final boolean DEBUG_CLEAN_APKS = false;
15527        int [] users = userManager.getUserIdsLPr();
15528        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
15529        while (psit.hasNext()) {
15530            PackageSetting ps = psit.next();
15531            if (ps.pkg == null) {
15532                continue;
15533            }
15534            final String packageName = ps.pkg.packageName;
15535            // Skip over if system app
15536            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15537                continue;
15538            }
15539            if (DEBUG_CLEAN_APKS) {
15540                Slog.i(TAG, "Checking package " + packageName);
15541            }
15542            boolean keep = false;
15543            for (int i = 0; i < users.length; i++) {
15544                if (users[i] != userHandle && ps.getInstalled(users[i])) {
15545                    keep = true;
15546                    if (DEBUG_CLEAN_APKS) {
15547                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
15548                                + users[i]);
15549                    }
15550                    break;
15551                }
15552            }
15553            if (!keep) {
15554                if (DEBUG_CLEAN_APKS) {
15555                    Slog.i(TAG, "  Removing package " + packageName);
15556                }
15557                mHandler.post(new Runnable() {
15558                    public void run() {
15559                        deletePackageX(packageName, userHandle, 0);
15560                    } //end run
15561                });
15562            }
15563        }
15564    }
15565
15566    /** Called by UserManagerService */
15567    void createNewUserLILPw(int userHandle, File path) {
15568        if (mInstaller != null) {
15569            mInstaller.createUserConfig(userHandle);
15570            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
15571            applyFactoryDefaultBrowserLPw(userHandle);
15572        }
15573    }
15574
15575    void newUserCreatedLILPw(final int userHandle) {
15576        // We cannot grant the default permissions with a lock held as
15577        // we query providers from other components for default handlers
15578        // such as enabled IMEs, etc.
15579        mHandler.post(new Runnable() {
15580            @Override
15581            public void run() {
15582                mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
15583            }
15584        });
15585    }
15586
15587    @Override
15588    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
15589        mContext.enforceCallingOrSelfPermission(
15590                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15591                "Only package verification agents can read the verifier device identity");
15592
15593        synchronized (mPackages) {
15594            return mSettings.getVerifierDeviceIdentityLPw();
15595        }
15596    }
15597
15598    @Override
15599    public void setPermissionEnforced(String permission, boolean enforced) {
15600        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
15601        if (READ_EXTERNAL_STORAGE.equals(permission)) {
15602            synchronized (mPackages) {
15603                if (mSettings.mReadExternalStorageEnforced == null
15604                        || mSettings.mReadExternalStorageEnforced != enforced) {
15605                    mSettings.mReadExternalStorageEnforced = enforced;
15606                    mSettings.writeLPr();
15607                }
15608            }
15609            // kill any non-foreground processes so we restart them and
15610            // grant/revoke the GID.
15611            final IActivityManager am = ActivityManagerNative.getDefault();
15612            if (am != null) {
15613                final long token = Binder.clearCallingIdentity();
15614                try {
15615                    am.killProcessesBelowForeground("setPermissionEnforcement");
15616                } catch (RemoteException e) {
15617                } finally {
15618                    Binder.restoreCallingIdentity(token);
15619                }
15620            }
15621        } else {
15622            throw new IllegalArgumentException("No selective enforcement for " + permission);
15623        }
15624    }
15625
15626    @Override
15627    @Deprecated
15628    public boolean isPermissionEnforced(String permission) {
15629        return true;
15630    }
15631
15632    @Override
15633    public boolean isStorageLow() {
15634        final long token = Binder.clearCallingIdentity();
15635        try {
15636            final DeviceStorageMonitorInternal
15637                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
15638            if (dsm != null) {
15639                return dsm.isMemoryLow();
15640            } else {
15641                return false;
15642            }
15643        } finally {
15644            Binder.restoreCallingIdentity(token);
15645        }
15646    }
15647
15648    @Override
15649    public IPackageInstaller getPackageInstaller() {
15650        return mInstallerService;
15651    }
15652
15653    private boolean userNeedsBadging(int userId) {
15654        int index = mUserNeedsBadging.indexOfKey(userId);
15655        if (index < 0) {
15656            final UserInfo userInfo;
15657            final long token = Binder.clearCallingIdentity();
15658            try {
15659                userInfo = sUserManager.getUserInfo(userId);
15660            } finally {
15661                Binder.restoreCallingIdentity(token);
15662            }
15663            final boolean b;
15664            if (userInfo != null && userInfo.isManagedProfile()) {
15665                b = true;
15666            } else {
15667                b = false;
15668            }
15669            mUserNeedsBadging.put(userId, b);
15670            return b;
15671        }
15672        return mUserNeedsBadging.valueAt(index);
15673    }
15674
15675    @Override
15676    public KeySet getKeySetByAlias(String packageName, String alias) {
15677        if (packageName == null || alias == null) {
15678            return null;
15679        }
15680        synchronized(mPackages) {
15681            final PackageParser.Package pkg = mPackages.get(packageName);
15682            if (pkg == null) {
15683                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15684                throw new IllegalArgumentException("Unknown package: " + packageName);
15685            }
15686            KeySetManagerService ksms = mSettings.mKeySetManagerService;
15687            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
15688        }
15689    }
15690
15691    @Override
15692    public KeySet getSigningKeySet(String packageName) {
15693        if (packageName == null) {
15694            return null;
15695        }
15696        synchronized(mPackages) {
15697            final PackageParser.Package pkg = mPackages.get(packageName);
15698            if (pkg == null) {
15699                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15700                throw new IllegalArgumentException("Unknown package: " + packageName);
15701            }
15702            if (pkg.applicationInfo.uid != Binder.getCallingUid()
15703                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
15704                throw new SecurityException("May not access signing KeySet of other apps.");
15705            }
15706            KeySetManagerService ksms = mSettings.mKeySetManagerService;
15707            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
15708        }
15709    }
15710
15711    @Override
15712    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
15713        if (packageName == null || ks == null) {
15714            return false;
15715        }
15716        synchronized(mPackages) {
15717            final PackageParser.Package pkg = mPackages.get(packageName);
15718            if (pkg == null) {
15719                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15720                throw new IllegalArgumentException("Unknown package: " + packageName);
15721            }
15722            IBinder ksh = ks.getToken();
15723            if (ksh instanceof KeySetHandle) {
15724                KeySetManagerService ksms = mSettings.mKeySetManagerService;
15725                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
15726            }
15727            return false;
15728        }
15729    }
15730
15731    @Override
15732    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
15733        if (packageName == null || ks == null) {
15734            return false;
15735        }
15736        synchronized(mPackages) {
15737            final PackageParser.Package pkg = mPackages.get(packageName);
15738            if (pkg == null) {
15739                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15740                throw new IllegalArgumentException("Unknown package: " + packageName);
15741            }
15742            IBinder ksh = ks.getToken();
15743            if (ksh instanceof KeySetHandle) {
15744                KeySetManagerService ksms = mSettings.mKeySetManagerService;
15745                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
15746            }
15747            return false;
15748        }
15749    }
15750
15751    public void getUsageStatsIfNoPackageUsageInfo() {
15752        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
15753            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
15754            if (usm == null) {
15755                throw new IllegalStateException("UsageStatsManager must be initialized");
15756            }
15757            long now = System.currentTimeMillis();
15758            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
15759            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
15760                String packageName = entry.getKey();
15761                PackageParser.Package pkg = mPackages.get(packageName);
15762                if (pkg == null) {
15763                    continue;
15764                }
15765                UsageStats usage = entry.getValue();
15766                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
15767                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
15768            }
15769        }
15770    }
15771
15772    /**
15773     * Check and throw if the given before/after packages would be considered a
15774     * downgrade.
15775     */
15776    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
15777            throws PackageManagerException {
15778        if (after.versionCode < before.mVersionCode) {
15779            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15780                    "Update version code " + after.versionCode + " is older than current "
15781                    + before.mVersionCode);
15782        } else if (after.versionCode == before.mVersionCode) {
15783            if (after.baseRevisionCode < before.baseRevisionCode) {
15784                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15785                        "Update base revision code " + after.baseRevisionCode
15786                        + " is older than current " + before.baseRevisionCode);
15787            }
15788
15789            if (!ArrayUtils.isEmpty(after.splitNames)) {
15790                for (int i = 0; i < after.splitNames.length; i++) {
15791                    final String splitName = after.splitNames[i];
15792                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
15793                    if (j != -1) {
15794                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
15795                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15796                                    "Update split " + splitName + " revision code "
15797                                    + after.splitRevisionCodes[i] + " is older than current "
15798                                    + before.splitRevisionCodes[j]);
15799                        }
15800                    }
15801                }
15802            }
15803        }
15804    }
15805
15806    private static class MoveCallbacks extends Handler {
15807        private static final int MSG_CREATED = 1;
15808        private static final int MSG_STATUS_CHANGED = 2;
15809
15810        private final RemoteCallbackList<IPackageMoveObserver>
15811                mCallbacks = new RemoteCallbackList<>();
15812
15813        private final SparseIntArray mLastStatus = new SparseIntArray();
15814
15815        public MoveCallbacks(Looper looper) {
15816            super(looper);
15817        }
15818
15819        public void register(IPackageMoveObserver callback) {
15820            mCallbacks.register(callback);
15821        }
15822
15823        public void unregister(IPackageMoveObserver callback) {
15824            mCallbacks.unregister(callback);
15825        }
15826
15827        @Override
15828        public void handleMessage(Message msg) {
15829            final SomeArgs args = (SomeArgs) msg.obj;
15830            final int n = mCallbacks.beginBroadcast();
15831            for (int i = 0; i < n; i++) {
15832                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
15833                try {
15834                    invokeCallback(callback, msg.what, args);
15835                } catch (RemoteException ignored) {
15836                }
15837            }
15838            mCallbacks.finishBroadcast();
15839            args.recycle();
15840        }
15841
15842        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
15843                throws RemoteException {
15844            switch (what) {
15845                case MSG_CREATED: {
15846                    callback.onCreated(args.argi1, (Bundle) args.arg2);
15847                    break;
15848                }
15849                case MSG_STATUS_CHANGED: {
15850                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
15851                    break;
15852                }
15853            }
15854        }
15855
15856        private void notifyCreated(int moveId, Bundle extras) {
15857            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
15858
15859            final SomeArgs args = SomeArgs.obtain();
15860            args.argi1 = moveId;
15861            args.arg2 = extras;
15862            obtainMessage(MSG_CREATED, args).sendToTarget();
15863        }
15864
15865        private void notifyStatusChanged(int moveId, int status) {
15866            notifyStatusChanged(moveId, status, -1);
15867        }
15868
15869        private void notifyStatusChanged(int moveId, int status, long estMillis) {
15870            Slog.v(TAG, "Move " + moveId + " status " + status);
15871
15872            final SomeArgs args = SomeArgs.obtain();
15873            args.argi1 = moveId;
15874            args.argi2 = status;
15875            args.arg3 = estMillis;
15876            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
15877
15878            synchronized (mLastStatus) {
15879                mLastStatus.put(moveId, status);
15880            }
15881        }
15882    }
15883
15884    private final class OnPermissionChangeListeners extends Handler {
15885        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
15886
15887        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
15888                new RemoteCallbackList<>();
15889
15890        public OnPermissionChangeListeners(Looper looper) {
15891            super(looper);
15892        }
15893
15894        @Override
15895        public void handleMessage(Message msg) {
15896            switch (msg.what) {
15897                case MSG_ON_PERMISSIONS_CHANGED: {
15898                    final int uid = msg.arg1;
15899                    handleOnPermissionsChanged(uid);
15900                } break;
15901            }
15902        }
15903
15904        public void addListenerLocked(IOnPermissionsChangeListener listener) {
15905            mPermissionListeners.register(listener);
15906
15907        }
15908
15909        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
15910            mPermissionListeners.unregister(listener);
15911        }
15912
15913        public void onPermissionsChanged(int uid) {
15914            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
15915                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
15916            }
15917        }
15918
15919        private void handleOnPermissionsChanged(int uid) {
15920            final int count = mPermissionListeners.beginBroadcast();
15921            try {
15922                for (int i = 0; i < count; i++) {
15923                    IOnPermissionsChangeListener callback = mPermissionListeners
15924                            .getBroadcastItem(i);
15925                    try {
15926                        callback.onPermissionsChanged(uid);
15927                    } catch (RemoteException e) {
15928                        Log.e(TAG, "Permission listener is dead", e);
15929                    }
15930                }
15931            } finally {
15932                mPermissionListeners.finishBroadcast();
15933            }
15934        }
15935    }
15936
15937    private class PackageManagerInternalImpl extends PackageManagerInternal {
15938        @Override
15939        public void setLocationPackagesProvider(PackagesProvider provider) {
15940            synchronized (mPackages) {
15941                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
15942            }
15943        }
15944
15945        @Override
15946        public void setImePackagesProvider(PackagesProvider provider) {
15947            synchronized (mPackages) {
15948                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
15949            }
15950        }
15951
15952        @Override
15953        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
15954            synchronized (mPackages) {
15955                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
15956            }
15957        }
15958
15959        @Override
15960        public void setSmsAppPackagesProvider(PackagesProvider provider) {
15961            synchronized (mPackages) {
15962                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
15963            }
15964        }
15965
15966        @Override
15967        public void setDialerAppPackagesProvider(PackagesProvider provider) {
15968            synchronized (mPackages) {
15969                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
15970            }
15971        }
15972
15973        @Override
15974        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
15975            synchronized (mPackages) {
15976                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
15977                        packageName, userId);
15978            }
15979        }
15980
15981        @Override
15982        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
15983            synchronized (mPackages) {
15984                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
15985                        packageName, userId);
15986            }
15987        }
15988    }
15989
15990    @Override
15991    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
15992        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
15993        synchronized (mPackages) {
15994            mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
15995                    packageNames, userId);
15996        }
15997    }
15998
15999    private static void enforceSystemOrPhoneCaller(String tag) {
16000        int callingUid = Binder.getCallingUid();
16001        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
16002            throw new SecurityException(
16003                    "Cannot call " + tag + " from UID " + callingUid);
16004        }
16005    }
16006}
16007