PackageManagerService.java revision cdfd230a392d0f0557a3a5bada221b7a05113392
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        synchronized (mPackages) {
3415            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3416            for (int userId : UserManagerService.getInstance().getUserIds()) {
3417                mDefaultPermissionPolicy.grantDefaultPermissions(userId);
3418            }
3419        }
3420    }
3421
3422    @Override
3423    public int getPermissionFlags(String name, String packageName, int userId) {
3424        if (!sUserManager.exists(userId)) {
3425            return 0;
3426        }
3427
3428        mContext.enforceCallingOrSelfPermission(
3429                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3430                "getPermissionFlags");
3431
3432        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3433                "getPermissionFlags");
3434
3435        synchronized (mPackages) {
3436            final PackageParser.Package pkg = mPackages.get(packageName);
3437            if (pkg == null) {
3438                throw new IllegalArgumentException("Unknown package: " + packageName);
3439            }
3440
3441            final BasePermission bp = mSettings.mPermissions.get(name);
3442            if (bp == null) {
3443                throw new IllegalArgumentException("Unknown permission: " + name);
3444            }
3445
3446            SettingBase sb = (SettingBase) pkg.mExtras;
3447            if (sb == null) {
3448                throw new IllegalArgumentException("Unknown package: " + packageName);
3449            }
3450
3451            PermissionsState permissionsState = sb.getPermissionsState();
3452            return permissionsState.getPermissionFlags(name, userId);
3453        }
3454    }
3455
3456    @Override
3457    public void updatePermissionFlags(String name, String packageName, int flagMask,
3458            int flagValues, int userId) {
3459        if (!sUserManager.exists(userId)) {
3460            return;
3461        }
3462
3463        mContext.enforceCallingOrSelfPermission(
3464                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3465                "updatePermissionFlags");
3466
3467        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3468                "updatePermissionFlags");
3469
3470        // Only the system can change system fixed flags.
3471        if (getCallingUid() != Process.SYSTEM_UID) {
3472            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3473            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3474        }
3475
3476        synchronized (mPackages) {
3477            final PackageParser.Package pkg = mPackages.get(packageName);
3478            if (pkg == null) {
3479                throw new IllegalArgumentException("Unknown package: " + packageName);
3480            }
3481
3482            final BasePermission bp = mSettings.mPermissions.get(name);
3483            if (bp == null) {
3484                throw new IllegalArgumentException("Unknown permission: " + name);
3485            }
3486
3487            SettingBase sb = (SettingBase) pkg.mExtras;
3488            if (sb == null) {
3489                throw new IllegalArgumentException("Unknown package: " + packageName);
3490            }
3491
3492            PermissionsState permissionsState = sb.getPermissionsState();
3493
3494            // Only the package manager can change flags for system component permissions.
3495            final int flags = permissionsState.getPermissionFlags(bp.name, userId);
3496            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3497                return;
3498            }
3499
3500            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3501
3502            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3503                // Install and runtime permissions are stored in different places,
3504                // so figure out what permission changed and persist the change.
3505                if (permissionsState.getInstallPermissionState(name) != null) {
3506                    scheduleWriteSettingsLocked();
3507                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3508                        || hadState) {
3509                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3510                }
3511            }
3512        }
3513    }
3514
3515    /**
3516     * Update the permission flags for all packages and runtime permissions of a user in order
3517     * to allow device or profile owner to remove POLICY_FIXED.
3518     */
3519    @Override
3520    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3521        if (!sUserManager.exists(userId)) {
3522            return;
3523        }
3524
3525        mContext.enforceCallingOrSelfPermission(
3526                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3527                "updatePermissionFlagsForAllApps");
3528
3529        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3530                "updatePermissionFlagsForAllApps");
3531
3532        // Only the system can change system fixed flags.
3533        if (getCallingUid() != Process.SYSTEM_UID) {
3534            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3535            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3536        }
3537
3538        synchronized (mPackages) {
3539            boolean changed = false;
3540            final int packageCount = mPackages.size();
3541            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
3542                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
3543                SettingBase sb = (SettingBase) pkg.mExtras;
3544                if (sb == null) {
3545                    continue;
3546                }
3547                PermissionsState permissionsState = sb.getPermissionsState();
3548                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
3549                        userId, flagMask, flagValues);
3550            }
3551            if (changed) {
3552                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3553            }
3554        }
3555    }
3556
3557    @Override
3558    public boolean shouldShowRequestPermissionRationale(String permissionName,
3559            String packageName, int userId) {
3560        if (UserHandle.getCallingUserId() != userId) {
3561            mContext.enforceCallingPermission(
3562                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3563                    "canShowRequestPermissionRationale for user " + userId);
3564        }
3565
3566        final int uid = getPackageUid(packageName, userId);
3567        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
3568            return false;
3569        }
3570
3571        if (checkPermission(permissionName, packageName, userId)
3572                == PackageManager.PERMISSION_GRANTED) {
3573            return false;
3574        }
3575
3576        final int flags;
3577
3578        final long identity = Binder.clearCallingIdentity();
3579        try {
3580            flags = getPermissionFlags(permissionName,
3581                    packageName, userId);
3582        } finally {
3583            Binder.restoreCallingIdentity(identity);
3584        }
3585
3586        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
3587                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
3588                | PackageManager.FLAG_PERMISSION_USER_FIXED;
3589
3590        if ((flags & fixedFlags) != 0) {
3591            return false;
3592        }
3593
3594        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
3595    }
3596
3597    void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) {
3598        BasePermission bp = mSettings.mPermissions.get(permission);
3599        if (bp == null) {
3600            throw new SecurityException("Missing " + permission + " permission");
3601        }
3602
3603        SettingBase sb = (SettingBase) pkg.mExtras;
3604        PermissionsState permissionsState = sb.getPermissionsState();
3605
3606        if (permissionsState.grantInstallPermission(bp) !=
3607                PermissionsState.PERMISSION_OPERATION_FAILURE) {
3608            scheduleWriteSettingsLocked();
3609        }
3610    }
3611
3612    @Override
3613    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3614        mContext.enforceCallingOrSelfPermission(
3615                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
3616                "addOnPermissionsChangeListener");
3617
3618        synchronized (mPackages) {
3619            mOnPermissionChangeListeners.addListenerLocked(listener);
3620        }
3621    }
3622
3623    @Override
3624    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3625        synchronized (mPackages) {
3626            mOnPermissionChangeListeners.removeListenerLocked(listener);
3627        }
3628    }
3629
3630    @Override
3631    public boolean isProtectedBroadcast(String actionName) {
3632        synchronized (mPackages) {
3633            return mProtectedBroadcasts.contains(actionName);
3634        }
3635    }
3636
3637    @Override
3638    public int checkSignatures(String pkg1, String pkg2) {
3639        synchronized (mPackages) {
3640            final PackageParser.Package p1 = mPackages.get(pkg1);
3641            final PackageParser.Package p2 = mPackages.get(pkg2);
3642            if (p1 == null || p1.mExtras == null
3643                    || p2 == null || p2.mExtras == null) {
3644                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3645            }
3646            return compareSignatures(p1.mSignatures, p2.mSignatures);
3647        }
3648    }
3649
3650    @Override
3651    public int checkUidSignatures(int uid1, int uid2) {
3652        // Map to base uids.
3653        uid1 = UserHandle.getAppId(uid1);
3654        uid2 = UserHandle.getAppId(uid2);
3655        // reader
3656        synchronized (mPackages) {
3657            Signature[] s1;
3658            Signature[] s2;
3659            Object obj = mSettings.getUserIdLPr(uid1);
3660            if (obj != null) {
3661                if (obj instanceof SharedUserSetting) {
3662                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3663                } else if (obj instanceof PackageSetting) {
3664                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3665                } else {
3666                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3667                }
3668            } else {
3669                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3670            }
3671            obj = mSettings.getUserIdLPr(uid2);
3672            if (obj != null) {
3673                if (obj instanceof SharedUserSetting) {
3674                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3675                } else if (obj instanceof PackageSetting) {
3676                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3677                } else {
3678                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3679                }
3680            } else {
3681                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3682            }
3683            return compareSignatures(s1, s2);
3684        }
3685    }
3686
3687    private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) {
3688        final long identity = Binder.clearCallingIdentity();
3689        try {
3690            if (sb instanceof SharedUserSetting) {
3691                SharedUserSetting sus = (SharedUserSetting) sb;
3692                final int packageCount = sus.packages.size();
3693                for (int i = 0; i < packageCount; i++) {
3694                    PackageSetting susPs = sus.packages.valueAt(i);
3695                    if (userId == UserHandle.USER_ALL) {
3696                        killApplication(susPs.pkg.packageName, susPs.appId, reason);
3697                    } else {
3698                        final int uid = UserHandle.getUid(userId, susPs.appId);
3699                        killUid(uid, reason);
3700                    }
3701                }
3702            } else if (sb instanceof PackageSetting) {
3703                PackageSetting ps = (PackageSetting) sb;
3704                if (userId == UserHandle.USER_ALL) {
3705                    killApplication(ps.pkg.packageName, ps.appId, reason);
3706                } else {
3707                    final int uid = UserHandle.getUid(userId, ps.appId);
3708                    killUid(uid, reason);
3709                }
3710            }
3711        } finally {
3712            Binder.restoreCallingIdentity(identity);
3713        }
3714    }
3715
3716    private static void killUid(int uid, String reason) {
3717        IActivityManager am = ActivityManagerNative.getDefault();
3718        if (am != null) {
3719            try {
3720                am.killUid(uid, reason);
3721            } catch (RemoteException e) {
3722                /* ignore - same process */
3723            }
3724        }
3725    }
3726
3727    /**
3728     * Compares two sets of signatures. Returns:
3729     * <br />
3730     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3731     * <br />
3732     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3733     * <br />
3734     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3735     * <br />
3736     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3737     * <br />
3738     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3739     */
3740    static int compareSignatures(Signature[] s1, Signature[] s2) {
3741        if (s1 == null) {
3742            return s2 == null
3743                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3744                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3745        }
3746
3747        if (s2 == null) {
3748            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3749        }
3750
3751        if (s1.length != s2.length) {
3752            return PackageManager.SIGNATURE_NO_MATCH;
3753        }
3754
3755        // Since both signature sets are of size 1, we can compare without HashSets.
3756        if (s1.length == 1) {
3757            return s1[0].equals(s2[0]) ?
3758                    PackageManager.SIGNATURE_MATCH :
3759                    PackageManager.SIGNATURE_NO_MATCH;
3760        }
3761
3762        ArraySet<Signature> set1 = new ArraySet<Signature>();
3763        for (Signature sig : s1) {
3764            set1.add(sig);
3765        }
3766        ArraySet<Signature> set2 = new ArraySet<Signature>();
3767        for (Signature sig : s2) {
3768            set2.add(sig);
3769        }
3770        // Make sure s2 contains all signatures in s1.
3771        if (set1.equals(set2)) {
3772            return PackageManager.SIGNATURE_MATCH;
3773        }
3774        return PackageManager.SIGNATURE_NO_MATCH;
3775    }
3776
3777    /**
3778     * If the database version for this type of package (internal storage or
3779     * external storage) is less than the version where package signatures
3780     * were updated, return true.
3781     */
3782    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3783        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
3784                DatabaseVersion.SIGNATURE_END_ENTITY))
3785                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
3786                        DatabaseVersion.SIGNATURE_END_ENTITY));
3787    }
3788
3789    /**
3790     * Used for backward compatibility to make sure any packages with
3791     * certificate chains get upgraded to the new style. {@code existingSigs}
3792     * will be in the old format (since they were stored on disk from before the
3793     * system upgrade) and {@code scannedSigs} will be in the newer format.
3794     */
3795    private int compareSignaturesCompat(PackageSignatures existingSigs,
3796            PackageParser.Package scannedPkg) {
3797        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
3798            return PackageManager.SIGNATURE_NO_MATCH;
3799        }
3800
3801        ArraySet<Signature> existingSet = new ArraySet<Signature>();
3802        for (Signature sig : existingSigs.mSignatures) {
3803            existingSet.add(sig);
3804        }
3805        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
3806        for (Signature sig : scannedPkg.mSignatures) {
3807            try {
3808                Signature[] chainSignatures = sig.getChainSignatures();
3809                for (Signature chainSig : chainSignatures) {
3810                    scannedCompatSet.add(chainSig);
3811                }
3812            } catch (CertificateEncodingException e) {
3813                scannedCompatSet.add(sig);
3814            }
3815        }
3816        /*
3817         * Make sure the expanded scanned set contains all signatures in the
3818         * existing one.
3819         */
3820        if (scannedCompatSet.equals(existingSet)) {
3821            // Migrate the old signatures to the new scheme.
3822            existingSigs.assignSignatures(scannedPkg.mSignatures);
3823            // The new KeySets will be re-added later in the scanning process.
3824            synchronized (mPackages) {
3825                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
3826            }
3827            return PackageManager.SIGNATURE_MATCH;
3828        }
3829        return PackageManager.SIGNATURE_NO_MATCH;
3830    }
3831
3832    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3833        if (isExternal(scannedPkg)) {
3834            return mSettings.isExternalDatabaseVersionOlderThan(
3835                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3836        } else {
3837            return mSettings.isInternalDatabaseVersionOlderThan(
3838                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3839        }
3840    }
3841
3842    private int compareSignaturesRecover(PackageSignatures existingSigs,
3843            PackageParser.Package scannedPkg) {
3844        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
3845            return PackageManager.SIGNATURE_NO_MATCH;
3846        }
3847
3848        String msg = null;
3849        try {
3850            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
3851                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
3852                        + scannedPkg.packageName);
3853                return PackageManager.SIGNATURE_MATCH;
3854            }
3855        } catch (CertificateException e) {
3856            msg = e.getMessage();
3857        }
3858
3859        logCriticalInfo(Log.INFO,
3860                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
3861        return PackageManager.SIGNATURE_NO_MATCH;
3862    }
3863
3864    @Override
3865    public String[] getPackagesForUid(int uid) {
3866        uid = UserHandle.getAppId(uid);
3867        // reader
3868        synchronized (mPackages) {
3869            Object obj = mSettings.getUserIdLPr(uid);
3870            if (obj instanceof SharedUserSetting) {
3871                final SharedUserSetting sus = (SharedUserSetting) obj;
3872                final int N = sus.packages.size();
3873                final String[] res = new String[N];
3874                final Iterator<PackageSetting> it = sus.packages.iterator();
3875                int i = 0;
3876                while (it.hasNext()) {
3877                    res[i++] = it.next().name;
3878                }
3879                return res;
3880            } else if (obj instanceof PackageSetting) {
3881                final PackageSetting ps = (PackageSetting) obj;
3882                return new String[] { ps.name };
3883            }
3884        }
3885        return null;
3886    }
3887
3888    @Override
3889    public String getNameForUid(int uid) {
3890        // reader
3891        synchronized (mPackages) {
3892            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3893            if (obj instanceof SharedUserSetting) {
3894                final SharedUserSetting sus = (SharedUserSetting) obj;
3895                return sus.name + ":" + sus.userId;
3896            } else if (obj instanceof PackageSetting) {
3897                final PackageSetting ps = (PackageSetting) obj;
3898                return ps.name;
3899            }
3900        }
3901        return null;
3902    }
3903
3904    @Override
3905    public int getUidForSharedUser(String sharedUserName) {
3906        if(sharedUserName == null) {
3907            return -1;
3908        }
3909        // reader
3910        synchronized (mPackages) {
3911            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
3912            if (suid == null) {
3913                return -1;
3914            }
3915            return suid.userId;
3916        }
3917    }
3918
3919    @Override
3920    public int getFlagsForUid(int uid) {
3921        synchronized (mPackages) {
3922            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3923            if (obj instanceof SharedUserSetting) {
3924                final SharedUserSetting sus = (SharedUserSetting) obj;
3925                return sus.pkgFlags;
3926            } else if (obj instanceof PackageSetting) {
3927                final PackageSetting ps = (PackageSetting) obj;
3928                return ps.pkgFlags;
3929            }
3930        }
3931        return 0;
3932    }
3933
3934    @Override
3935    public int getPrivateFlagsForUid(int uid) {
3936        synchronized (mPackages) {
3937            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3938            if (obj instanceof SharedUserSetting) {
3939                final SharedUserSetting sus = (SharedUserSetting) obj;
3940                return sus.pkgPrivateFlags;
3941            } else if (obj instanceof PackageSetting) {
3942                final PackageSetting ps = (PackageSetting) obj;
3943                return ps.pkgPrivateFlags;
3944            }
3945        }
3946        return 0;
3947    }
3948
3949    @Override
3950    public boolean isUidPrivileged(int uid) {
3951        uid = UserHandle.getAppId(uid);
3952        // reader
3953        synchronized (mPackages) {
3954            Object obj = mSettings.getUserIdLPr(uid);
3955            if (obj instanceof SharedUserSetting) {
3956                final SharedUserSetting sus = (SharedUserSetting) obj;
3957                final Iterator<PackageSetting> it = sus.packages.iterator();
3958                while (it.hasNext()) {
3959                    if (it.next().isPrivileged()) {
3960                        return true;
3961                    }
3962                }
3963            } else if (obj instanceof PackageSetting) {
3964                final PackageSetting ps = (PackageSetting) obj;
3965                return ps.isPrivileged();
3966            }
3967        }
3968        return false;
3969    }
3970
3971    @Override
3972    public String[] getAppOpPermissionPackages(String permissionName) {
3973        synchronized (mPackages) {
3974            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
3975            if (pkgs == null) {
3976                return null;
3977            }
3978            return pkgs.toArray(new String[pkgs.size()]);
3979        }
3980    }
3981
3982    @Override
3983    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
3984            int flags, int userId) {
3985        if (!sUserManager.exists(userId)) return null;
3986        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
3987        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3988        return chooseBestActivity(intent, resolvedType, flags, query, userId);
3989    }
3990
3991    @Override
3992    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
3993            IntentFilter filter, int match, ComponentName activity) {
3994        final int userId = UserHandle.getCallingUserId();
3995        if (DEBUG_PREFERRED) {
3996            Log.v(TAG, "setLastChosenActivity intent=" + intent
3997                + " resolvedType=" + resolvedType
3998                + " flags=" + flags
3999                + " filter=" + filter
4000                + " match=" + match
4001                + " activity=" + activity);
4002            filter.dump(new PrintStreamPrinter(System.out), "    ");
4003        }
4004        intent.setComponent(null);
4005        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4006        // Find any earlier preferred or last chosen entries and nuke them
4007        findPreferredActivity(intent, resolvedType,
4008                flags, query, 0, false, true, false, userId);
4009        // Add the new activity as the last chosen for this filter
4010        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4011                "Setting last chosen");
4012    }
4013
4014    @Override
4015    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4016        final int userId = UserHandle.getCallingUserId();
4017        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4018        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4019        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4020                false, false, false, userId);
4021    }
4022
4023    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4024            int flags, List<ResolveInfo> query, int userId) {
4025        if (query != null) {
4026            final int N = query.size();
4027            if (N == 1) {
4028                return query.get(0);
4029            } else if (N > 1) {
4030                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4031                // If there is more than one activity with the same priority,
4032                // then let the user decide between them.
4033                ResolveInfo r0 = query.get(0);
4034                ResolveInfo r1 = query.get(1);
4035                if (DEBUG_INTENT_MATCHING || debug) {
4036                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4037                            + r1.activityInfo.name + "=" + r1.priority);
4038                }
4039                // If the first activity has a higher priority, or a different
4040                // default, then it is always desireable to pick it.
4041                if (r0.priority != r1.priority
4042                        || r0.preferredOrder != r1.preferredOrder
4043                        || r0.isDefault != r1.isDefault) {
4044                    return query.get(0);
4045                }
4046                // If we have saved a preference for a preferred activity for
4047                // this Intent, use that.
4048                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4049                        flags, query, r0.priority, true, false, debug, userId);
4050                if (ri != null) {
4051                    return ri;
4052                }
4053                if (userId != 0) {
4054                    ri = new ResolveInfo(mResolveInfo);
4055                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
4056                    ri.activityInfo.applicationInfo = new ApplicationInfo(
4057                            ri.activityInfo.applicationInfo);
4058                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4059                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4060                    return ri;
4061                }
4062                return mResolveInfo;
4063            }
4064        }
4065        return null;
4066    }
4067
4068    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4069            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4070        final int N = query.size();
4071        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4072                .get(userId);
4073        // Get the list of persistent preferred activities that handle the intent
4074        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4075        List<PersistentPreferredActivity> pprefs = ppir != null
4076                ? ppir.queryIntent(intent, resolvedType,
4077                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4078                : null;
4079        if (pprefs != null && pprefs.size() > 0) {
4080            final int M = pprefs.size();
4081            for (int i=0; i<M; i++) {
4082                final PersistentPreferredActivity ppa = pprefs.get(i);
4083                if (DEBUG_PREFERRED || debug) {
4084                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4085                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4086                            + "\n  component=" + ppa.mComponent);
4087                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4088                }
4089                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4090                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4091                if (DEBUG_PREFERRED || debug) {
4092                    Slog.v(TAG, "Found persistent preferred activity:");
4093                    if (ai != null) {
4094                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4095                    } else {
4096                        Slog.v(TAG, "  null");
4097                    }
4098                }
4099                if (ai == null) {
4100                    // This previously registered persistent preferred activity
4101                    // component is no longer known. Ignore it and do NOT remove it.
4102                    continue;
4103                }
4104                for (int j=0; j<N; j++) {
4105                    final ResolveInfo ri = query.get(j);
4106                    if (!ri.activityInfo.applicationInfo.packageName
4107                            .equals(ai.applicationInfo.packageName)) {
4108                        continue;
4109                    }
4110                    if (!ri.activityInfo.name.equals(ai.name)) {
4111                        continue;
4112                    }
4113                    //  Found a persistent preference that can handle the intent.
4114                    if (DEBUG_PREFERRED || debug) {
4115                        Slog.v(TAG, "Returning persistent preferred activity: " +
4116                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4117                    }
4118                    return ri;
4119                }
4120            }
4121        }
4122        return null;
4123    }
4124
4125    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4126            List<ResolveInfo> query, int priority, boolean always,
4127            boolean removeMatches, boolean debug, int userId) {
4128        if (!sUserManager.exists(userId)) return null;
4129        // writer
4130        synchronized (mPackages) {
4131            if (intent.getSelector() != null) {
4132                intent = intent.getSelector();
4133            }
4134            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4135
4136            // Try to find a matching persistent preferred activity.
4137            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4138                    debug, userId);
4139
4140            // If a persistent preferred activity matched, use it.
4141            if (pri != null) {
4142                return pri;
4143            }
4144
4145            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4146            // Get the list of preferred activities that handle the intent
4147            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4148            List<PreferredActivity> prefs = pir != null
4149                    ? pir.queryIntent(intent, resolvedType,
4150                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4151                    : null;
4152            if (prefs != null && prefs.size() > 0) {
4153                boolean changed = false;
4154                try {
4155                    // First figure out how good the original match set is.
4156                    // We will only allow preferred activities that came
4157                    // from the same match quality.
4158                    int match = 0;
4159
4160                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4161
4162                    final int N = query.size();
4163                    for (int j=0; j<N; j++) {
4164                        final ResolveInfo ri = query.get(j);
4165                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4166                                + ": 0x" + Integer.toHexString(match));
4167                        if (ri.match > match) {
4168                            match = ri.match;
4169                        }
4170                    }
4171
4172                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4173                            + Integer.toHexString(match));
4174
4175                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4176                    final int M = prefs.size();
4177                    for (int i=0; i<M; i++) {
4178                        final PreferredActivity pa = prefs.get(i);
4179                        if (DEBUG_PREFERRED || debug) {
4180                            Slog.v(TAG, "Checking PreferredActivity ds="
4181                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4182                                    + "\n  component=" + pa.mPref.mComponent);
4183                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4184                        }
4185                        if (pa.mPref.mMatch != match) {
4186                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4187                                    + Integer.toHexString(pa.mPref.mMatch));
4188                            continue;
4189                        }
4190                        // If it's not an "always" type preferred activity and that's what we're
4191                        // looking for, skip it.
4192                        if (always && !pa.mPref.mAlways) {
4193                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4194                            continue;
4195                        }
4196                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4197                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4198                        if (DEBUG_PREFERRED || debug) {
4199                            Slog.v(TAG, "Found preferred activity:");
4200                            if (ai != null) {
4201                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4202                            } else {
4203                                Slog.v(TAG, "  null");
4204                            }
4205                        }
4206                        if (ai == null) {
4207                            // This previously registered preferred activity
4208                            // component is no longer known.  Most likely an update
4209                            // to the app was installed and in the new version this
4210                            // component no longer exists.  Clean it up by removing
4211                            // it from the preferred activities list, and skip it.
4212                            Slog.w(TAG, "Removing dangling preferred activity: "
4213                                    + pa.mPref.mComponent);
4214                            pir.removeFilter(pa);
4215                            changed = true;
4216                            continue;
4217                        }
4218                        for (int j=0; j<N; j++) {
4219                            final ResolveInfo ri = query.get(j);
4220                            if (!ri.activityInfo.applicationInfo.packageName
4221                                    .equals(ai.applicationInfo.packageName)) {
4222                                continue;
4223                            }
4224                            if (!ri.activityInfo.name.equals(ai.name)) {
4225                                continue;
4226                            }
4227
4228                            if (removeMatches) {
4229                                pir.removeFilter(pa);
4230                                changed = true;
4231                                if (DEBUG_PREFERRED) {
4232                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4233                                }
4234                                break;
4235                            }
4236
4237                            // Okay we found a previously set preferred or last chosen app.
4238                            // If the result set is different from when this
4239                            // was created, we need to clear it and re-ask the
4240                            // user their preference, if we're looking for an "always" type entry.
4241                            if (always && !pa.mPref.sameSet(query)) {
4242                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4243                                        + intent + " type " + resolvedType);
4244                                if (DEBUG_PREFERRED) {
4245                                    Slog.v(TAG, "Removing preferred activity since set changed "
4246                                            + pa.mPref.mComponent);
4247                                }
4248                                pir.removeFilter(pa);
4249                                // Re-add the filter as a "last chosen" entry (!always)
4250                                PreferredActivity lastChosen = new PreferredActivity(
4251                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4252                                pir.addFilter(lastChosen);
4253                                changed = true;
4254                                return null;
4255                            }
4256
4257                            // Yay! Either the set matched or we're looking for the last chosen
4258                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4259                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4260                            return ri;
4261                        }
4262                    }
4263                } finally {
4264                    if (changed) {
4265                        if (DEBUG_PREFERRED) {
4266                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4267                        }
4268                        scheduleWritePackageRestrictionsLocked(userId);
4269                    }
4270                }
4271            }
4272        }
4273        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4274        return null;
4275    }
4276
4277    /*
4278     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4279     */
4280    @Override
4281    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4282            int targetUserId) {
4283        mContext.enforceCallingOrSelfPermission(
4284                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4285        List<CrossProfileIntentFilter> matches =
4286                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4287        if (matches != null) {
4288            int size = matches.size();
4289            for (int i = 0; i < size; i++) {
4290                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4291            }
4292        }
4293        if (hasWebURI(intent)) {
4294            // cross-profile app linking works only towards the parent.
4295            final UserInfo parent = getProfileParent(sourceUserId);
4296            synchronized(mPackages) {
4297                return getCrossProfileDomainPreferredLpr(intent, resolvedType, 0, sourceUserId,
4298                        parent.id) != null;
4299            }
4300        }
4301        return false;
4302    }
4303
4304    private UserInfo getProfileParent(int userId) {
4305        final long identity = Binder.clearCallingIdentity();
4306        try {
4307            return sUserManager.getProfileParent(userId);
4308        } finally {
4309            Binder.restoreCallingIdentity(identity);
4310        }
4311    }
4312
4313    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4314            String resolvedType, int userId) {
4315        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4316        if (resolver != null) {
4317            return resolver.queryIntent(intent, resolvedType, false, userId);
4318        }
4319        return null;
4320    }
4321
4322    @Override
4323    public List<ResolveInfo> queryIntentActivities(Intent intent,
4324            String resolvedType, int flags, int userId) {
4325        if (!sUserManager.exists(userId)) return Collections.emptyList();
4326        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4327        ComponentName comp = intent.getComponent();
4328        if (comp == null) {
4329            if (intent.getSelector() != null) {
4330                intent = intent.getSelector();
4331                comp = intent.getComponent();
4332            }
4333        }
4334
4335        if (comp != null) {
4336            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4337            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4338            if (ai != null) {
4339                final ResolveInfo ri = new ResolveInfo();
4340                ri.activityInfo = ai;
4341                list.add(ri);
4342            }
4343            return list;
4344        }
4345
4346        // reader
4347        synchronized (mPackages) {
4348            final String pkgName = intent.getPackage();
4349            if (pkgName == null) {
4350                List<CrossProfileIntentFilter> matchingFilters =
4351                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4352                // Check for results that need to skip the current profile.
4353                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4354                        resolvedType, flags, userId);
4355                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4356                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4357                    result.add(xpResolveInfo);
4358                    return filterIfNotPrimaryUser(result, userId);
4359                }
4360
4361                // Check for results in the current profile.
4362                List<ResolveInfo> result = mActivities.queryIntent(
4363                        intent, resolvedType, flags, userId);
4364
4365                // Check for cross profile results.
4366                xpResolveInfo = queryCrossProfileIntents(
4367                        matchingFilters, intent, resolvedType, flags, userId);
4368                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4369                    result.add(xpResolveInfo);
4370                    Collections.sort(result, mResolvePrioritySorter);
4371                }
4372                result = filterIfNotPrimaryUser(result, userId);
4373                if (hasWebURI(intent)) {
4374                    CrossProfileDomainInfo xpDomainInfo = null;
4375                    final UserInfo parent = getProfileParent(userId);
4376                    if (parent != null) {
4377                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4378                                flags, userId, parent.id);
4379                    }
4380                    if (xpDomainInfo != null) {
4381                        if (xpResolveInfo != null) {
4382                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4383                            // in the result.
4384                            result.remove(xpResolveInfo);
4385                        }
4386                        if (result.size() == 0) {
4387                            result.add(xpDomainInfo.resolveInfo);
4388                            return result;
4389                        }
4390                    } else if (result.size() <= 1) {
4391                        return result;
4392                    }
4393                    result = filterCandidatesWithDomainPreferredActivitiesLPr(flags, result,
4394                            xpDomainInfo);
4395                    Collections.sort(result, mResolvePrioritySorter);
4396                }
4397                return result;
4398            }
4399            final PackageParser.Package pkg = mPackages.get(pkgName);
4400            if (pkg != null) {
4401                return filterIfNotPrimaryUser(
4402                        mActivities.queryIntentForPackage(
4403                                intent, resolvedType, flags, pkg.activities, userId),
4404                        userId);
4405            }
4406            return new ArrayList<ResolveInfo>();
4407        }
4408    }
4409
4410    private static class CrossProfileDomainInfo {
4411        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4412        ResolveInfo resolveInfo;
4413        /* Best domain verification status of the activities found in the other profile */
4414        int bestDomainVerificationStatus;
4415    }
4416
4417    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4418            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4419        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_APP_LINKING,
4420                sourceUserId)) {
4421            return null;
4422        }
4423        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4424                resolvedType, flags, parentUserId);
4425
4426        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4427            return null;
4428        }
4429        CrossProfileDomainInfo result = null;
4430        int size = resultTargetUser.size();
4431        for (int i = 0; i < size; i++) {
4432            ResolveInfo riTargetUser = resultTargetUser.get(i);
4433            // Intent filter verification is only for filters that specify a host. So don't return
4434            // those that handle all web uris.
4435            if (riTargetUser.handleAllWebDataURI) {
4436                continue;
4437            }
4438            String packageName = riTargetUser.activityInfo.packageName;
4439            PackageSetting ps = mSettings.mPackages.get(packageName);
4440            if (ps == null) {
4441                continue;
4442            }
4443            int status = getDomainVerificationStatusLPr(ps, parentUserId);
4444            if (result == null) {
4445                result = new CrossProfileDomainInfo();
4446                result.resolveInfo =
4447                        createForwardingResolveInfo(null, sourceUserId, parentUserId);
4448                result.bestDomainVerificationStatus = status;
4449            } else {
4450                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
4451                        result.bestDomainVerificationStatus);
4452            }
4453        }
4454        return result;
4455    }
4456
4457    /**
4458     * Verification statuses are ordered from the worse to the best, except for
4459     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
4460     */
4461    private int bestDomainVerificationStatus(int status1, int status2) {
4462        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4463            return status2;
4464        }
4465        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4466            return status1;
4467        }
4468        return (int) MathUtils.max(status1, status2);
4469    }
4470
4471    private boolean isUserEnabled(int userId) {
4472        long callingId = Binder.clearCallingIdentity();
4473        try {
4474            UserInfo userInfo = sUserManager.getUserInfo(userId);
4475            return userInfo != null && userInfo.isEnabled();
4476        } finally {
4477            Binder.restoreCallingIdentity(callingId);
4478        }
4479    }
4480
4481    /**
4482     * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
4483     *
4484     * @return filtered list
4485     */
4486    private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
4487        if (userId == UserHandle.USER_OWNER) {
4488            return resolveInfos;
4489        }
4490        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4491            ResolveInfo info = resolveInfos.get(i);
4492            if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
4493                resolveInfos.remove(i);
4494            }
4495        }
4496        return resolveInfos;
4497    }
4498
4499    private static boolean hasWebURI(Intent intent) {
4500        if (intent.getData() == null) {
4501            return false;
4502        }
4503        final String scheme = intent.getScheme();
4504        if (TextUtils.isEmpty(scheme)) {
4505            return false;
4506        }
4507        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4508    }
4509
4510    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(
4511            int flags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo) {
4512        if (DEBUG_PREFERRED) {
4513            Slog.v("TAG", "Filtering results with prefered activities. Candidates count: " +
4514                    candidates.size());
4515        }
4516
4517        final int userId = UserHandle.getCallingUserId();
4518        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4519        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
4520        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4521        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4522        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4523
4524        synchronized (mPackages) {
4525            final int count = candidates.size();
4526            // First, try to use the domain preferred app. Partition the candidates into four lists:
4527            // one for the final results, one for the "do not use ever", one for "undefined status"
4528            // and finally one for "Browser App type".
4529            for (int n=0; n<count; n++) {
4530                ResolveInfo info = candidates.get(n);
4531                String packageName = info.activityInfo.packageName;
4532                PackageSetting ps = mSettings.mPackages.get(packageName);
4533                if (ps != null) {
4534                    // Add to the special match all list (Browser use case)
4535                    if (info.handleAllWebDataURI) {
4536                        matchAllList.add(info);
4537                        continue;
4538                    }
4539                    // Try to get the status from User settings first
4540                    int status = getDomainVerificationStatusLPr(ps, userId);
4541                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4542                        alwaysList.add(info);
4543                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4544                        neverList.add(info);
4545                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
4546                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
4547                        undefinedList.add(info);
4548                    }
4549                }
4550            }
4551            // First try to add the "always" resolution for the current user if there is any
4552            if (alwaysList.size() > 0) {
4553                result.addAll(alwaysList);
4554            // if there is an "always" for the parent user, add it.
4555            } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus
4556                    == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4557                result.add(xpDomainInfo.resolveInfo);
4558            } else {
4559                // Add all undefined Apps as we want them to appear in the Disambiguation dialog.
4560                result.addAll(undefinedList);
4561                if (xpDomainInfo != null && (
4562                        xpDomainInfo.bestDomainVerificationStatus
4563                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
4564                        || xpDomainInfo.bestDomainVerificationStatus
4565                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) {
4566                    result.add(xpDomainInfo.resolveInfo);
4567                }
4568                // Also add Browsers (all of them or only the default one)
4569                if ((flags & MATCH_ALL) != 0) {
4570                    result.addAll(matchAllList);
4571                } else {
4572                    // Try to add the Default Browser if we can
4573                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(
4574                            UserHandle.myUserId());
4575                    if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
4576                        boolean defaultBrowserFound = false;
4577                        final int browserCount = matchAllList.size();
4578                        for (int n=0; n<browserCount; n++) {
4579                            ResolveInfo browser = matchAllList.get(n);
4580                            if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) {
4581                                result.add(browser);
4582                                defaultBrowserFound = true;
4583                                break;
4584                            }
4585                        }
4586                        if (!defaultBrowserFound) {
4587                            result.addAll(matchAllList);
4588                        }
4589                    } else {
4590                        result.addAll(matchAllList);
4591                    }
4592                }
4593
4594                // If there is nothing selected, add all candidates and remove the ones that the User
4595                // has explicitely put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
4596                if (result.size() == 0) {
4597                    result.addAll(candidates);
4598                    result.removeAll(neverList);
4599                }
4600            }
4601        }
4602        if (DEBUG_PREFERRED) {
4603            Slog.v("TAG", "Filtered results with prefered activities. New candidates count: " +
4604                    result.size());
4605        }
4606        return result;
4607    }
4608
4609    private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4610        int status = ps.getDomainVerificationStatusForUser(userId);
4611        // if none available, get the master status
4612        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4613            if (ps.getIntentFilterVerificationInfo() != null) {
4614                status = ps.getIntentFilterVerificationInfo().getStatus();
4615            }
4616        }
4617        return status;
4618    }
4619
4620    private ResolveInfo querySkipCurrentProfileIntents(
4621            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4622            int flags, int sourceUserId) {
4623        if (matchingFilters != null) {
4624            int size = matchingFilters.size();
4625            for (int i = 0; i < size; i ++) {
4626                CrossProfileIntentFilter filter = matchingFilters.get(i);
4627                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4628                    // Checking if there are activities in the target user that can handle the
4629                    // intent.
4630                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4631                            flags, sourceUserId);
4632                    if (resolveInfo != null) {
4633                        return resolveInfo;
4634                    }
4635                }
4636            }
4637        }
4638        return null;
4639    }
4640
4641    // Return matching ResolveInfo if any for skip current profile intent filters.
4642    private ResolveInfo queryCrossProfileIntents(
4643            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4644            int flags, int sourceUserId) {
4645        if (matchingFilters != null) {
4646            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4647            // match the same intent. For performance reasons, it is better not to
4648            // run queryIntent twice for the same userId
4649            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4650            int size = matchingFilters.size();
4651            for (int i = 0; i < size; i++) {
4652                CrossProfileIntentFilter filter = matchingFilters.get(i);
4653                int targetUserId = filter.getTargetUserId();
4654                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4655                        && !alreadyTriedUserIds.get(targetUserId)) {
4656                    // Checking if there are activities in the target user that can handle the
4657                    // intent.
4658                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4659                            flags, sourceUserId);
4660                    if (resolveInfo != null) return resolveInfo;
4661                    alreadyTriedUserIds.put(targetUserId, true);
4662                }
4663            }
4664        }
4665        return null;
4666    }
4667
4668    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
4669            String resolvedType, int flags, int sourceUserId) {
4670        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4671                resolvedType, flags, filter.getTargetUserId());
4672        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
4673            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
4674        }
4675        return null;
4676    }
4677
4678    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
4679            int sourceUserId, int targetUserId) {
4680        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4681        String className;
4682        if (targetUserId == UserHandle.USER_OWNER) {
4683            className = FORWARD_INTENT_TO_USER_OWNER;
4684        } else {
4685            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4686        }
4687        ComponentName forwardingActivityComponentName = new ComponentName(
4688                mAndroidApplication.packageName, className);
4689        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
4690                sourceUserId);
4691        if (targetUserId == UserHandle.USER_OWNER) {
4692            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
4693            forwardingResolveInfo.noResourceId = true;
4694        }
4695        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
4696        forwardingResolveInfo.priority = 0;
4697        forwardingResolveInfo.preferredOrder = 0;
4698        forwardingResolveInfo.match = 0;
4699        forwardingResolveInfo.isDefault = true;
4700        forwardingResolveInfo.filter = filter;
4701        forwardingResolveInfo.targetUserId = targetUserId;
4702        return forwardingResolveInfo;
4703    }
4704
4705    @Override
4706    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
4707            Intent[] specifics, String[] specificTypes, Intent intent,
4708            String resolvedType, int flags, int userId) {
4709        if (!sUserManager.exists(userId)) return Collections.emptyList();
4710        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
4711                false, "query intent activity options");
4712        final String resultsAction = intent.getAction();
4713
4714        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
4715                | PackageManager.GET_RESOLVED_FILTER, userId);
4716
4717        if (DEBUG_INTENT_MATCHING) {
4718            Log.v(TAG, "Query " + intent + ": " + results);
4719        }
4720
4721        int specificsPos = 0;
4722        int N;
4723
4724        // todo: note that the algorithm used here is O(N^2).  This
4725        // isn't a problem in our current environment, but if we start running
4726        // into situations where we have more than 5 or 10 matches then this
4727        // should probably be changed to something smarter...
4728
4729        // First we go through and resolve each of the specific items
4730        // that were supplied, taking care of removing any corresponding
4731        // duplicate items in the generic resolve list.
4732        if (specifics != null) {
4733            for (int i=0; i<specifics.length; i++) {
4734                final Intent sintent = specifics[i];
4735                if (sintent == null) {
4736                    continue;
4737                }
4738
4739                if (DEBUG_INTENT_MATCHING) {
4740                    Log.v(TAG, "Specific #" + i + ": " + sintent);
4741                }
4742
4743                String action = sintent.getAction();
4744                if (resultsAction != null && resultsAction.equals(action)) {
4745                    // If this action was explicitly requested, then don't
4746                    // remove things that have it.
4747                    action = null;
4748                }
4749
4750                ResolveInfo ri = null;
4751                ActivityInfo ai = null;
4752
4753                ComponentName comp = sintent.getComponent();
4754                if (comp == null) {
4755                    ri = resolveIntent(
4756                        sintent,
4757                        specificTypes != null ? specificTypes[i] : null,
4758                            flags, userId);
4759                    if (ri == null) {
4760                        continue;
4761                    }
4762                    if (ri == mResolveInfo) {
4763                        // ACK!  Must do something better with this.
4764                    }
4765                    ai = ri.activityInfo;
4766                    comp = new ComponentName(ai.applicationInfo.packageName,
4767                            ai.name);
4768                } else {
4769                    ai = getActivityInfo(comp, flags, userId);
4770                    if (ai == null) {
4771                        continue;
4772                    }
4773                }
4774
4775                // Look for any generic query activities that are duplicates
4776                // of this specific one, and remove them from the results.
4777                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
4778                N = results.size();
4779                int j;
4780                for (j=specificsPos; j<N; j++) {
4781                    ResolveInfo sri = results.get(j);
4782                    if ((sri.activityInfo.name.equals(comp.getClassName())
4783                            && sri.activityInfo.applicationInfo.packageName.equals(
4784                                    comp.getPackageName()))
4785                        || (action != null && sri.filter.matchAction(action))) {
4786                        results.remove(j);
4787                        if (DEBUG_INTENT_MATCHING) Log.v(
4788                            TAG, "Removing duplicate item from " + j
4789                            + " due to specific " + specificsPos);
4790                        if (ri == null) {
4791                            ri = sri;
4792                        }
4793                        j--;
4794                        N--;
4795                    }
4796                }
4797
4798                // Add this specific item to its proper place.
4799                if (ri == null) {
4800                    ri = new ResolveInfo();
4801                    ri.activityInfo = ai;
4802                }
4803                results.add(specificsPos, ri);
4804                ri.specificIndex = i;
4805                specificsPos++;
4806            }
4807        }
4808
4809        // Now we go through the remaining generic results and remove any
4810        // duplicate actions that are found here.
4811        N = results.size();
4812        for (int i=specificsPos; i<N-1; i++) {
4813            final ResolveInfo rii = results.get(i);
4814            if (rii.filter == null) {
4815                continue;
4816            }
4817
4818            // Iterate over all of the actions of this result's intent
4819            // filter...  typically this should be just one.
4820            final Iterator<String> it = rii.filter.actionsIterator();
4821            if (it == null) {
4822                continue;
4823            }
4824            while (it.hasNext()) {
4825                final String action = it.next();
4826                if (resultsAction != null && resultsAction.equals(action)) {
4827                    // If this action was explicitly requested, then don't
4828                    // remove things that have it.
4829                    continue;
4830                }
4831                for (int j=i+1; j<N; j++) {
4832                    final ResolveInfo rij = results.get(j);
4833                    if (rij.filter != null && rij.filter.hasAction(action)) {
4834                        results.remove(j);
4835                        if (DEBUG_INTENT_MATCHING) Log.v(
4836                            TAG, "Removing duplicate item from " + j
4837                            + " due to action " + action + " at " + i);
4838                        j--;
4839                        N--;
4840                    }
4841                }
4842            }
4843
4844            // If the caller didn't request filter information, drop it now
4845            // so we don't have to marshall/unmarshall it.
4846            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4847                rii.filter = null;
4848            }
4849        }
4850
4851        // Filter out the caller activity if so requested.
4852        if (caller != null) {
4853            N = results.size();
4854            for (int i=0; i<N; i++) {
4855                ActivityInfo ainfo = results.get(i).activityInfo;
4856                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
4857                        && caller.getClassName().equals(ainfo.name)) {
4858                    results.remove(i);
4859                    break;
4860                }
4861            }
4862        }
4863
4864        // If the caller didn't request filter information,
4865        // drop them now so we don't have to
4866        // marshall/unmarshall it.
4867        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4868            N = results.size();
4869            for (int i=0; i<N; i++) {
4870                results.get(i).filter = null;
4871            }
4872        }
4873
4874        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
4875        return results;
4876    }
4877
4878    @Override
4879    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
4880            int userId) {
4881        if (!sUserManager.exists(userId)) return Collections.emptyList();
4882        ComponentName comp = intent.getComponent();
4883        if (comp == null) {
4884            if (intent.getSelector() != null) {
4885                intent = intent.getSelector();
4886                comp = intent.getComponent();
4887            }
4888        }
4889        if (comp != null) {
4890            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4891            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
4892            if (ai != null) {
4893                ResolveInfo ri = new ResolveInfo();
4894                ri.activityInfo = ai;
4895                list.add(ri);
4896            }
4897            return list;
4898        }
4899
4900        // reader
4901        synchronized (mPackages) {
4902            String pkgName = intent.getPackage();
4903            if (pkgName == null) {
4904                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
4905            }
4906            final PackageParser.Package pkg = mPackages.get(pkgName);
4907            if (pkg != null) {
4908                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
4909                        userId);
4910            }
4911            return null;
4912        }
4913    }
4914
4915    @Override
4916    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
4917        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
4918        if (!sUserManager.exists(userId)) return null;
4919        if (query != null) {
4920            if (query.size() >= 1) {
4921                // If there is more than one service with the same priority,
4922                // just arbitrarily pick the first one.
4923                return query.get(0);
4924            }
4925        }
4926        return null;
4927    }
4928
4929    @Override
4930    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
4931            int userId) {
4932        if (!sUserManager.exists(userId)) return Collections.emptyList();
4933        ComponentName comp = intent.getComponent();
4934        if (comp == null) {
4935            if (intent.getSelector() != null) {
4936                intent = intent.getSelector();
4937                comp = intent.getComponent();
4938            }
4939        }
4940        if (comp != null) {
4941            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4942            final ServiceInfo si = getServiceInfo(comp, flags, userId);
4943            if (si != null) {
4944                final ResolveInfo ri = new ResolveInfo();
4945                ri.serviceInfo = si;
4946                list.add(ri);
4947            }
4948            return list;
4949        }
4950
4951        // reader
4952        synchronized (mPackages) {
4953            String pkgName = intent.getPackage();
4954            if (pkgName == null) {
4955                return mServices.queryIntent(intent, resolvedType, flags, userId);
4956            }
4957            final PackageParser.Package pkg = mPackages.get(pkgName);
4958            if (pkg != null) {
4959                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
4960                        userId);
4961            }
4962            return null;
4963        }
4964    }
4965
4966    @Override
4967    public List<ResolveInfo> queryIntentContentProviders(
4968            Intent intent, String resolvedType, int flags, int userId) {
4969        if (!sUserManager.exists(userId)) return Collections.emptyList();
4970        ComponentName comp = intent.getComponent();
4971        if (comp == null) {
4972            if (intent.getSelector() != null) {
4973                intent = intent.getSelector();
4974                comp = intent.getComponent();
4975            }
4976        }
4977        if (comp != null) {
4978            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4979            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
4980            if (pi != null) {
4981                final ResolveInfo ri = new ResolveInfo();
4982                ri.providerInfo = pi;
4983                list.add(ri);
4984            }
4985            return list;
4986        }
4987
4988        // reader
4989        synchronized (mPackages) {
4990            String pkgName = intent.getPackage();
4991            if (pkgName == null) {
4992                return mProviders.queryIntent(intent, resolvedType, flags, userId);
4993            }
4994            final PackageParser.Package pkg = mPackages.get(pkgName);
4995            if (pkg != null) {
4996                return mProviders.queryIntentForPackage(
4997                        intent, resolvedType, flags, pkg.providers, userId);
4998            }
4999            return null;
5000        }
5001    }
5002
5003    @Override
5004    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5005        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5006
5007        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5008
5009        // writer
5010        synchronized (mPackages) {
5011            ArrayList<PackageInfo> list;
5012            if (listUninstalled) {
5013                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5014                for (PackageSetting ps : mSettings.mPackages.values()) {
5015                    PackageInfo pi;
5016                    if (ps.pkg != null) {
5017                        pi = generatePackageInfo(ps.pkg, flags, userId);
5018                    } else {
5019                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5020                    }
5021                    if (pi != null) {
5022                        list.add(pi);
5023                    }
5024                }
5025            } else {
5026                list = new ArrayList<PackageInfo>(mPackages.size());
5027                for (PackageParser.Package p : mPackages.values()) {
5028                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5029                    if (pi != null) {
5030                        list.add(pi);
5031                    }
5032                }
5033            }
5034
5035            return new ParceledListSlice<PackageInfo>(list);
5036        }
5037    }
5038
5039    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5040            String[] permissions, boolean[] tmp, int flags, int userId) {
5041        int numMatch = 0;
5042        final PermissionsState permissionsState = ps.getPermissionsState();
5043        for (int i=0; i<permissions.length; i++) {
5044            final String permission = permissions[i];
5045            if (permissionsState.hasPermission(permission, userId)) {
5046                tmp[i] = true;
5047                numMatch++;
5048            } else {
5049                tmp[i] = false;
5050            }
5051        }
5052        if (numMatch == 0) {
5053            return;
5054        }
5055        PackageInfo pi;
5056        if (ps.pkg != null) {
5057            pi = generatePackageInfo(ps.pkg, flags, userId);
5058        } else {
5059            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5060        }
5061        // The above might return null in cases of uninstalled apps or install-state
5062        // skew across users/profiles.
5063        if (pi != null) {
5064            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5065                if (numMatch == permissions.length) {
5066                    pi.requestedPermissions = permissions;
5067                } else {
5068                    pi.requestedPermissions = new String[numMatch];
5069                    numMatch = 0;
5070                    for (int i=0; i<permissions.length; i++) {
5071                        if (tmp[i]) {
5072                            pi.requestedPermissions[numMatch] = permissions[i];
5073                            numMatch++;
5074                        }
5075                    }
5076                }
5077            }
5078            list.add(pi);
5079        }
5080    }
5081
5082    @Override
5083    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5084            String[] permissions, int flags, int userId) {
5085        if (!sUserManager.exists(userId)) return null;
5086        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5087
5088        // writer
5089        synchronized (mPackages) {
5090            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5091            boolean[] tmpBools = new boolean[permissions.length];
5092            if (listUninstalled) {
5093                for (PackageSetting ps : mSettings.mPackages.values()) {
5094                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5095                }
5096            } else {
5097                for (PackageParser.Package pkg : mPackages.values()) {
5098                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5099                    if (ps != null) {
5100                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5101                                userId);
5102                    }
5103                }
5104            }
5105
5106            return new ParceledListSlice<PackageInfo>(list);
5107        }
5108    }
5109
5110    @Override
5111    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5112        if (!sUserManager.exists(userId)) return null;
5113        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5114
5115        // writer
5116        synchronized (mPackages) {
5117            ArrayList<ApplicationInfo> list;
5118            if (listUninstalled) {
5119                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5120                for (PackageSetting ps : mSettings.mPackages.values()) {
5121                    ApplicationInfo ai;
5122                    if (ps.pkg != null) {
5123                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5124                                ps.readUserState(userId), userId);
5125                    } else {
5126                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5127                    }
5128                    if (ai != null) {
5129                        list.add(ai);
5130                    }
5131                }
5132            } else {
5133                list = new ArrayList<ApplicationInfo>(mPackages.size());
5134                for (PackageParser.Package p : mPackages.values()) {
5135                    if (p.mExtras != null) {
5136                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5137                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5138                        if (ai != null) {
5139                            list.add(ai);
5140                        }
5141                    }
5142                }
5143            }
5144
5145            return new ParceledListSlice<ApplicationInfo>(list);
5146        }
5147    }
5148
5149    public List<ApplicationInfo> getPersistentApplications(int flags) {
5150        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5151
5152        // reader
5153        synchronized (mPackages) {
5154            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5155            final int userId = UserHandle.getCallingUserId();
5156            while (i.hasNext()) {
5157                final PackageParser.Package p = i.next();
5158                if (p.applicationInfo != null
5159                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5160                        && (!mSafeMode || isSystemApp(p))) {
5161                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5162                    if (ps != null) {
5163                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5164                                ps.readUserState(userId), userId);
5165                        if (ai != null) {
5166                            finalList.add(ai);
5167                        }
5168                    }
5169                }
5170            }
5171        }
5172
5173        return finalList;
5174    }
5175
5176    @Override
5177    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5178        if (!sUserManager.exists(userId)) return null;
5179        // reader
5180        synchronized (mPackages) {
5181            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5182            PackageSetting ps = provider != null
5183                    ? mSettings.mPackages.get(provider.owner.packageName)
5184                    : null;
5185            return ps != null
5186                    && mSettings.isEnabledLPr(provider.info, flags, userId)
5187                    && (!mSafeMode || (provider.info.applicationInfo.flags
5188                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5189                    ? PackageParser.generateProviderInfo(provider, flags,
5190                            ps.readUserState(userId), userId)
5191                    : null;
5192        }
5193    }
5194
5195    /**
5196     * @deprecated
5197     */
5198    @Deprecated
5199    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5200        // reader
5201        synchronized (mPackages) {
5202            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5203                    .entrySet().iterator();
5204            final int userId = UserHandle.getCallingUserId();
5205            while (i.hasNext()) {
5206                Map.Entry<String, PackageParser.Provider> entry = i.next();
5207                PackageParser.Provider p = entry.getValue();
5208                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5209
5210                if (ps != null && p.syncable
5211                        && (!mSafeMode || (p.info.applicationInfo.flags
5212                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5213                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5214                            ps.readUserState(userId), userId);
5215                    if (info != null) {
5216                        outNames.add(entry.getKey());
5217                        outInfo.add(info);
5218                    }
5219                }
5220            }
5221        }
5222    }
5223
5224    @Override
5225    public List<ProviderInfo> queryContentProviders(String processName,
5226            int uid, int flags) {
5227        ArrayList<ProviderInfo> finalList = null;
5228        // reader
5229        synchronized (mPackages) {
5230            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5231            final int userId = processName != null ?
5232                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
5233            while (i.hasNext()) {
5234                final PackageParser.Provider p = i.next();
5235                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5236                if (ps != null && p.info.authority != null
5237                        && (processName == null
5238                                || (p.info.processName.equals(processName)
5239                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5240                        && mSettings.isEnabledLPr(p.info, flags, userId)
5241                        && (!mSafeMode
5242                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5243                    if (finalList == null) {
5244                        finalList = new ArrayList<ProviderInfo>(3);
5245                    }
5246                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5247                            ps.readUserState(userId), userId);
5248                    if (info != null) {
5249                        finalList.add(info);
5250                    }
5251                }
5252            }
5253        }
5254
5255        if (finalList != null) {
5256            Collections.sort(finalList, mProviderInitOrderSorter);
5257        }
5258
5259        return finalList;
5260    }
5261
5262    @Override
5263    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
5264            int flags) {
5265        // reader
5266        synchronized (mPackages) {
5267            final PackageParser.Instrumentation i = mInstrumentation.get(name);
5268            return PackageParser.generateInstrumentationInfo(i, flags);
5269        }
5270    }
5271
5272    @Override
5273    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
5274            int flags) {
5275        ArrayList<InstrumentationInfo> finalList =
5276            new ArrayList<InstrumentationInfo>();
5277
5278        // reader
5279        synchronized (mPackages) {
5280            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
5281            while (i.hasNext()) {
5282                final PackageParser.Instrumentation p = i.next();
5283                if (targetPackage == null
5284                        || targetPackage.equals(p.info.targetPackage)) {
5285                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
5286                            flags);
5287                    if (ii != null) {
5288                        finalList.add(ii);
5289                    }
5290                }
5291            }
5292        }
5293
5294        return finalList;
5295    }
5296
5297    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
5298        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
5299        if (overlays == null) {
5300            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
5301            return;
5302        }
5303        for (PackageParser.Package opkg : overlays.values()) {
5304            // Not much to do if idmap fails: we already logged the error
5305            // and we certainly don't want to abort installation of pkg simply
5306            // because an overlay didn't fit properly. For these reasons,
5307            // ignore the return value of createIdmapForPackagePairLI.
5308            createIdmapForPackagePairLI(pkg, opkg);
5309        }
5310    }
5311
5312    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
5313            PackageParser.Package opkg) {
5314        if (!opkg.mTrustedOverlay) {
5315            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
5316                    opkg.baseCodePath + ": overlay not trusted");
5317            return false;
5318        }
5319        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
5320        if (overlaySet == null) {
5321            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
5322                    opkg.baseCodePath + " but target package has no known overlays");
5323            return false;
5324        }
5325        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
5326        // TODO: generate idmap for split APKs
5327        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
5328            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
5329                    + opkg.baseCodePath);
5330            return false;
5331        }
5332        PackageParser.Package[] overlayArray =
5333            overlaySet.values().toArray(new PackageParser.Package[0]);
5334        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
5335            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
5336                return p1.mOverlayPriority - p2.mOverlayPriority;
5337            }
5338        };
5339        Arrays.sort(overlayArray, cmp);
5340
5341        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5342        int i = 0;
5343        for (PackageParser.Package p : overlayArray) {
5344            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5345        }
5346        return true;
5347    }
5348
5349    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5350        final File[] files = dir.listFiles();
5351        if (ArrayUtils.isEmpty(files)) {
5352            Log.d(TAG, "No files in app dir " + dir);
5353            return;
5354        }
5355
5356        if (DEBUG_PACKAGE_SCANNING) {
5357            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
5358                    + " flags=0x" + Integer.toHexString(parseFlags));
5359        }
5360
5361        for (File file : files) {
5362            final boolean isPackage = (isApkFile(file) || file.isDirectory())
5363                    && !PackageInstallerService.isStageName(file.getName());
5364            if (!isPackage) {
5365                // Ignore entries which are not packages
5366                continue;
5367            }
5368            try {
5369                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
5370                        scanFlags, currentTime, null);
5371            } catch (PackageManagerException e) {
5372                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
5373
5374                // Delete invalid userdata apps
5375                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
5376                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
5377                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
5378                    if (file.isDirectory()) {
5379                        mInstaller.rmPackageDir(file.getAbsolutePath());
5380                    } else {
5381                        file.delete();
5382                    }
5383                }
5384            }
5385        }
5386    }
5387
5388    private static File getSettingsProblemFile() {
5389        File dataDir = Environment.getDataDirectory();
5390        File systemDir = new File(dataDir, "system");
5391        File fname = new File(systemDir, "uiderrors.txt");
5392        return fname;
5393    }
5394
5395    static void reportSettingsProblem(int priority, String msg) {
5396        logCriticalInfo(priority, msg);
5397    }
5398
5399    static void logCriticalInfo(int priority, String msg) {
5400        Slog.println(priority, TAG, msg);
5401        EventLogTags.writePmCriticalInfo(msg);
5402        try {
5403            File fname = getSettingsProblemFile();
5404            FileOutputStream out = new FileOutputStream(fname, true);
5405            PrintWriter pw = new FastPrintWriter(out);
5406            SimpleDateFormat formatter = new SimpleDateFormat();
5407            String dateString = formatter.format(new Date(System.currentTimeMillis()));
5408            pw.println(dateString + ": " + msg);
5409            pw.close();
5410            FileUtils.setPermissions(
5411                    fname.toString(),
5412                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5413                    -1, -1);
5414        } catch (java.io.IOException e) {
5415        }
5416    }
5417
5418    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5419            PackageParser.Package pkg, File srcFile, int parseFlags)
5420            throws PackageManagerException {
5421        if (ps != null
5422                && ps.codePath.equals(srcFile)
5423                && ps.timeStamp == srcFile.lastModified()
5424                && !isCompatSignatureUpdateNeeded(pkg)
5425                && !isRecoverSignatureUpdateNeeded(pkg)) {
5426            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5427            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5428            ArraySet<PublicKey> signingKs;
5429            synchronized (mPackages) {
5430                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
5431            }
5432            if (ps.signatures.mSignatures != null
5433                    && ps.signatures.mSignatures.length != 0
5434                    && signingKs != null) {
5435                // Optimization: reuse the existing cached certificates
5436                // if the package appears to be unchanged.
5437                pkg.mSignatures = ps.signatures.mSignatures;
5438                pkg.mSigningKeys = signingKs;
5439                return;
5440            }
5441
5442            Slog.w(TAG, "PackageSetting for " + ps.name
5443                    + " is missing signatures.  Collecting certs again to recover them.");
5444        } else {
5445            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
5446        }
5447
5448        try {
5449            pp.collectCertificates(pkg, parseFlags);
5450            pp.collectManifestDigest(pkg);
5451        } catch (PackageParserException e) {
5452            throw PackageManagerException.from(e);
5453        }
5454    }
5455
5456    /*
5457     *  Scan a package and return the newly parsed package.
5458     *  Returns null in case of errors and the error code is stored in mLastScanError
5459     */
5460    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
5461            long currentTime, UserHandle user) throws PackageManagerException {
5462        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
5463        parseFlags |= mDefParseFlags;
5464        PackageParser pp = new PackageParser();
5465        pp.setSeparateProcesses(mSeparateProcesses);
5466        pp.setOnlyCoreApps(mOnlyCore);
5467        pp.setDisplayMetrics(mMetrics);
5468
5469        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
5470            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
5471        }
5472
5473        final PackageParser.Package pkg;
5474        try {
5475            pkg = pp.parsePackage(scanFile, parseFlags);
5476        } catch (PackageParserException e) {
5477            throw PackageManagerException.from(e);
5478        }
5479
5480        PackageSetting ps = null;
5481        PackageSetting updatedPkg;
5482        // reader
5483        synchronized (mPackages) {
5484            // Look to see if we already know about this package.
5485            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
5486            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
5487                // This package has been renamed to its original name.  Let's
5488                // use that.
5489                ps = mSettings.peekPackageLPr(oldName);
5490            }
5491            // If there was no original package, see one for the real package name.
5492            if (ps == null) {
5493                ps = mSettings.peekPackageLPr(pkg.packageName);
5494            }
5495            // Check to see if this package could be hiding/updating a system
5496            // package.  Must look for it either under the original or real
5497            // package name depending on our state.
5498            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
5499            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
5500        }
5501        boolean updatedPkgBetter = false;
5502        // First check if this is a system package that may involve an update
5503        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5504            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
5505            // it needs to drop FLAG_PRIVILEGED.
5506            if (locationIsPrivileged(scanFile)) {
5507                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5508            } else {
5509                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5510            }
5511
5512            if (ps != null && !ps.codePath.equals(scanFile)) {
5513                // The path has changed from what was last scanned...  check the
5514                // version of the new path against what we have stored to determine
5515                // what to do.
5516                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
5517                if (pkg.mVersionCode <= ps.versionCode) {
5518                    // The system package has been updated and the code path does not match
5519                    // Ignore entry. Skip it.
5520                    Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5521                            + " ignored: updated version " + ps.versionCode
5522                            + " better than this " + pkg.mVersionCode);
5523                    if (!updatedPkg.codePath.equals(scanFile)) {
5524                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5525                                + ps.name + " changing from " + updatedPkg.codePathString
5526                                + " to " + scanFile);
5527                        updatedPkg.codePath = scanFile;
5528                        updatedPkg.codePathString = scanFile.toString();
5529                        updatedPkg.resourcePath = scanFile;
5530                        updatedPkg.resourcePathString = scanFile.toString();
5531                    }
5532                    updatedPkg.pkg = pkg;
5533                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null);
5534                } else {
5535                    // The current app on the system partition is better than
5536                    // what we have updated to on the data partition; switch
5537                    // back to the system partition version.
5538                    // At this point, its safely assumed that package installation for
5539                    // apps in system partition will go through. If not there won't be a working
5540                    // version of the app
5541                    // writer
5542                    synchronized (mPackages) {
5543                        // Just remove the loaded entries from package lists.
5544                        mPackages.remove(ps.name);
5545                    }
5546
5547                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5548                            + " reverting from " + ps.codePathString
5549                            + ": new version " + pkg.mVersionCode
5550                            + " better than installed " + ps.versionCode);
5551
5552                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5553                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5554                    synchronized (mInstallLock) {
5555                        args.cleanUpResourcesLI();
5556                    }
5557                    synchronized (mPackages) {
5558                        mSettings.enableSystemPackageLPw(ps.name);
5559                    }
5560                    updatedPkgBetter = true;
5561                }
5562            }
5563        }
5564
5565        if (updatedPkg != null) {
5566            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5567            // initially
5568            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5569
5570            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5571            // flag set initially
5572            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5573                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5574            }
5575        }
5576
5577        // Verify certificates against what was last scanned
5578        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5579
5580        /*
5581         * A new system app appeared, but we already had a non-system one of the
5582         * same name installed earlier.
5583         */
5584        boolean shouldHideSystemApp = false;
5585        if (updatedPkg == null && ps != null
5586                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5587            /*
5588             * Check to make sure the signatures match first. If they don't,
5589             * wipe the installed application and its data.
5590             */
5591            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5592                    != PackageManager.SIGNATURE_MATCH) {
5593                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5594                        + " signatures don't match existing userdata copy; removing");
5595                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5596                ps = null;
5597            } else {
5598                /*
5599                 * If the newly-added system app is an older version than the
5600                 * already installed version, hide it. It will be scanned later
5601                 * and re-added like an update.
5602                 */
5603                if (pkg.mVersionCode <= ps.versionCode) {
5604                    shouldHideSystemApp = true;
5605                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5606                            + " but new version " + pkg.mVersionCode + " better than installed "
5607                            + ps.versionCode + "; hiding system");
5608                } else {
5609                    /*
5610                     * The newly found system app is a newer version that the
5611                     * one previously installed. Simply remove the
5612                     * already-installed application and replace it with our own
5613                     * while keeping the application data.
5614                     */
5615                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5616                            + " reverting from " + ps.codePathString + ": new version "
5617                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5618                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5619                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5620                    synchronized (mInstallLock) {
5621                        args.cleanUpResourcesLI();
5622                    }
5623                }
5624            }
5625        }
5626
5627        // The apk is forward locked (not public) if its code and resources
5628        // are kept in different files. (except for app in either system or
5629        // vendor path).
5630        // TODO grab this value from PackageSettings
5631        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5632            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5633                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5634            }
5635        }
5636
5637        // TODO: extend to support forward-locked splits
5638        String resourcePath = null;
5639        String baseResourcePath = null;
5640        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5641            if (ps != null && ps.resourcePathString != null) {
5642                resourcePath = ps.resourcePathString;
5643                baseResourcePath = ps.resourcePathString;
5644            } else {
5645                // Should not happen at all. Just log an error.
5646                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5647            }
5648        } else {
5649            resourcePath = pkg.codePath;
5650            baseResourcePath = pkg.baseCodePath;
5651        }
5652
5653        // Set application objects path explicitly.
5654        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
5655        pkg.applicationInfo.setCodePath(pkg.codePath);
5656        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5657        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5658        pkg.applicationInfo.setResourcePath(resourcePath);
5659        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5660        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5661
5662        // Note that we invoke the following method only if we are about to unpack an application
5663        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5664                | SCAN_UPDATE_SIGNATURE, currentTime, user);
5665
5666        /*
5667         * If the system app should be overridden by a previously installed
5668         * data, hide the system app now and let the /data/app scan pick it up
5669         * again.
5670         */
5671        if (shouldHideSystemApp) {
5672            synchronized (mPackages) {
5673                /*
5674                 * We have to grant systems permissions before we hide, because
5675                 * grantPermissions will assume the package update is trying to
5676                 * expand its permissions.
5677                 */
5678                grantPermissionsLPw(pkg, true, pkg.packageName);
5679                mSettings.disableSystemPackageLPw(pkg.packageName);
5680            }
5681        }
5682
5683        return scannedPkg;
5684    }
5685
5686    private static String fixProcessName(String defProcessName,
5687            String processName, int uid) {
5688        if (processName == null) {
5689            return defProcessName;
5690        }
5691        return processName;
5692    }
5693
5694    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
5695            throws PackageManagerException {
5696        if (pkgSetting.signatures.mSignatures != null) {
5697            // Already existing package. Make sure signatures match
5698            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
5699                    == PackageManager.SIGNATURE_MATCH;
5700            if (!match) {
5701                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
5702                        == PackageManager.SIGNATURE_MATCH;
5703            }
5704            if (!match) {
5705                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
5706                        == PackageManager.SIGNATURE_MATCH;
5707            }
5708            if (!match) {
5709                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5710                        + pkg.packageName + " signatures do not match the "
5711                        + "previously installed version; ignoring!");
5712            }
5713        }
5714
5715        // Check for shared user signatures
5716        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
5717            // Already existing package. Make sure signatures match
5718            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5719                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
5720            if (!match) {
5721                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
5722                        == PackageManager.SIGNATURE_MATCH;
5723            }
5724            if (!match) {
5725                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
5726                        == PackageManager.SIGNATURE_MATCH;
5727            }
5728            if (!match) {
5729                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
5730                        "Package " + pkg.packageName
5731                        + " has no signatures that match those in shared user "
5732                        + pkgSetting.sharedUser.name + "; ignoring!");
5733            }
5734        }
5735    }
5736
5737    /**
5738     * Enforces that only the system UID or root's UID can call a method exposed
5739     * via Binder.
5740     *
5741     * @param message used as message if SecurityException is thrown
5742     * @throws SecurityException if the caller is not system or root
5743     */
5744    private static final void enforceSystemOrRoot(String message) {
5745        final int uid = Binder.getCallingUid();
5746        if (uid != Process.SYSTEM_UID && uid != 0) {
5747            throw new SecurityException(message);
5748        }
5749    }
5750
5751    @Override
5752    public void performBootDexOpt() {
5753        enforceSystemOrRoot("Only the system can request dexopt be performed");
5754
5755        // Before everything else, see whether we need to fstrim.
5756        try {
5757            IMountService ms = PackageHelper.getMountService();
5758            if (ms != null) {
5759                final boolean isUpgrade = isUpgrade();
5760                boolean doTrim = isUpgrade;
5761                if (doTrim) {
5762                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
5763                } else {
5764                    final long interval = android.provider.Settings.Global.getLong(
5765                            mContext.getContentResolver(),
5766                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
5767                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
5768                    if (interval > 0) {
5769                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
5770                        if (timeSinceLast > interval) {
5771                            doTrim = true;
5772                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
5773                                    + "; running immediately");
5774                        }
5775                    }
5776                }
5777                if (doTrim) {
5778                    if (!isFirstBoot()) {
5779                        try {
5780                            ActivityManagerNative.getDefault().showBootMessage(
5781                                    mContext.getResources().getString(
5782                                            R.string.android_upgrading_fstrim), true);
5783                        } catch (RemoteException e) {
5784                        }
5785                    }
5786                    ms.runMaintenance();
5787                }
5788            } else {
5789                Slog.e(TAG, "Mount service unavailable!");
5790            }
5791        } catch (RemoteException e) {
5792            // Can't happen; MountService is local
5793        }
5794
5795        final ArraySet<PackageParser.Package> pkgs;
5796        synchronized (mPackages) {
5797            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
5798        }
5799
5800        if (pkgs != null) {
5801            // Sort apps by importance for dexopt ordering. Important apps are given more priority
5802            // in case the device runs out of space.
5803            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
5804            // Give priority to core apps.
5805            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5806                PackageParser.Package pkg = it.next();
5807                if (pkg.coreApp) {
5808                    if (DEBUG_DEXOPT) {
5809                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
5810                    }
5811                    sortedPkgs.add(pkg);
5812                    it.remove();
5813                }
5814            }
5815            // Give priority to system apps that listen for pre boot complete.
5816            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
5817            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
5818            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5819                PackageParser.Package pkg = it.next();
5820                if (pkgNames.contains(pkg.packageName)) {
5821                    if (DEBUG_DEXOPT) {
5822                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
5823                    }
5824                    sortedPkgs.add(pkg);
5825                    it.remove();
5826                }
5827            }
5828            // Give priority to system apps.
5829            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5830                PackageParser.Package pkg = it.next();
5831                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
5832                    if (DEBUG_DEXOPT) {
5833                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
5834                    }
5835                    sortedPkgs.add(pkg);
5836                    it.remove();
5837                }
5838            }
5839            // Give priority to updated system apps.
5840            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5841                PackageParser.Package pkg = it.next();
5842                if (pkg.isUpdatedSystemApp()) {
5843                    if (DEBUG_DEXOPT) {
5844                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
5845                    }
5846                    sortedPkgs.add(pkg);
5847                    it.remove();
5848                }
5849            }
5850            // Give priority to apps that listen for boot complete.
5851            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
5852            pkgNames = getPackageNamesForIntent(intent);
5853            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5854                PackageParser.Package pkg = it.next();
5855                if (pkgNames.contains(pkg.packageName)) {
5856                    if (DEBUG_DEXOPT) {
5857                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
5858                    }
5859                    sortedPkgs.add(pkg);
5860                    it.remove();
5861                }
5862            }
5863            // Filter out packages that aren't recently used.
5864            filterRecentlyUsedApps(pkgs);
5865            // Add all remaining apps.
5866            for (PackageParser.Package pkg : pkgs) {
5867                if (DEBUG_DEXOPT) {
5868                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
5869                }
5870                sortedPkgs.add(pkg);
5871            }
5872
5873            // If we want to be lazy, filter everything that wasn't recently used.
5874            if (mLazyDexOpt) {
5875                filterRecentlyUsedApps(sortedPkgs);
5876            }
5877
5878            int i = 0;
5879            int total = sortedPkgs.size();
5880            File dataDir = Environment.getDataDirectory();
5881            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
5882            if (lowThreshold == 0) {
5883                throw new IllegalStateException("Invalid low memory threshold");
5884            }
5885            for (PackageParser.Package pkg : sortedPkgs) {
5886                long usableSpace = dataDir.getUsableSpace();
5887                if (usableSpace < lowThreshold) {
5888                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
5889                    break;
5890                }
5891                performBootDexOpt(pkg, ++i, total);
5892            }
5893        }
5894    }
5895
5896    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
5897        // Filter out packages that aren't recently used.
5898        //
5899        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
5900        // should do a full dexopt.
5901        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
5902            int total = pkgs.size();
5903            int skipped = 0;
5904            long now = System.currentTimeMillis();
5905            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
5906                PackageParser.Package pkg = i.next();
5907                long then = pkg.mLastPackageUsageTimeInMills;
5908                if (then + mDexOptLRUThresholdInMills < now) {
5909                    if (DEBUG_DEXOPT) {
5910                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
5911                              ((then == 0) ? "never" : new Date(then)));
5912                    }
5913                    i.remove();
5914                    skipped++;
5915                }
5916            }
5917            if (DEBUG_DEXOPT) {
5918                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
5919            }
5920        }
5921    }
5922
5923    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
5924        List<ResolveInfo> ris = null;
5925        try {
5926            ris = AppGlobals.getPackageManager().queryIntentReceivers(
5927                    intent, null, 0, UserHandle.USER_OWNER);
5928        } catch (RemoteException e) {
5929        }
5930        ArraySet<String> pkgNames = new ArraySet<String>();
5931        if (ris != null) {
5932            for (ResolveInfo ri : ris) {
5933                pkgNames.add(ri.activityInfo.packageName);
5934            }
5935        }
5936        return pkgNames;
5937    }
5938
5939    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
5940        if (DEBUG_DEXOPT) {
5941            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
5942        }
5943        if (!isFirstBoot()) {
5944            try {
5945                ActivityManagerNative.getDefault().showBootMessage(
5946                        mContext.getResources().getString(R.string.android_upgrading_apk,
5947                                curr, total), true);
5948            } catch (RemoteException e) {
5949            }
5950        }
5951        PackageParser.Package p = pkg;
5952        synchronized (mInstallLock) {
5953            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
5954                    false /* force dex */, false /* defer */, true /* include dependencies */);
5955        }
5956    }
5957
5958    @Override
5959    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
5960        return performDexOpt(packageName, instructionSet, false);
5961    }
5962
5963    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
5964        boolean dexopt = mLazyDexOpt || backgroundDexopt;
5965        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
5966        if (!dexopt && !updateUsage) {
5967            // We aren't going to dexopt or update usage, so bail early.
5968            return false;
5969        }
5970        PackageParser.Package p;
5971        final String targetInstructionSet;
5972        synchronized (mPackages) {
5973            p = mPackages.get(packageName);
5974            if (p == null) {
5975                return false;
5976            }
5977            if (updateUsage) {
5978                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
5979            }
5980            mPackageUsage.write(false);
5981            if (!dexopt) {
5982                // We aren't going to dexopt, so bail early.
5983                return false;
5984            }
5985
5986            targetInstructionSet = instructionSet != null ? instructionSet :
5987                    getPrimaryInstructionSet(p.applicationInfo);
5988            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
5989                return false;
5990            }
5991        }
5992
5993        synchronized (mInstallLock) {
5994            final String[] instructionSets = new String[] { targetInstructionSet };
5995            int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
5996                    false /* forceDex */, false /* defer */, true /* inclDependencies */);
5997            return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
5998        }
5999    }
6000
6001    public ArraySet<String> getPackagesThatNeedDexOpt() {
6002        ArraySet<String> pkgs = null;
6003        synchronized (mPackages) {
6004            for (PackageParser.Package p : mPackages.values()) {
6005                if (DEBUG_DEXOPT) {
6006                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6007                }
6008                if (!p.mDexOptPerformed.isEmpty()) {
6009                    continue;
6010                }
6011                if (pkgs == null) {
6012                    pkgs = new ArraySet<String>();
6013                }
6014                pkgs.add(p.packageName);
6015            }
6016        }
6017        return pkgs;
6018    }
6019
6020    public void shutdown() {
6021        mPackageUsage.write(true);
6022    }
6023
6024    @Override
6025    public void forceDexOpt(String packageName) {
6026        enforceSystemOrRoot("forceDexOpt");
6027
6028        PackageParser.Package pkg;
6029        synchronized (mPackages) {
6030            pkg = mPackages.get(packageName);
6031            if (pkg == null) {
6032                throw new IllegalArgumentException("Missing package: " + packageName);
6033            }
6034        }
6035
6036        synchronized (mInstallLock) {
6037            final String[] instructionSets = new String[] {
6038                    getPrimaryInstructionSet(pkg.applicationInfo) };
6039            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6040                    true /*forceDex*/, false /* defer */, true /* inclDependencies */);
6041            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6042                throw new IllegalStateException("Failed to dexopt: " + res);
6043            }
6044        }
6045    }
6046
6047    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6048        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6049            Slog.w(TAG, "Unable to update from " + oldPkg.name
6050                    + " to " + newPkg.packageName
6051                    + ": old package not in system partition");
6052            return false;
6053        } else if (mPackages.get(oldPkg.name) != null) {
6054            Slog.w(TAG, "Unable to update from " + oldPkg.name
6055                    + " to " + newPkg.packageName
6056                    + ": old package still exists");
6057            return false;
6058        }
6059        return true;
6060    }
6061
6062    private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
6063        int[] users = sUserManager.getUserIds();
6064        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
6065        if (res < 0) {
6066            return res;
6067        }
6068        for (int user : users) {
6069            if (user != 0) {
6070                res = mInstaller.createUserData(volumeUuid, packageName,
6071                        UserHandle.getUid(user, uid), user, seinfo);
6072                if (res < 0) {
6073                    return res;
6074                }
6075            }
6076        }
6077        return res;
6078    }
6079
6080    private int removeDataDirsLI(String volumeUuid, String packageName) {
6081        int[] users = sUserManager.getUserIds();
6082        int res = 0;
6083        for (int user : users) {
6084            int resInner = mInstaller.remove(volumeUuid, packageName, user);
6085            if (resInner < 0) {
6086                res = resInner;
6087            }
6088        }
6089
6090        return res;
6091    }
6092
6093    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6094        int[] users = sUserManager.getUserIds();
6095        int res = 0;
6096        for (int user : users) {
6097            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
6098            if (resInner < 0) {
6099                res = resInner;
6100            }
6101        }
6102        return res;
6103    }
6104
6105    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6106            PackageParser.Package changingLib) {
6107        if (file.path != null) {
6108            usesLibraryFiles.add(file.path);
6109            return;
6110        }
6111        PackageParser.Package p = mPackages.get(file.apk);
6112        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6113            // If we are doing this while in the middle of updating a library apk,
6114            // then we need to make sure to use that new apk for determining the
6115            // dependencies here.  (We haven't yet finished committing the new apk
6116            // to the package manager state.)
6117            if (p == null || p.packageName.equals(changingLib.packageName)) {
6118                p = changingLib;
6119            }
6120        }
6121        if (p != null) {
6122            usesLibraryFiles.addAll(p.getAllCodePaths());
6123        }
6124    }
6125
6126    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6127            PackageParser.Package changingLib) throws PackageManagerException {
6128        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6129            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6130            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6131            for (int i=0; i<N; i++) {
6132                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6133                if (file == null) {
6134                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6135                            "Package " + pkg.packageName + " requires unavailable shared library "
6136                            + pkg.usesLibraries.get(i) + "; failing!");
6137                }
6138                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6139            }
6140            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6141            for (int i=0; i<N; i++) {
6142                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6143                if (file == null) {
6144                    Slog.w(TAG, "Package " + pkg.packageName
6145                            + " desires unavailable shared library "
6146                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6147                } else {
6148                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6149                }
6150            }
6151            N = usesLibraryFiles.size();
6152            if (N > 0) {
6153                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6154            } else {
6155                pkg.usesLibraryFiles = null;
6156            }
6157        }
6158    }
6159
6160    private static boolean hasString(List<String> list, List<String> which) {
6161        if (list == null) {
6162            return false;
6163        }
6164        for (int i=list.size()-1; i>=0; i--) {
6165            for (int j=which.size()-1; j>=0; j--) {
6166                if (which.get(j).equals(list.get(i))) {
6167                    return true;
6168                }
6169            }
6170        }
6171        return false;
6172    }
6173
6174    private void updateAllSharedLibrariesLPw() {
6175        for (PackageParser.Package pkg : mPackages.values()) {
6176            try {
6177                updateSharedLibrariesLPw(pkg, null);
6178            } catch (PackageManagerException e) {
6179                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6180            }
6181        }
6182    }
6183
6184    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6185            PackageParser.Package changingPkg) {
6186        ArrayList<PackageParser.Package> res = null;
6187        for (PackageParser.Package pkg : mPackages.values()) {
6188            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6189                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6190                if (res == null) {
6191                    res = new ArrayList<PackageParser.Package>();
6192                }
6193                res.add(pkg);
6194                try {
6195                    updateSharedLibrariesLPw(pkg, changingPkg);
6196                } catch (PackageManagerException e) {
6197                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6198                }
6199            }
6200        }
6201        return res;
6202    }
6203
6204    /**
6205     * Derive the value of the {@code cpuAbiOverride} based on the provided
6206     * value and an optional stored value from the package settings.
6207     */
6208    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6209        String cpuAbiOverride = null;
6210
6211        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6212            cpuAbiOverride = null;
6213        } else if (abiOverride != null) {
6214            cpuAbiOverride = abiOverride;
6215        } else if (settings != null) {
6216            cpuAbiOverride = settings.cpuAbiOverrideString;
6217        }
6218
6219        return cpuAbiOverride;
6220    }
6221
6222    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6223            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6224        boolean success = false;
6225        try {
6226            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6227                    currentTime, user);
6228            success = true;
6229            return res;
6230        } finally {
6231            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6232                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6233            }
6234        }
6235    }
6236
6237    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6238            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6239        final File scanFile = new File(pkg.codePath);
6240        if (pkg.applicationInfo.getCodePath() == null ||
6241                pkg.applicationInfo.getResourcePath() == null) {
6242            // Bail out. The resource and code paths haven't been set.
6243            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6244                    "Code and resource paths haven't been set correctly");
6245        }
6246
6247        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6248            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6249        } else {
6250            // Only allow system apps to be flagged as core apps.
6251            pkg.coreApp = false;
6252        }
6253
6254        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6255            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6256        }
6257
6258        if (mCustomResolverComponentName != null &&
6259                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6260            setUpCustomResolverActivity(pkg);
6261        }
6262
6263        if (pkg.packageName.equals("android")) {
6264            synchronized (mPackages) {
6265                if (mAndroidApplication != null) {
6266                    Slog.w(TAG, "*************************************************");
6267                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6268                    Slog.w(TAG, " file=" + scanFile);
6269                    Slog.w(TAG, "*************************************************");
6270                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6271                            "Core android package being redefined.  Skipping.");
6272                }
6273
6274                // Set up information for our fall-back user intent resolution activity.
6275                mPlatformPackage = pkg;
6276                pkg.mVersionCode = mSdkVersion;
6277                mAndroidApplication = pkg.applicationInfo;
6278
6279                if (!mResolverReplaced) {
6280                    mResolveActivity.applicationInfo = mAndroidApplication;
6281                    mResolveActivity.name = ResolverActivity.class.getName();
6282                    mResolveActivity.packageName = mAndroidApplication.packageName;
6283                    mResolveActivity.processName = "system:ui";
6284                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6285                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6286                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6287                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6288                    mResolveActivity.exported = true;
6289                    mResolveActivity.enabled = true;
6290                    mResolveInfo.activityInfo = mResolveActivity;
6291                    mResolveInfo.priority = 0;
6292                    mResolveInfo.preferredOrder = 0;
6293                    mResolveInfo.match = 0;
6294                    mResolveComponentName = new ComponentName(
6295                            mAndroidApplication.packageName, mResolveActivity.name);
6296                }
6297            }
6298        }
6299
6300        if (DEBUG_PACKAGE_SCANNING) {
6301            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6302                Log.d(TAG, "Scanning package " + pkg.packageName);
6303        }
6304
6305        if (mPackages.containsKey(pkg.packageName)
6306                || mSharedLibraries.containsKey(pkg.packageName)) {
6307            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6308                    "Application package " + pkg.packageName
6309                    + " already installed.  Skipping duplicate.");
6310        }
6311
6312        // If we're only installing presumed-existing packages, require that the
6313        // scanned APK is both already known and at the path previously established
6314        // for it.  Previously unknown packages we pick up normally, but if we have an
6315        // a priori expectation about this package's install presence, enforce it.
6316        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6317            PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6318            if (known != null) {
6319                if (DEBUG_PACKAGE_SCANNING) {
6320                    Log.d(TAG, "Examining " + pkg.codePath
6321                            + " and requiring known paths " + known.codePathString
6322                            + " & " + known.resourcePathString);
6323                }
6324                if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6325                        || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6326                    throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6327                            "Application package " + pkg.packageName
6328                            + " found at " + pkg.applicationInfo.getCodePath()
6329                            + " but expected at " + known.codePathString + "; ignoring.");
6330                }
6331            }
6332        }
6333
6334        // Initialize package source and resource directories
6335        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6336        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6337
6338        SharedUserSetting suid = null;
6339        PackageSetting pkgSetting = null;
6340
6341        if (!isSystemApp(pkg)) {
6342            // Only system apps can use these features.
6343            pkg.mOriginalPackages = null;
6344            pkg.mRealPackage = null;
6345            pkg.mAdoptPermissions = null;
6346        }
6347
6348        // writer
6349        synchronized (mPackages) {
6350            if (pkg.mSharedUserId != null) {
6351                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6352                if (suid == null) {
6353                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6354                            "Creating application package " + pkg.packageName
6355                            + " for shared user failed");
6356                }
6357                if (DEBUG_PACKAGE_SCANNING) {
6358                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6359                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6360                                + "): packages=" + suid.packages);
6361                }
6362            }
6363
6364            // Check if we are renaming from an original package name.
6365            PackageSetting origPackage = null;
6366            String realName = null;
6367            if (pkg.mOriginalPackages != null) {
6368                // This package may need to be renamed to a previously
6369                // installed name.  Let's check on that...
6370                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
6371                if (pkg.mOriginalPackages.contains(renamed)) {
6372                    // This package had originally been installed as the
6373                    // original name, and we have already taken care of
6374                    // transitioning to the new one.  Just update the new
6375                    // one to continue using the old name.
6376                    realName = pkg.mRealPackage;
6377                    if (!pkg.packageName.equals(renamed)) {
6378                        // Callers into this function may have already taken
6379                        // care of renaming the package; only do it here if
6380                        // it is not already done.
6381                        pkg.setPackageName(renamed);
6382                    }
6383
6384                } else {
6385                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
6386                        if ((origPackage = mSettings.peekPackageLPr(
6387                                pkg.mOriginalPackages.get(i))) != null) {
6388                            // We do have the package already installed under its
6389                            // original name...  should we use it?
6390                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
6391                                // New package is not compatible with original.
6392                                origPackage = null;
6393                                continue;
6394                            } else if (origPackage.sharedUser != null) {
6395                                // Make sure uid is compatible between packages.
6396                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6397                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6398                                            + " to " + pkg.packageName + ": old uid "
6399                                            + origPackage.sharedUser.name
6400                                            + " differs from " + pkg.mSharedUserId);
6401                                    origPackage = null;
6402                                    continue;
6403                                }
6404                            } else {
6405                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6406                                        + pkg.packageName + " to old name " + origPackage.name);
6407                            }
6408                            break;
6409                        }
6410                    }
6411                }
6412            }
6413
6414            if (mTransferedPackages.contains(pkg.packageName)) {
6415                Slog.w(TAG, "Package " + pkg.packageName
6416                        + " was transferred to another, but its .apk remains");
6417            }
6418
6419            // Just create the setting, don't add it yet. For already existing packages
6420            // the PkgSetting exists already and doesn't have to be created.
6421            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6422                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6423                    pkg.applicationInfo.primaryCpuAbi,
6424                    pkg.applicationInfo.secondaryCpuAbi,
6425                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6426                    user, false);
6427            if (pkgSetting == null) {
6428                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6429                        "Creating application package " + pkg.packageName + " failed");
6430            }
6431
6432            if (pkgSetting.origPackage != null) {
6433                // If we are first transitioning from an original package,
6434                // fix up the new package's name now.  We need to do this after
6435                // looking up the package under its new name, so getPackageLP
6436                // can take care of fiddling things correctly.
6437                pkg.setPackageName(origPackage.name);
6438
6439                // File a report about this.
6440                String msg = "New package " + pkgSetting.realName
6441                        + " renamed to replace old package " + pkgSetting.name;
6442                reportSettingsProblem(Log.WARN, msg);
6443
6444                // Make a note of it.
6445                mTransferedPackages.add(origPackage.name);
6446
6447                // No longer need to retain this.
6448                pkgSetting.origPackage = null;
6449            }
6450
6451            if (realName != null) {
6452                // Make a note of it.
6453                mTransferedPackages.add(pkg.packageName);
6454            }
6455
6456            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6457                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6458            }
6459
6460            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6461                // Check all shared libraries and map to their actual file path.
6462                // We only do this here for apps not on a system dir, because those
6463                // are the only ones that can fail an install due to this.  We
6464                // will take care of the system apps by updating all of their
6465                // library paths after the scan is done.
6466                updateSharedLibrariesLPw(pkg, null);
6467            }
6468
6469            if (mFoundPolicyFile) {
6470                SELinuxMMAC.assignSeinfoValue(pkg);
6471            }
6472
6473            pkg.applicationInfo.uid = pkgSetting.appId;
6474            pkg.mExtras = pkgSetting;
6475            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
6476                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
6477                    // We just determined the app is signed correctly, so bring
6478                    // over the latest parsed certs.
6479                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6480                } else {
6481                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6482                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6483                                "Package " + pkg.packageName + " upgrade keys do not match the "
6484                                + "previously installed version");
6485                    } else {
6486                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
6487                        String msg = "System package " + pkg.packageName
6488                            + " signature changed; retaining data.";
6489                        reportSettingsProblem(Log.WARN, msg);
6490                    }
6491                }
6492            } else {
6493                try {
6494                    verifySignaturesLP(pkgSetting, pkg);
6495                    // We just determined the app is signed correctly, so bring
6496                    // over the latest parsed certs.
6497                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6498                } catch (PackageManagerException e) {
6499                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6500                        throw e;
6501                    }
6502                    // The signature has changed, but this package is in the system
6503                    // image...  let's recover!
6504                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6505                    // However...  if this package is part of a shared user, but it
6506                    // doesn't match the signature of the shared user, let's fail.
6507                    // What this means is that you can't change the signatures
6508                    // associated with an overall shared user, which doesn't seem all
6509                    // that unreasonable.
6510                    if (pkgSetting.sharedUser != null) {
6511                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6512                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
6513                            throw new PackageManagerException(
6514                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
6515                                            "Signature mismatch for shared user : "
6516                                            + pkgSetting.sharedUser);
6517                        }
6518                    }
6519                    // File a report about this.
6520                    String msg = "System package " + pkg.packageName
6521                        + " signature changed; retaining data.";
6522                    reportSettingsProblem(Log.WARN, msg);
6523                }
6524            }
6525            // Verify that this new package doesn't have any content providers
6526            // that conflict with existing packages.  Only do this if the
6527            // package isn't already installed, since we don't want to break
6528            // things that are installed.
6529            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6530                final int N = pkg.providers.size();
6531                int i;
6532                for (i=0; i<N; i++) {
6533                    PackageParser.Provider p = pkg.providers.get(i);
6534                    if (p.info.authority != null) {
6535                        String names[] = p.info.authority.split(";");
6536                        for (int j = 0; j < names.length; j++) {
6537                            if (mProvidersByAuthority.containsKey(names[j])) {
6538                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6539                                final String otherPackageName =
6540                                        ((other != null && other.getComponentName() != null) ?
6541                                                other.getComponentName().getPackageName() : "?");
6542                                throw new PackageManagerException(
6543                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
6544                                                "Can't install because provider name " + names[j]
6545                                                + " (in package " + pkg.applicationInfo.packageName
6546                                                + ") is already used by " + otherPackageName);
6547                            }
6548                        }
6549                    }
6550                }
6551            }
6552
6553            if (pkg.mAdoptPermissions != null) {
6554                // This package wants to adopt ownership of permissions from
6555                // another package.
6556                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6557                    final String origName = pkg.mAdoptPermissions.get(i);
6558                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
6559                    if (orig != null) {
6560                        if (verifyPackageUpdateLPr(orig, pkg)) {
6561                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
6562                                    + pkg.packageName);
6563                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
6564                        }
6565                    }
6566                }
6567            }
6568        }
6569
6570        final String pkgName = pkg.packageName;
6571
6572        final long scanFileTime = scanFile.lastModified();
6573        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6574        pkg.applicationInfo.processName = fixProcessName(
6575                pkg.applicationInfo.packageName,
6576                pkg.applicationInfo.processName,
6577                pkg.applicationInfo.uid);
6578
6579        File dataPath;
6580        if (mPlatformPackage == pkg) {
6581            // The system package is special.
6582            dataPath = new File(Environment.getDataDirectory(), "system");
6583
6584            pkg.applicationInfo.dataDir = dataPath.getPath();
6585
6586        } else {
6587            // This is a normal package, need to make its data directory.
6588            dataPath = PackageManager.getDataDirForUser(pkg.volumeUuid, pkg.packageName,
6589                    UserHandle.USER_OWNER);
6590
6591            boolean uidError = false;
6592            if (dataPath.exists()) {
6593                int currentUid = 0;
6594                try {
6595                    StructStat stat = Os.stat(dataPath.getPath());
6596                    currentUid = stat.st_uid;
6597                } catch (ErrnoException e) {
6598                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6599                }
6600
6601                // If we have mismatched owners for the data path, we have a problem.
6602                if (currentUid != pkg.applicationInfo.uid) {
6603                    boolean recovered = false;
6604                    if (currentUid == 0) {
6605                        // The directory somehow became owned by root.  Wow.
6606                        // This is probably because the system was stopped while
6607                        // installd was in the middle of messing with its libs
6608                        // directory.  Ask installd to fix that.
6609                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
6610                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
6611                        if (ret >= 0) {
6612                            recovered = true;
6613                            String msg = "Package " + pkg.packageName
6614                                    + " unexpectedly changed to uid 0; recovered to " +
6615                                    + pkg.applicationInfo.uid;
6616                            reportSettingsProblem(Log.WARN, msg);
6617                        }
6618                    }
6619                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6620                            || (scanFlags&SCAN_BOOTING) != 0)) {
6621                        // If this is a system app, we can at least delete its
6622                        // current data so the application will still work.
6623                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
6624                        if (ret >= 0) {
6625                            // TODO: Kill the processes first
6626                            // Old data gone!
6627                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6628                                    ? "System package " : "Third party package ";
6629                            String msg = prefix + pkg.packageName
6630                                    + " has changed from uid: "
6631                                    + currentUid + " to "
6632                                    + pkg.applicationInfo.uid + "; old data erased";
6633                            reportSettingsProblem(Log.WARN, msg);
6634                            recovered = true;
6635
6636                            // And now re-install the app.
6637                            ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6638                                    pkg.applicationInfo.seinfo);
6639                            if (ret == -1) {
6640                                // Ack should not happen!
6641                                msg = prefix + pkg.packageName
6642                                        + " could not have data directory re-created after delete.";
6643                                reportSettingsProblem(Log.WARN, msg);
6644                                throw new PackageManagerException(
6645                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6646                            }
6647                        }
6648                        if (!recovered) {
6649                            mHasSystemUidErrors = true;
6650                        }
6651                    } else if (!recovered) {
6652                        // If we allow this install to proceed, we will be broken.
6653                        // Abort, abort!
6654                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
6655                                "scanPackageLI");
6656                    }
6657                    if (!recovered) {
6658                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
6659                            + pkg.applicationInfo.uid + "/fs_"
6660                            + currentUid;
6661                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
6662                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
6663                        String msg = "Package " + pkg.packageName
6664                                + " has mismatched uid: "
6665                                + currentUid + " on disk, "
6666                                + pkg.applicationInfo.uid + " in settings";
6667                        // writer
6668                        synchronized (mPackages) {
6669                            mSettings.mReadMessages.append(msg);
6670                            mSettings.mReadMessages.append('\n');
6671                            uidError = true;
6672                            if (!pkgSetting.uidError) {
6673                                reportSettingsProblem(Log.ERROR, msg);
6674                            }
6675                        }
6676                    }
6677                }
6678                pkg.applicationInfo.dataDir = dataPath.getPath();
6679                if (mShouldRestoreconData) {
6680                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
6681                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
6682                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
6683                }
6684            } else {
6685                if (DEBUG_PACKAGE_SCANNING) {
6686                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6687                        Log.v(TAG, "Want this data dir: " + dataPath);
6688                }
6689                //invoke installer to do the actual installation
6690                int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6691                        pkg.applicationInfo.seinfo);
6692                if (ret < 0) {
6693                    // Error from installer
6694                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6695                            "Unable to create data dirs [errorCode=" + ret + "]");
6696                }
6697
6698                if (dataPath.exists()) {
6699                    pkg.applicationInfo.dataDir = dataPath.getPath();
6700                } else {
6701                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
6702                    pkg.applicationInfo.dataDir = null;
6703                }
6704            }
6705
6706            pkgSetting.uidError = uidError;
6707        }
6708
6709        final String path = scanFile.getPath();
6710        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
6711
6712        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
6713            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
6714
6715            // Some system apps still use directory structure for native libraries
6716            // in which case we might end up not detecting abi solely based on apk
6717            // structure. Try to detect abi based on directory structure.
6718            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
6719                    pkg.applicationInfo.primaryCpuAbi == null) {
6720                setBundledAppAbisAndRoots(pkg, pkgSetting);
6721                setNativeLibraryPaths(pkg);
6722            }
6723
6724        } else {
6725            if ((scanFlags & SCAN_MOVE) != 0) {
6726                // We haven't run dex-opt for this move (since we've moved the compiled output too)
6727                // but we already have this packages package info in the PackageSetting. We just
6728                // use that and derive the native library path based on the new codepath.
6729                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
6730                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
6731            }
6732
6733            // Set native library paths again. For moves, the path will be updated based on the
6734            // ABIs we've determined above. For non-moves, the path will be updated based on the
6735            // ABIs we determined during compilation, but the path will depend on the final
6736            // package path (after the rename away from the stage path).
6737            setNativeLibraryPaths(pkg);
6738        }
6739
6740        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
6741        final int[] userIds = sUserManager.getUserIds();
6742        synchronized (mInstallLock) {
6743            // Create a native library symlink only if we have native libraries
6744            // and if the native libraries are 32 bit libraries. We do not provide
6745            // this symlink for 64 bit libraries.
6746            if (pkg.applicationInfo.primaryCpuAbi != null &&
6747                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
6748                final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
6749                for (int userId : userIds) {
6750                    if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
6751                            nativeLibPath, userId) < 0) {
6752                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
6753                                "Failed linking native library dir (user=" + userId + ")");
6754                    }
6755                }
6756            }
6757        }
6758
6759        // This is a special case for the "system" package, where the ABI is
6760        // dictated by the zygote configuration (and init.rc). We should keep track
6761        // of this ABI so that we can deal with "normal" applications that run under
6762        // the same UID correctly.
6763        if (mPlatformPackage == pkg) {
6764            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
6765                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
6766        }
6767
6768        // If there's a mismatch between the abi-override in the package setting
6769        // and the abiOverride specified for the install. Warn about this because we
6770        // would've already compiled the app without taking the package setting into
6771        // account.
6772        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
6773            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
6774                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
6775                        " for package: " + pkg.packageName);
6776            }
6777        }
6778
6779        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6780        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6781        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
6782
6783        // Copy the derived override back to the parsed package, so that we can
6784        // update the package settings accordingly.
6785        pkg.cpuAbiOverride = cpuAbiOverride;
6786
6787        if (DEBUG_ABI_SELECTION) {
6788            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
6789                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
6790                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
6791        }
6792
6793        // Push the derived path down into PackageSettings so we know what to
6794        // clean up at uninstall time.
6795        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
6796
6797        if (DEBUG_ABI_SELECTION) {
6798            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
6799                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
6800                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
6801        }
6802
6803        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
6804            // We don't do this here during boot because we can do it all
6805            // at once after scanning all existing packages.
6806            //
6807            // We also do this *before* we perform dexopt on this package, so that
6808            // we can avoid redundant dexopts, and also to make sure we've got the
6809            // code and package path correct.
6810            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
6811                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
6812        }
6813
6814        if ((scanFlags & SCAN_NO_DEX) == 0) {
6815            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
6816                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */);
6817            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6818                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
6819            }
6820        }
6821        if (mFactoryTest && pkg.requestedPermissions.contains(
6822                android.Manifest.permission.FACTORY_TEST)) {
6823            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
6824        }
6825
6826        ArrayList<PackageParser.Package> clientLibPkgs = null;
6827
6828        // writer
6829        synchronized (mPackages) {
6830            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6831                // Only system apps can add new shared libraries.
6832                if (pkg.libraryNames != null) {
6833                    for (int i=0; i<pkg.libraryNames.size(); i++) {
6834                        String name = pkg.libraryNames.get(i);
6835                        boolean allowed = false;
6836                        if (pkg.isUpdatedSystemApp()) {
6837                            // New library entries can only be added through the
6838                            // system image.  This is important to get rid of a lot
6839                            // of nasty edge cases: for example if we allowed a non-
6840                            // system update of the app to add a library, then uninstalling
6841                            // the update would make the library go away, and assumptions
6842                            // we made such as through app install filtering would now
6843                            // have allowed apps on the device which aren't compatible
6844                            // with it.  Better to just have the restriction here, be
6845                            // conservative, and create many fewer cases that can negatively
6846                            // impact the user experience.
6847                            final PackageSetting sysPs = mSettings
6848                                    .getDisabledSystemPkgLPr(pkg.packageName);
6849                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
6850                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
6851                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
6852                                        allowed = true;
6853                                        allowed = true;
6854                                        break;
6855                                    }
6856                                }
6857                            }
6858                        } else {
6859                            allowed = true;
6860                        }
6861                        if (allowed) {
6862                            if (!mSharedLibraries.containsKey(name)) {
6863                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
6864                            } else if (!name.equals(pkg.packageName)) {
6865                                Slog.w(TAG, "Package " + pkg.packageName + " library "
6866                                        + name + " already exists; skipping");
6867                            }
6868                        } else {
6869                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
6870                                    + name + " that is not declared on system image; skipping");
6871                        }
6872                    }
6873                    if ((scanFlags&SCAN_BOOTING) == 0) {
6874                        // If we are not booting, we need to update any applications
6875                        // that are clients of our shared library.  If we are booting,
6876                        // this will all be done once the scan is complete.
6877                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
6878                    }
6879                }
6880            }
6881        }
6882
6883        // We also need to dexopt any apps that are dependent on this library.  Note that
6884        // if these fail, we should abort the install since installing the library will
6885        // result in some apps being broken.
6886        if (clientLibPkgs != null) {
6887            if ((scanFlags & SCAN_NO_DEX) == 0) {
6888                for (int i = 0; i < clientLibPkgs.size(); i++) {
6889                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
6890                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
6891                            null /* instruction sets */, forceDex,
6892                            (scanFlags & SCAN_DEFER_DEX) != 0, false);
6893                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6894                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
6895                                "scanPackageLI failed to dexopt clientLibPkgs");
6896                    }
6897                }
6898            }
6899        }
6900
6901        // Also need to kill any apps that are dependent on the library.
6902        if (clientLibPkgs != null) {
6903            for (int i=0; i<clientLibPkgs.size(); i++) {
6904                PackageParser.Package clientPkg = clientLibPkgs.get(i);
6905                killApplication(clientPkg.applicationInfo.packageName,
6906                        clientPkg.applicationInfo.uid, "update lib");
6907            }
6908        }
6909
6910        // Make sure we're not adding any bogus keyset info
6911        KeySetManagerService ksms = mSettings.mKeySetManagerService;
6912        ksms.assertScannedPackageValid(pkg);
6913
6914        // writer
6915        synchronized (mPackages) {
6916            // We don't expect installation to fail beyond this point
6917
6918            // Add the new setting to mSettings
6919            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
6920            // Add the new setting to mPackages
6921            mPackages.put(pkg.applicationInfo.packageName, pkg);
6922            // Make sure we don't accidentally delete its data.
6923            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
6924            while (iter.hasNext()) {
6925                PackageCleanItem item = iter.next();
6926                if (pkgName.equals(item.packageName)) {
6927                    iter.remove();
6928                }
6929            }
6930
6931            // Take care of first install / last update times.
6932            if (currentTime != 0) {
6933                if (pkgSetting.firstInstallTime == 0) {
6934                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
6935                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
6936                    pkgSetting.lastUpdateTime = currentTime;
6937                }
6938            } else if (pkgSetting.firstInstallTime == 0) {
6939                // We need *something*.  Take time time stamp of the file.
6940                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
6941            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
6942                if (scanFileTime != pkgSetting.timeStamp) {
6943                    // A package on the system image has changed; consider this
6944                    // to be an update.
6945                    pkgSetting.lastUpdateTime = scanFileTime;
6946                }
6947            }
6948
6949            // Add the package's KeySets to the global KeySetManagerService
6950            ksms.addScannedPackageLPw(pkg);
6951
6952            int N = pkg.providers.size();
6953            StringBuilder r = null;
6954            int i;
6955            for (i=0; i<N; i++) {
6956                PackageParser.Provider p = pkg.providers.get(i);
6957                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
6958                        p.info.processName, pkg.applicationInfo.uid);
6959                mProviders.addProvider(p);
6960                p.syncable = p.info.isSyncable;
6961                if (p.info.authority != null) {
6962                    String names[] = p.info.authority.split(";");
6963                    p.info.authority = null;
6964                    for (int j = 0; j < names.length; j++) {
6965                        if (j == 1 && p.syncable) {
6966                            // We only want the first authority for a provider to possibly be
6967                            // syncable, so if we already added this provider using a different
6968                            // authority clear the syncable flag. We copy the provider before
6969                            // changing it because the mProviders object contains a reference
6970                            // to a provider that we don't want to change.
6971                            // Only do this for the second authority since the resulting provider
6972                            // object can be the same for all future authorities for this provider.
6973                            p = new PackageParser.Provider(p);
6974                            p.syncable = false;
6975                        }
6976                        if (!mProvidersByAuthority.containsKey(names[j])) {
6977                            mProvidersByAuthority.put(names[j], p);
6978                            if (p.info.authority == null) {
6979                                p.info.authority = names[j];
6980                            } else {
6981                                p.info.authority = p.info.authority + ";" + names[j];
6982                            }
6983                            if (DEBUG_PACKAGE_SCANNING) {
6984                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6985                                    Log.d(TAG, "Registered content provider: " + names[j]
6986                                            + ", className = " + p.info.name + ", isSyncable = "
6987                                            + p.info.isSyncable);
6988                            }
6989                        } else {
6990                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6991                            Slog.w(TAG, "Skipping provider name " + names[j] +
6992                                    " (in package " + pkg.applicationInfo.packageName +
6993                                    "): name already used by "
6994                                    + ((other != null && other.getComponentName() != null)
6995                                            ? other.getComponentName().getPackageName() : "?"));
6996                        }
6997                    }
6998                }
6999                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7000                    if (r == null) {
7001                        r = new StringBuilder(256);
7002                    } else {
7003                        r.append(' ');
7004                    }
7005                    r.append(p.info.name);
7006                }
7007            }
7008            if (r != null) {
7009                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7010            }
7011
7012            N = pkg.services.size();
7013            r = null;
7014            for (i=0; i<N; i++) {
7015                PackageParser.Service s = pkg.services.get(i);
7016                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7017                        s.info.processName, pkg.applicationInfo.uid);
7018                mServices.addService(s);
7019                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7020                    if (r == null) {
7021                        r = new StringBuilder(256);
7022                    } else {
7023                        r.append(' ');
7024                    }
7025                    r.append(s.info.name);
7026                }
7027            }
7028            if (r != null) {
7029                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7030            }
7031
7032            N = pkg.receivers.size();
7033            r = null;
7034            for (i=0; i<N; i++) {
7035                PackageParser.Activity a = pkg.receivers.get(i);
7036                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7037                        a.info.processName, pkg.applicationInfo.uid);
7038                mReceivers.addActivity(a, "receiver");
7039                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7040                    if (r == null) {
7041                        r = new StringBuilder(256);
7042                    } else {
7043                        r.append(' ');
7044                    }
7045                    r.append(a.info.name);
7046                }
7047            }
7048            if (r != null) {
7049                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7050            }
7051
7052            N = pkg.activities.size();
7053            r = null;
7054            for (i=0; i<N; i++) {
7055                PackageParser.Activity a = pkg.activities.get(i);
7056                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7057                        a.info.processName, pkg.applicationInfo.uid);
7058                mActivities.addActivity(a, "activity");
7059                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7060                    if (r == null) {
7061                        r = new StringBuilder(256);
7062                    } else {
7063                        r.append(' ');
7064                    }
7065                    r.append(a.info.name);
7066                }
7067            }
7068            if (r != null) {
7069                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7070            }
7071
7072            N = pkg.permissionGroups.size();
7073            r = null;
7074            for (i=0; i<N; i++) {
7075                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7076                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7077                if (cur == null) {
7078                    mPermissionGroups.put(pg.info.name, pg);
7079                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7080                        if (r == null) {
7081                            r = new StringBuilder(256);
7082                        } else {
7083                            r.append(' ');
7084                        }
7085                        r.append(pg.info.name);
7086                    }
7087                } else {
7088                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7089                            + pg.info.packageName + " ignored: original from "
7090                            + cur.info.packageName);
7091                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7092                        if (r == null) {
7093                            r = new StringBuilder(256);
7094                        } else {
7095                            r.append(' ');
7096                        }
7097                        r.append("DUP:");
7098                        r.append(pg.info.name);
7099                    }
7100                }
7101            }
7102            if (r != null) {
7103                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7104            }
7105
7106            N = pkg.permissions.size();
7107            r = null;
7108            for (i=0; i<N; i++) {
7109                PackageParser.Permission p = pkg.permissions.get(i);
7110
7111                // Now that permission groups have a special meaning, we ignore permission
7112                // groups for legacy apps to prevent unexpected behavior. In particular,
7113                // permissions for one app being granted to someone just becuase they happen
7114                // to be in a group defined by another app (before this had no implications).
7115                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7116                    p.group = mPermissionGroups.get(p.info.group);
7117                    // Warn for a permission in an unknown group.
7118                    if (p.info.group != null && p.group == null) {
7119                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7120                                + p.info.packageName + " in an unknown group " + p.info.group);
7121                    }
7122                }
7123
7124                ArrayMap<String, BasePermission> permissionMap =
7125                        p.tree ? mSettings.mPermissionTrees
7126                                : mSettings.mPermissions;
7127                BasePermission bp = permissionMap.get(p.info.name);
7128
7129                // Allow system apps to redefine non-system permissions
7130                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7131                    final boolean currentOwnerIsSystem = (bp.perm != null
7132                            && isSystemApp(bp.perm.owner));
7133                    if (isSystemApp(p.owner)) {
7134                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7135                            // It's a built-in permission and no owner, take ownership now
7136                            bp.packageSetting = pkgSetting;
7137                            bp.perm = p;
7138                            bp.uid = pkg.applicationInfo.uid;
7139                            bp.sourcePackage = p.info.packageName;
7140                        } else if (!currentOwnerIsSystem) {
7141                            String msg = "New decl " + p.owner + " of permission  "
7142                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7143                            reportSettingsProblem(Log.WARN, msg);
7144                            bp = null;
7145                        }
7146                    }
7147                }
7148
7149                if (bp == null) {
7150                    bp = new BasePermission(p.info.name, p.info.packageName,
7151                            BasePermission.TYPE_NORMAL);
7152                    permissionMap.put(p.info.name, bp);
7153                }
7154
7155                if (bp.perm == null) {
7156                    if (bp.sourcePackage == null
7157                            || bp.sourcePackage.equals(p.info.packageName)) {
7158                        BasePermission tree = findPermissionTreeLP(p.info.name);
7159                        if (tree == null
7160                                || tree.sourcePackage.equals(p.info.packageName)) {
7161                            bp.packageSetting = pkgSetting;
7162                            bp.perm = p;
7163                            bp.uid = pkg.applicationInfo.uid;
7164                            bp.sourcePackage = p.info.packageName;
7165                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7166                                if (r == null) {
7167                                    r = new StringBuilder(256);
7168                                } else {
7169                                    r.append(' ');
7170                                }
7171                                r.append(p.info.name);
7172                            }
7173                        } else {
7174                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7175                                    + p.info.packageName + " ignored: base tree "
7176                                    + tree.name + " is from package "
7177                                    + tree.sourcePackage);
7178                        }
7179                    } else {
7180                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7181                                + p.info.packageName + " ignored: original from "
7182                                + bp.sourcePackage);
7183                    }
7184                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7185                    if (r == null) {
7186                        r = new StringBuilder(256);
7187                    } else {
7188                        r.append(' ');
7189                    }
7190                    r.append("DUP:");
7191                    r.append(p.info.name);
7192                }
7193                if (bp.perm == p) {
7194                    bp.protectionLevel = p.info.protectionLevel;
7195                }
7196            }
7197
7198            if (r != null) {
7199                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7200            }
7201
7202            N = pkg.instrumentation.size();
7203            r = null;
7204            for (i=0; i<N; i++) {
7205                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7206                a.info.packageName = pkg.applicationInfo.packageName;
7207                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7208                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7209                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7210                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7211                a.info.dataDir = pkg.applicationInfo.dataDir;
7212
7213                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7214                // need other information about the application, like the ABI and what not ?
7215                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7216                mInstrumentation.put(a.getComponentName(), a);
7217                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7218                    if (r == null) {
7219                        r = new StringBuilder(256);
7220                    } else {
7221                        r.append(' ');
7222                    }
7223                    r.append(a.info.name);
7224                }
7225            }
7226            if (r != null) {
7227                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7228            }
7229
7230            if (pkg.protectedBroadcasts != null) {
7231                N = pkg.protectedBroadcasts.size();
7232                for (i=0; i<N; i++) {
7233                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7234                }
7235            }
7236
7237            pkgSetting.setTimeStamp(scanFileTime);
7238
7239            // Create idmap files for pairs of (packages, overlay packages).
7240            // Note: "android", ie framework-res.apk, is handled by native layers.
7241            if (pkg.mOverlayTarget != null) {
7242                // This is an overlay package.
7243                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7244                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7245                        mOverlays.put(pkg.mOverlayTarget,
7246                                new ArrayMap<String, PackageParser.Package>());
7247                    }
7248                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7249                    map.put(pkg.packageName, pkg);
7250                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7251                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7252                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7253                                "scanPackageLI failed to createIdmap");
7254                    }
7255                }
7256            } else if (mOverlays.containsKey(pkg.packageName) &&
7257                    !pkg.packageName.equals("android")) {
7258                // This is a regular package, with one or more known overlay packages.
7259                createIdmapsForPackageLI(pkg);
7260            }
7261        }
7262
7263        return pkg;
7264    }
7265
7266    /**
7267     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7268     * is derived purely on the basis of the contents of {@code scanFile} and
7269     * {@code cpuAbiOverride}.
7270     *
7271     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7272     */
7273    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7274                                 String cpuAbiOverride, boolean extractLibs)
7275            throws PackageManagerException {
7276        // TODO: We can probably be smarter about this stuff. For installed apps,
7277        // we can calculate this information at install time once and for all. For
7278        // system apps, we can probably assume that this information doesn't change
7279        // after the first boot scan. As things stand, we do lots of unnecessary work.
7280
7281        // Give ourselves some initial paths; we'll come back for another
7282        // pass once we've determined ABI below.
7283        setNativeLibraryPaths(pkg);
7284
7285        // We would never need to extract libs for forward-locked and external packages,
7286        // since the container service will do it for us. We shouldn't attempt to
7287        // extract libs from system app when it was not updated.
7288        if (pkg.isForwardLocked() || isExternal(pkg) ||
7289            (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) {
7290            extractLibs = false;
7291        }
7292
7293        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7294        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7295
7296        NativeLibraryHelper.Handle handle = null;
7297        try {
7298            handle = NativeLibraryHelper.Handle.create(scanFile);
7299            // TODO(multiArch): This can be null for apps that didn't go through the
7300            // usual installation process. We can calculate it again, like we
7301            // do during install time.
7302            //
7303            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7304            // unnecessary.
7305            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7306
7307            // Null out the abis so that they can be recalculated.
7308            pkg.applicationInfo.primaryCpuAbi = null;
7309            pkg.applicationInfo.secondaryCpuAbi = null;
7310            if (isMultiArch(pkg.applicationInfo)) {
7311                // Warn if we've set an abiOverride for multi-lib packages..
7312                // By definition, we need to copy both 32 and 64 bit libraries for
7313                // such packages.
7314                if (pkg.cpuAbiOverride != null
7315                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7316                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7317                }
7318
7319                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7320                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7321                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7322                    if (extractLibs) {
7323                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7324                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7325                                useIsaSpecificSubdirs);
7326                    } else {
7327                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7328                    }
7329                }
7330
7331                maybeThrowExceptionForMultiArchCopy(
7332                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7333
7334                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7335                    if (extractLibs) {
7336                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7337                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7338                                useIsaSpecificSubdirs);
7339                    } else {
7340                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7341                    }
7342                }
7343
7344                maybeThrowExceptionForMultiArchCopy(
7345                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7346
7347                if (abi64 >= 0) {
7348                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7349                }
7350
7351                if (abi32 >= 0) {
7352                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7353                    if (abi64 >= 0) {
7354                        pkg.applicationInfo.secondaryCpuAbi = abi;
7355                    } else {
7356                        pkg.applicationInfo.primaryCpuAbi = abi;
7357                    }
7358                }
7359            } else {
7360                String[] abiList = (cpuAbiOverride != null) ?
7361                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7362
7363                // Enable gross and lame hacks for apps that are built with old
7364                // SDK tools. We must scan their APKs for renderscript bitcode and
7365                // not launch them if it's present. Don't bother checking on devices
7366                // that don't have 64 bit support.
7367                boolean needsRenderScriptOverride = false;
7368                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7369                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7370                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7371                    needsRenderScriptOverride = true;
7372                }
7373
7374                final int copyRet;
7375                if (extractLibs) {
7376                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7377                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7378                } else {
7379                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7380                }
7381
7382                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7383                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7384                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7385                }
7386
7387                if (copyRet >= 0) {
7388                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7389                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7390                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7391                } else if (needsRenderScriptOverride) {
7392                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7393                }
7394            }
7395        } catch (IOException ioe) {
7396            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7397        } finally {
7398            IoUtils.closeQuietly(handle);
7399        }
7400
7401        // Now that we've calculated the ABIs and determined if it's an internal app,
7402        // we will go ahead and populate the nativeLibraryPath.
7403        setNativeLibraryPaths(pkg);
7404    }
7405
7406    /**
7407     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7408     * i.e, so that all packages can be run inside a single process if required.
7409     *
7410     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7411     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7412     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7413     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7414     * updating a package that belongs to a shared user.
7415     *
7416     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7417     * adds unnecessary complexity.
7418     */
7419    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7420            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
7421        String requiredInstructionSet = null;
7422        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7423            requiredInstructionSet = VMRuntime.getInstructionSet(
7424                     scannedPackage.applicationInfo.primaryCpuAbi);
7425        }
7426
7427        PackageSetting requirer = null;
7428        for (PackageSetting ps : packagesForUser) {
7429            // If packagesForUser contains scannedPackage, we skip it. This will happen
7430            // when scannedPackage is an update of an existing package. Without this check,
7431            // we will never be able to change the ABI of any package belonging to a shared
7432            // user, even if it's compatible with other packages.
7433            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7434                if (ps.primaryCpuAbiString == null) {
7435                    continue;
7436                }
7437
7438                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7439                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7440                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7441                    // this but there's not much we can do.
7442                    String errorMessage = "Instruction set mismatch, "
7443                            + ((requirer == null) ? "[caller]" : requirer)
7444                            + " requires " + requiredInstructionSet + " whereas " + ps
7445                            + " requires " + instructionSet;
7446                    Slog.w(TAG, errorMessage);
7447                }
7448
7449                if (requiredInstructionSet == null) {
7450                    requiredInstructionSet = instructionSet;
7451                    requirer = ps;
7452                }
7453            }
7454        }
7455
7456        if (requiredInstructionSet != null) {
7457            String adjustedAbi;
7458            if (requirer != null) {
7459                // requirer != null implies that either scannedPackage was null or that scannedPackage
7460                // did not require an ABI, in which case we have to adjust scannedPackage to match
7461                // the ABI of the set (which is the same as requirer's ABI)
7462                adjustedAbi = requirer.primaryCpuAbiString;
7463                if (scannedPackage != null) {
7464                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7465                }
7466            } else {
7467                // requirer == null implies that we're updating all ABIs in the set to
7468                // match scannedPackage.
7469                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7470            }
7471
7472            for (PackageSetting ps : packagesForUser) {
7473                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7474                    if (ps.primaryCpuAbiString != null) {
7475                        continue;
7476                    }
7477
7478                    ps.primaryCpuAbiString = adjustedAbi;
7479                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7480                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7481                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7482
7483                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
7484                                null /* instruction sets */, forceDexOpt, deferDexOpt, true);
7485                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7486                            ps.primaryCpuAbiString = null;
7487                            ps.pkg.applicationInfo.primaryCpuAbi = null;
7488                            return;
7489                        } else {
7490                            mInstaller.rmdex(ps.codePathString,
7491                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
7492                        }
7493                    }
7494                }
7495            }
7496        }
7497    }
7498
7499    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7500        synchronized (mPackages) {
7501            mResolverReplaced = true;
7502            // Set up information for custom user intent resolution activity.
7503            mResolveActivity.applicationInfo = pkg.applicationInfo;
7504            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7505            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7506            mResolveActivity.processName = pkg.applicationInfo.packageName;
7507            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7508            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7509                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7510            mResolveActivity.theme = 0;
7511            mResolveActivity.exported = true;
7512            mResolveActivity.enabled = true;
7513            mResolveInfo.activityInfo = mResolveActivity;
7514            mResolveInfo.priority = 0;
7515            mResolveInfo.preferredOrder = 0;
7516            mResolveInfo.match = 0;
7517            mResolveComponentName = mCustomResolverComponentName;
7518            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7519                    mResolveComponentName);
7520        }
7521    }
7522
7523    private static String calculateBundledApkRoot(final String codePathString) {
7524        final File codePath = new File(codePathString);
7525        final File codeRoot;
7526        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7527            codeRoot = Environment.getRootDirectory();
7528        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7529            codeRoot = Environment.getOemDirectory();
7530        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7531            codeRoot = Environment.getVendorDirectory();
7532        } else {
7533            // Unrecognized code path; take its top real segment as the apk root:
7534            // e.g. /something/app/blah.apk => /something
7535            try {
7536                File f = codePath.getCanonicalFile();
7537                File parent = f.getParentFile();    // non-null because codePath is a file
7538                File tmp;
7539                while ((tmp = parent.getParentFile()) != null) {
7540                    f = parent;
7541                    parent = tmp;
7542                }
7543                codeRoot = f;
7544                Slog.w(TAG, "Unrecognized code path "
7545                        + codePath + " - using " + codeRoot);
7546            } catch (IOException e) {
7547                // Can't canonicalize the code path -- shenanigans?
7548                Slog.w(TAG, "Can't canonicalize code path " + codePath);
7549                return Environment.getRootDirectory().getPath();
7550            }
7551        }
7552        return codeRoot.getPath();
7553    }
7554
7555    /**
7556     * Derive and set the location of native libraries for the given package,
7557     * which varies depending on where and how the package was installed.
7558     */
7559    private void setNativeLibraryPaths(PackageParser.Package pkg) {
7560        final ApplicationInfo info = pkg.applicationInfo;
7561        final String codePath = pkg.codePath;
7562        final File codeFile = new File(codePath);
7563        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7564        final boolean asecApp = info.isForwardLocked() || isExternal(info);
7565
7566        info.nativeLibraryRootDir = null;
7567        info.nativeLibraryRootRequiresIsa = false;
7568        info.nativeLibraryDir = null;
7569        info.secondaryNativeLibraryDir = null;
7570
7571        if (isApkFile(codeFile)) {
7572            // Monolithic install
7573            if (bundledApp) {
7574                // If "/system/lib64/apkname" exists, assume that is the per-package
7575                // native library directory to use; otherwise use "/system/lib/apkname".
7576                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
7577                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
7578                        getPrimaryInstructionSet(info));
7579
7580                // This is a bundled system app so choose the path based on the ABI.
7581                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
7582                // is just the default path.
7583                final String apkName = deriveCodePathName(codePath);
7584                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
7585                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
7586                        apkName).getAbsolutePath();
7587
7588                if (info.secondaryCpuAbi != null) {
7589                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7590                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7591                            secondaryLibDir, apkName).getAbsolutePath();
7592                }
7593            } else if (asecApp) {
7594                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
7595                        .getAbsolutePath();
7596            } else {
7597                final String apkName = deriveCodePathName(codePath);
7598                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
7599                        .getAbsolutePath();
7600            }
7601
7602            info.nativeLibraryRootRequiresIsa = false;
7603            info.nativeLibraryDir = info.nativeLibraryRootDir;
7604        } else {
7605            // Cluster install
7606            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7607            info.nativeLibraryRootRequiresIsa = true;
7608
7609            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7610                    getPrimaryInstructionSet(info)).getAbsolutePath();
7611
7612            if (info.secondaryCpuAbi != null) {
7613                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7614                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7615            }
7616        }
7617    }
7618
7619    /**
7620     * Calculate the abis and roots for a bundled app. These can uniquely
7621     * be determined from the contents of the system partition, i.e whether
7622     * it contains 64 or 32 bit shared libraries etc. We do not validate any
7623     * of this information, and instead assume that the system was built
7624     * sensibly.
7625     */
7626    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
7627                                           PackageSetting pkgSetting) {
7628        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
7629
7630        // If "/system/lib64/apkname" exists, assume that is the per-package
7631        // native library directory to use; otherwise use "/system/lib/apkname".
7632        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
7633        setBundledAppAbi(pkg, apkRoot, apkName);
7634        // pkgSetting might be null during rescan following uninstall of updates
7635        // to a bundled app, so accommodate that possibility.  The settings in
7636        // that case will be established later from the parsed package.
7637        //
7638        // If the settings aren't null, sync them up with what we've just derived.
7639        // note that apkRoot isn't stored in the package settings.
7640        if (pkgSetting != null) {
7641            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7642            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7643        }
7644    }
7645
7646    /**
7647     * Deduces the ABI of a bundled app and sets the relevant fields on the
7648     * parsed pkg object.
7649     *
7650     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
7651     *        under which system libraries are installed.
7652     * @param apkName the name of the installed package.
7653     */
7654    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7655        final File codeFile = new File(pkg.codePath);
7656
7657        final boolean has64BitLibs;
7658        final boolean has32BitLibs;
7659        if (isApkFile(codeFile)) {
7660            // Monolithic install
7661            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7662            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7663        } else {
7664            // Cluster install
7665            final File rootDir = new File(codeFile, LIB_DIR_NAME);
7666            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7667                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7668                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7669                has64BitLibs = (new File(rootDir, isa)).exists();
7670            } else {
7671                has64BitLibs = false;
7672            }
7673            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7674                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7675                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7676                has32BitLibs = (new File(rootDir, isa)).exists();
7677            } else {
7678                has32BitLibs = false;
7679            }
7680        }
7681
7682        if (has64BitLibs && !has32BitLibs) {
7683            // The package has 64 bit libs, but not 32 bit libs. Its primary
7684            // ABI should be 64 bit. We can safely assume here that the bundled
7685            // native libraries correspond to the most preferred ABI in the list.
7686
7687            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7688            pkg.applicationInfo.secondaryCpuAbi = null;
7689        } else if (has32BitLibs && !has64BitLibs) {
7690            // The package has 32 bit libs but not 64 bit libs. Its primary
7691            // ABI should be 32 bit.
7692
7693            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7694            pkg.applicationInfo.secondaryCpuAbi = null;
7695        } else if (has32BitLibs && has64BitLibs) {
7696            // The application has both 64 and 32 bit bundled libraries. We check
7697            // here that the app declares multiArch support, and warn if it doesn't.
7698            //
7699            // We will be lenient here and record both ABIs. The primary will be the
7700            // ABI that's higher on the list, i.e, a device that's configured to prefer
7701            // 64 bit apps will see a 64 bit primary ABI,
7702
7703            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
7704                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
7705            }
7706
7707            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
7708                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7709                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7710            } else {
7711                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7712                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7713            }
7714        } else {
7715            pkg.applicationInfo.primaryCpuAbi = null;
7716            pkg.applicationInfo.secondaryCpuAbi = null;
7717        }
7718    }
7719
7720    private void killApplication(String pkgName, int appId, String reason) {
7721        // Request the ActivityManager to kill the process(only for existing packages)
7722        // so that we do not end up in a confused state while the user is still using the older
7723        // version of the application while the new one gets installed.
7724        IActivityManager am = ActivityManagerNative.getDefault();
7725        if (am != null) {
7726            try {
7727                am.killApplicationWithAppId(pkgName, appId, reason);
7728            } catch (RemoteException e) {
7729            }
7730        }
7731    }
7732
7733    void removePackageLI(PackageSetting ps, boolean chatty) {
7734        if (DEBUG_INSTALL) {
7735            if (chatty)
7736                Log.d(TAG, "Removing package " + ps.name);
7737        }
7738
7739        // writer
7740        synchronized (mPackages) {
7741            mPackages.remove(ps.name);
7742            final PackageParser.Package pkg = ps.pkg;
7743            if (pkg != null) {
7744                cleanPackageDataStructuresLILPw(pkg, chatty);
7745            }
7746        }
7747    }
7748
7749    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
7750        if (DEBUG_INSTALL) {
7751            if (chatty)
7752                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
7753        }
7754
7755        // writer
7756        synchronized (mPackages) {
7757            mPackages.remove(pkg.applicationInfo.packageName);
7758            cleanPackageDataStructuresLILPw(pkg, chatty);
7759        }
7760    }
7761
7762    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
7763        int N = pkg.providers.size();
7764        StringBuilder r = null;
7765        int i;
7766        for (i=0; i<N; i++) {
7767            PackageParser.Provider p = pkg.providers.get(i);
7768            mProviders.removeProvider(p);
7769            if (p.info.authority == null) {
7770
7771                /* There was another ContentProvider with this authority when
7772                 * this app was installed so this authority is null,
7773                 * Ignore it as we don't have to unregister the provider.
7774                 */
7775                continue;
7776            }
7777            String names[] = p.info.authority.split(";");
7778            for (int j = 0; j < names.length; j++) {
7779                if (mProvidersByAuthority.get(names[j]) == p) {
7780                    mProvidersByAuthority.remove(names[j]);
7781                    if (DEBUG_REMOVE) {
7782                        if (chatty)
7783                            Log.d(TAG, "Unregistered content provider: " + names[j]
7784                                    + ", className = " + p.info.name + ", isSyncable = "
7785                                    + p.info.isSyncable);
7786                    }
7787                }
7788            }
7789            if (DEBUG_REMOVE && chatty) {
7790                if (r == null) {
7791                    r = new StringBuilder(256);
7792                } else {
7793                    r.append(' ');
7794                }
7795                r.append(p.info.name);
7796            }
7797        }
7798        if (r != null) {
7799            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
7800        }
7801
7802        N = pkg.services.size();
7803        r = null;
7804        for (i=0; i<N; i++) {
7805            PackageParser.Service s = pkg.services.get(i);
7806            mServices.removeService(s);
7807            if (chatty) {
7808                if (r == null) {
7809                    r = new StringBuilder(256);
7810                } else {
7811                    r.append(' ');
7812                }
7813                r.append(s.info.name);
7814            }
7815        }
7816        if (r != null) {
7817            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
7818        }
7819
7820        N = pkg.receivers.size();
7821        r = null;
7822        for (i=0; i<N; i++) {
7823            PackageParser.Activity a = pkg.receivers.get(i);
7824            mReceivers.removeActivity(a, "receiver");
7825            if (DEBUG_REMOVE && chatty) {
7826                if (r == null) {
7827                    r = new StringBuilder(256);
7828                } else {
7829                    r.append(' ');
7830                }
7831                r.append(a.info.name);
7832            }
7833        }
7834        if (r != null) {
7835            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
7836        }
7837
7838        N = pkg.activities.size();
7839        r = null;
7840        for (i=0; i<N; i++) {
7841            PackageParser.Activity a = pkg.activities.get(i);
7842            mActivities.removeActivity(a, "activity");
7843            if (DEBUG_REMOVE && chatty) {
7844                if (r == null) {
7845                    r = new StringBuilder(256);
7846                } else {
7847                    r.append(' ');
7848                }
7849                r.append(a.info.name);
7850            }
7851        }
7852        if (r != null) {
7853            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
7854        }
7855
7856        N = pkg.permissions.size();
7857        r = null;
7858        for (i=0; i<N; i++) {
7859            PackageParser.Permission p = pkg.permissions.get(i);
7860            BasePermission bp = mSettings.mPermissions.get(p.info.name);
7861            if (bp == null) {
7862                bp = mSettings.mPermissionTrees.get(p.info.name);
7863            }
7864            if (bp != null && bp.perm == p) {
7865                bp.perm = null;
7866                if (DEBUG_REMOVE && chatty) {
7867                    if (r == null) {
7868                        r = new StringBuilder(256);
7869                    } else {
7870                        r.append(' ');
7871                    }
7872                    r.append(p.info.name);
7873                }
7874            }
7875            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7876                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
7877                if (appOpPerms != null) {
7878                    appOpPerms.remove(pkg.packageName);
7879                }
7880            }
7881        }
7882        if (r != null) {
7883            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
7884        }
7885
7886        N = pkg.requestedPermissions.size();
7887        r = null;
7888        for (i=0; i<N; i++) {
7889            String perm = pkg.requestedPermissions.get(i);
7890            BasePermission bp = mSettings.mPermissions.get(perm);
7891            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7892                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
7893                if (appOpPerms != null) {
7894                    appOpPerms.remove(pkg.packageName);
7895                    if (appOpPerms.isEmpty()) {
7896                        mAppOpPermissionPackages.remove(perm);
7897                    }
7898                }
7899            }
7900        }
7901        if (r != null) {
7902            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
7903        }
7904
7905        N = pkg.instrumentation.size();
7906        r = null;
7907        for (i=0; i<N; i++) {
7908            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7909            mInstrumentation.remove(a.getComponentName());
7910            if (DEBUG_REMOVE && chatty) {
7911                if (r == null) {
7912                    r = new StringBuilder(256);
7913                } else {
7914                    r.append(' ');
7915                }
7916                r.append(a.info.name);
7917            }
7918        }
7919        if (r != null) {
7920            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
7921        }
7922
7923        r = null;
7924        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7925            // Only system apps can hold shared libraries.
7926            if (pkg.libraryNames != null) {
7927                for (i=0; i<pkg.libraryNames.size(); i++) {
7928                    String name = pkg.libraryNames.get(i);
7929                    SharedLibraryEntry cur = mSharedLibraries.get(name);
7930                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
7931                        mSharedLibraries.remove(name);
7932                        if (DEBUG_REMOVE && chatty) {
7933                            if (r == null) {
7934                                r = new StringBuilder(256);
7935                            } else {
7936                                r.append(' ');
7937                            }
7938                            r.append(name);
7939                        }
7940                    }
7941                }
7942            }
7943        }
7944        if (r != null) {
7945            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
7946        }
7947    }
7948
7949    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
7950        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
7951            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
7952                return true;
7953            }
7954        }
7955        return false;
7956    }
7957
7958    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
7959    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
7960    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
7961
7962    private void updatePermissionsLPw(String changingPkg,
7963            PackageParser.Package pkgInfo, int flags) {
7964        // Make sure there are no dangling permission trees.
7965        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
7966        while (it.hasNext()) {
7967            final BasePermission bp = it.next();
7968            if (bp.packageSetting == null) {
7969                // We may not yet have parsed the package, so just see if
7970                // we still know about its settings.
7971                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
7972            }
7973            if (bp.packageSetting == null) {
7974                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
7975                        + " from package " + bp.sourcePackage);
7976                it.remove();
7977            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
7978                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
7979                    Slog.i(TAG, "Removing old permission tree: " + bp.name
7980                            + " from package " + bp.sourcePackage);
7981                    flags |= UPDATE_PERMISSIONS_ALL;
7982                    it.remove();
7983                }
7984            }
7985        }
7986
7987        // Make sure all dynamic permissions have been assigned to a package,
7988        // and make sure there are no dangling permissions.
7989        it = mSettings.mPermissions.values().iterator();
7990        while (it.hasNext()) {
7991            final BasePermission bp = it.next();
7992            if (bp.type == BasePermission.TYPE_DYNAMIC) {
7993                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
7994                        + bp.name + " pkg=" + bp.sourcePackage
7995                        + " info=" + bp.pendingInfo);
7996                if (bp.packageSetting == null && bp.pendingInfo != null) {
7997                    final BasePermission tree = findPermissionTreeLP(bp.name);
7998                    if (tree != null && tree.perm != null) {
7999                        bp.packageSetting = tree.packageSetting;
8000                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8001                                new PermissionInfo(bp.pendingInfo));
8002                        bp.perm.info.packageName = tree.perm.info.packageName;
8003                        bp.perm.info.name = bp.name;
8004                        bp.uid = tree.uid;
8005                    }
8006                }
8007            }
8008            if (bp.packageSetting == null) {
8009                // We may not yet have parsed the package, so just see if
8010                // we still know about its settings.
8011                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8012            }
8013            if (bp.packageSetting == null) {
8014                Slog.w(TAG, "Removing dangling permission: " + bp.name
8015                        + " from package " + bp.sourcePackage);
8016                it.remove();
8017            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8018                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8019                    Slog.i(TAG, "Removing old permission: " + bp.name
8020                            + " from package " + bp.sourcePackage);
8021                    flags |= UPDATE_PERMISSIONS_ALL;
8022                    it.remove();
8023                }
8024            }
8025        }
8026
8027        // Now update the permissions for all packages, in particular
8028        // replace the granted permissions of the system packages.
8029        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8030            for (PackageParser.Package pkg : mPackages.values()) {
8031                if (pkg != pkgInfo) {
8032                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
8033                            changingPkg);
8034                }
8035            }
8036        }
8037
8038        if (pkgInfo != null) {
8039            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
8040        }
8041    }
8042
8043    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8044            String packageOfInterest) {
8045        // IMPORTANT: There are two types of permissions: install and runtime.
8046        // Install time permissions are granted when the app is installed to
8047        // all device users and users added in the future. Runtime permissions
8048        // are granted at runtime explicitly to specific users. Normal and signature
8049        // protected permissions are install time permissions. Dangerous permissions
8050        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8051        // otherwise they are runtime permissions. This function does not manage
8052        // runtime permissions except for the case an app targeting Lollipop MR1
8053        // being upgraded to target a newer SDK, in which case dangerous permissions
8054        // are transformed from install time to runtime ones.
8055
8056        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8057        if (ps == null) {
8058            return;
8059        }
8060
8061        PermissionsState permissionsState = ps.getPermissionsState();
8062        PermissionsState origPermissions = permissionsState;
8063
8064        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8065
8066        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8067
8068        boolean changedInstallPermission = false;
8069
8070        if (replace) {
8071            ps.installPermissionsFixed = false;
8072            if (!ps.isSharedUser()) {
8073                origPermissions = new PermissionsState(permissionsState);
8074                permissionsState.reset();
8075            }
8076        }
8077
8078        permissionsState.setGlobalGids(mGlobalGids);
8079
8080        final int N = pkg.requestedPermissions.size();
8081        for (int i=0; i<N; i++) {
8082            final String name = pkg.requestedPermissions.get(i);
8083            final BasePermission bp = mSettings.mPermissions.get(name);
8084
8085            if (DEBUG_INSTALL) {
8086                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8087            }
8088
8089            if (bp == null || bp.packageSetting == null) {
8090                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8091                    Slog.w(TAG, "Unknown permission " + name
8092                            + " in package " + pkg.packageName);
8093                }
8094                continue;
8095            }
8096
8097            final String perm = bp.name;
8098            boolean allowedSig = false;
8099            int grant = GRANT_DENIED;
8100
8101            // Keep track of app op permissions.
8102            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8103                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8104                if (pkgs == null) {
8105                    pkgs = new ArraySet<>();
8106                    mAppOpPermissionPackages.put(bp.name, pkgs);
8107                }
8108                pkgs.add(pkg.packageName);
8109            }
8110
8111            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8112            switch (level) {
8113                case PermissionInfo.PROTECTION_NORMAL: {
8114                    // For all apps normal permissions are install time ones.
8115                    grant = GRANT_INSTALL;
8116                } break;
8117
8118                case PermissionInfo.PROTECTION_DANGEROUS: {
8119                    if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
8120                        // For legacy apps dangerous permissions are install time ones.
8121                        grant = GRANT_INSTALL_LEGACY;
8122                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8123                        // For legacy apps that became modern, install becomes runtime.
8124                        grant = GRANT_UPGRADE;
8125                    } else {
8126                        // For modern apps keep runtime permissions unchanged.
8127                        grant = GRANT_RUNTIME;
8128                    }
8129                } break;
8130
8131                case PermissionInfo.PROTECTION_SIGNATURE: {
8132                    // For all apps signature permissions are install time ones.
8133                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8134                    if (allowedSig) {
8135                        grant = GRANT_INSTALL;
8136                    }
8137                } break;
8138            }
8139
8140            if (DEBUG_INSTALL) {
8141                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8142            }
8143
8144            if (grant != GRANT_DENIED) {
8145                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8146                    // If this is an existing, non-system package, then
8147                    // we can't add any new permissions to it.
8148                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8149                        // Except...  if this is a permission that was added
8150                        // to the platform (note: need to only do this when
8151                        // updating the platform).
8152                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8153                            grant = GRANT_DENIED;
8154                        }
8155                    }
8156                }
8157
8158                switch (grant) {
8159                    case GRANT_INSTALL: {
8160                        // Revoke this as runtime permission to handle the case of
8161                        // a runtime permission being downgraded to an install one.
8162                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8163                            if (origPermissions.getRuntimePermissionState(
8164                                    bp.name, userId) != null) {
8165                                // Revoke the runtime permission and clear the flags.
8166                                origPermissions.revokeRuntimePermission(bp, userId);
8167                                origPermissions.updatePermissionFlags(bp, userId,
8168                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8169                                // If we revoked a permission permission, we have to write.
8170                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8171                                        changedRuntimePermissionUserIds, userId);
8172                            }
8173                        }
8174                        // Grant an install permission.
8175                        if (permissionsState.grantInstallPermission(bp) !=
8176                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8177                            changedInstallPermission = true;
8178                        }
8179                    } break;
8180
8181                    case GRANT_INSTALL_LEGACY: {
8182                        // Grant an install permission.
8183                        if (permissionsState.grantInstallPermission(bp) !=
8184                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8185                            changedInstallPermission = true;
8186                        }
8187                    } break;
8188
8189                    case GRANT_RUNTIME: {
8190                        // Grant previously granted runtime permissions.
8191                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8192                            PermissionState permissionState = origPermissions
8193                                    .getRuntimePermissionState(bp.name, userId);
8194                            final int flags = permissionState != null
8195                                    ? permissionState.getFlags() : 0;
8196                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8197                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8198                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8199                                    // If we cannot put the permission as it was, we have to write.
8200                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8201                                            changedRuntimePermissionUserIds, userId);
8202                                }
8203                            }
8204                            // Propagate the permission flags.
8205                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8206                        }
8207                    } break;
8208
8209                    case GRANT_UPGRADE: {
8210                        // Grant runtime permissions for a previously held install permission.
8211                        PermissionState permissionState = origPermissions
8212                                .getInstallPermissionState(bp.name);
8213                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8214
8215                        if (origPermissions.revokeInstallPermission(bp)
8216                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8217                            // We will be transferring the permission flags, so clear them.
8218                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8219                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8220                            changedInstallPermission = true;
8221                        }
8222
8223                        // If the permission is not to be promoted to runtime we ignore it and
8224                        // also its other flags as they are not applicable to install permissions.
8225                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8226                            for (int userId : currentUserIds) {
8227                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8228                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8229                                    // Transfer the permission flags.
8230                                    permissionsState.updatePermissionFlags(bp, userId,
8231                                            flags, flags);
8232                                    // If we granted the permission, we have to write.
8233                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8234                                            changedRuntimePermissionUserIds, userId);
8235                                }
8236                            }
8237                        }
8238                    } break;
8239
8240                    default: {
8241                        if (packageOfInterest == null
8242                                || packageOfInterest.equals(pkg.packageName)) {
8243                            Slog.w(TAG, "Not granting permission " + perm
8244                                    + " to package " + pkg.packageName
8245                                    + " because it was previously installed without");
8246                        }
8247                    } break;
8248                }
8249            } else {
8250                if (permissionsState.revokeInstallPermission(bp) !=
8251                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8252                    // Also drop the permission flags.
8253                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8254                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8255                    changedInstallPermission = true;
8256                    Slog.i(TAG, "Un-granting permission " + perm
8257                            + " from package " + pkg.packageName
8258                            + " (protectionLevel=" + bp.protectionLevel
8259                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8260                            + ")");
8261                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8262                    // Don't print warning for app op permissions, since it is fine for them
8263                    // not to be granted, there is a UI for the user to decide.
8264                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8265                        Slog.w(TAG, "Not granting permission " + perm
8266                                + " to package " + pkg.packageName
8267                                + " (protectionLevel=" + bp.protectionLevel
8268                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8269                                + ")");
8270                    }
8271                }
8272            }
8273        }
8274
8275        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8276                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8277            // This is the first that we have heard about this package, so the
8278            // permissions we have now selected are fixed until explicitly
8279            // changed.
8280            ps.installPermissionsFixed = true;
8281        }
8282
8283        // Persist the runtime permissions state for users with changes.
8284        for (int userId : changedRuntimePermissionUserIds) {
8285            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
8286        }
8287    }
8288
8289    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8290        boolean allowed = false;
8291        final int NP = PackageParser.NEW_PERMISSIONS.length;
8292        for (int ip=0; ip<NP; ip++) {
8293            final PackageParser.NewPermissionInfo npi
8294                    = PackageParser.NEW_PERMISSIONS[ip];
8295            if (npi.name.equals(perm)
8296                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8297                allowed = true;
8298                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8299                        + pkg.packageName);
8300                break;
8301            }
8302        }
8303        return allowed;
8304    }
8305
8306    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8307            BasePermission bp, PermissionsState origPermissions) {
8308        boolean allowed;
8309        allowed = (compareSignatures(
8310                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8311                        == PackageManager.SIGNATURE_MATCH)
8312                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8313                        == PackageManager.SIGNATURE_MATCH);
8314        if (!allowed && (bp.protectionLevel
8315                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
8316            if (isSystemApp(pkg)) {
8317                // For updated system applications, a system permission
8318                // is granted only if it had been defined by the original application.
8319                if (pkg.isUpdatedSystemApp()) {
8320                    final PackageSetting sysPs = mSettings
8321                            .getDisabledSystemPkgLPr(pkg.packageName);
8322                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8323                        // If the original was granted this permission, we take
8324                        // that grant decision as read and propagate it to the
8325                        // update.
8326                        if (sysPs.isPrivileged()) {
8327                            allowed = true;
8328                        }
8329                    } else {
8330                        // The system apk may have been updated with an older
8331                        // version of the one on the data partition, but which
8332                        // granted a new system permission that it didn't have
8333                        // before.  In this case we do want to allow the app to
8334                        // now get the new permission if the ancestral apk is
8335                        // privileged to get it.
8336                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
8337                            for (int j=0;
8338                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
8339                                if (perm.equals(
8340                                        sysPs.pkg.requestedPermissions.get(j))) {
8341                                    allowed = true;
8342                                    break;
8343                                }
8344                            }
8345                        }
8346                    }
8347                } else {
8348                    allowed = isPrivilegedApp(pkg);
8349                }
8350            }
8351        }
8352        if (!allowed && (bp.protectionLevel
8353                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8354            // For development permissions, a development permission
8355            // is granted only if it was already granted.
8356            allowed = origPermissions.hasInstallPermission(perm);
8357        }
8358        return allowed;
8359    }
8360
8361    final class ActivityIntentResolver
8362            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8363        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8364                boolean defaultOnly, int userId) {
8365            if (!sUserManager.exists(userId)) return null;
8366            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8367            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8368        }
8369
8370        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8371                int userId) {
8372            if (!sUserManager.exists(userId)) return null;
8373            mFlags = flags;
8374            return super.queryIntent(intent, resolvedType,
8375                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8376        }
8377
8378        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8379                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8380            if (!sUserManager.exists(userId)) return null;
8381            if (packageActivities == null) {
8382                return null;
8383            }
8384            mFlags = flags;
8385            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8386            final int N = packageActivities.size();
8387            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8388                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8389
8390            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8391            for (int i = 0; i < N; ++i) {
8392                intentFilters = packageActivities.get(i).intents;
8393                if (intentFilters != null && intentFilters.size() > 0) {
8394                    PackageParser.ActivityIntentInfo[] array =
8395                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
8396                    intentFilters.toArray(array);
8397                    listCut.add(array);
8398                }
8399            }
8400            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8401        }
8402
8403        public final void addActivity(PackageParser.Activity a, String type) {
8404            final boolean systemApp = a.info.applicationInfo.isSystemApp();
8405            mActivities.put(a.getComponentName(), a);
8406            if (DEBUG_SHOW_INFO)
8407                Log.v(
8408                TAG, "  " + type + " " +
8409                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8410            if (DEBUG_SHOW_INFO)
8411                Log.v(TAG, "    Class=" + a.info.name);
8412            final int NI = a.intents.size();
8413            for (int j=0; j<NI; j++) {
8414                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8415                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
8416                    intent.setPriority(0);
8417                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
8418                            + a.className + " with priority > 0, forcing to 0");
8419                }
8420                if (DEBUG_SHOW_INFO) {
8421                    Log.v(TAG, "    IntentFilter:");
8422                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8423                }
8424                if (!intent.debugCheck()) {
8425                    Log.w(TAG, "==> For Activity " + a.info.name);
8426                }
8427                addFilter(intent);
8428            }
8429        }
8430
8431        public final void removeActivity(PackageParser.Activity a, String type) {
8432            mActivities.remove(a.getComponentName());
8433            if (DEBUG_SHOW_INFO) {
8434                Log.v(TAG, "  " + type + " "
8435                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
8436                                : a.info.name) + ":");
8437                Log.v(TAG, "    Class=" + a.info.name);
8438            }
8439            final int NI = a.intents.size();
8440            for (int j=0; j<NI; j++) {
8441                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8442                if (DEBUG_SHOW_INFO) {
8443                    Log.v(TAG, "    IntentFilter:");
8444                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8445                }
8446                removeFilter(intent);
8447            }
8448        }
8449
8450        @Override
8451        protected boolean allowFilterResult(
8452                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
8453            ActivityInfo filterAi = filter.activity.info;
8454            for (int i=dest.size()-1; i>=0; i--) {
8455                ActivityInfo destAi = dest.get(i).activityInfo;
8456                if (destAi.name == filterAi.name
8457                        && destAi.packageName == filterAi.packageName) {
8458                    return false;
8459                }
8460            }
8461            return true;
8462        }
8463
8464        @Override
8465        protected ActivityIntentInfo[] newArray(int size) {
8466            return new ActivityIntentInfo[size];
8467        }
8468
8469        @Override
8470        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
8471            if (!sUserManager.exists(userId)) return true;
8472            PackageParser.Package p = filter.activity.owner;
8473            if (p != null) {
8474                PackageSetting ps = (PackageSetting)p.mExtras;
8475                if (ps != null) {
8476                    // System apps are never considered stopped for purposes of
8477                    // filtering, because there may be no way for the user to
8478                    // actually re-launch them.
8479                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
8480                            && ps.getStopped(userId);
8481                }
8482            }
8483            return false;
8484        }
8485
8486        @Override
8487        protected boolean isPackageForFilter(String packageName,
8488                PackageParser.ActivityIntentInfo info) {
8489            return packageName.equals(info.activity.owner.packageName);
8490        }
8491
8492        @Override
8493        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
8494                int match, int userId) {
8495            if (!sUserManager.exists(userId)) return null;
8496            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
8497                return null;
8498            }
8499            final PackageParser.Activity activity = info.activity;
8500            if (mSafeMode && (activity.info.applicationInfo.flags
8501                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8502                return null;
8503            }
8504            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
8505            if (ps == null) {
8506                return null;
8507            }
8508            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
8509                    ps.readUserState(userId), userId);
8510            if (ai == null) {
8511                return null;
8512            }
8513            final ResolveInfo res = new ResolveInfo();
8514            res.activityInfo = ai;
8515            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8516                res.filter = info;
8517            }
8518            if (info != null) {
8519                res.handleAllWebDataURI = info.handleAllWebDataURI();
8520            }
8521            res.priority = info.getPriority();
8522            res.preferredOrder = activity.owner.mPreferredOrder;
8523            //System.out.println("Result: " + res.activityInfo.className +
8524            //                   " = " + res.priority);
8525            res.match = match;
8526            res.isDefault = info.hasDefault;
8527            res.labelRes = info.labelRes;
8528            res.nonLocalizedLabel = info.nonLocalizedLabel;
8529            if (userNeedsBadging(userId)) {
8530                res.noResourceId = true;
8531            } else {
8532                res.icon = info.icon;
8533            }
8534            res.iconResourceId = info.icon;
8535            res.system = res.activityInfo.applicationInfo.isSystemApp();
8536            return res;
8537        }
8538
8539        @Override
8540        protected void sortResults(List<ResolveInfo> results) {
8541            Collections.sort(results, mResolvePrioritySorter);
8542        }
8543
8544        @Override
8545        protected void dumpFilter(PrintWriter out, String prefix,
8546                PackageParser.ActivityIntentInfo filter) {
8547            out.print(prefix); out.print(
8548                    Integer.toHexString(System.identityHashCode(filter.activity)));
8549                    out.print(' ');
8550                    filter.activity.printComponentShortName(out);
8551                    out.print(" filter ");
8552                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8553        }
8554
8555        @Override
8556        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
8557            return filter.activity;
8558        }
8559
8560        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8561            PackageParser.Activity activity = (PackageParser.Activity)label;
8562            out.print(prefix); out.print(
8563                    Integer.toHexString(System.identityHashCode(activity)));
8564                    out.print(' ');
8565                    activity.printComponentShortName(out);
8566            if (count > 1) {
8567                out.print(" ("); out.print(count); out.print(" filters)");
8568            }
8569            out.println();
8570        }
8571
8572//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8573//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8574//            final List<ResolveInfo> retList = Lists.newArrayList();
8575//            while (i.hasNext()) {
8576//                final ResolveInfo resolveInfo = i.next();
8577//                if (isEnabledLP(resolveInfo.activityInfo)) {
8578//                    retList.add(resolveInfo);
8579//                }
8580//            }
8581//            return retList;
8582//        }
8583
8584        // Keys are String (activity class name), values are Activity.
8585        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
8586                = new ArrayMap<ComponentName, PackageParser.Activity>();
8587        private int mFlags;
8588    }
8589
8590    private final class ServiceIntentResolver
8591            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
8592        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8593                boolean defaultOnly, int userId) {
8594            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8595            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8596        }
8597
8598        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8599                int userId) {
8600            if (!sUserManager.exists(userId)) return null;
8601            mFlags = flags;
8602            return super.queryIntent(intent, resolvedType,
8603                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8604        }
8605
8606        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8607                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
8608            if (!sUserManager.exists(userId)) return null;
8609            if (packageServices == null) {
8610                return null;
8611            }
8612            mFlags = flags;
8613            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8614            final int N = packageServices.size();
8615            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
8616                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
8617
8618            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
8619            for (int i = 0; i < N; ++i) {
8620                intentFilters = packageServices.get(i).intents;
8621                if (intentFilters != null && intentFilters.size() > 0) {
8622                    PackageParser.ServiceIntentInfo[] array =
8623                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
8624                    intentFilters.toArray(array);
8625                    listCut.add(array);
8626                }
8627            }
8628            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8629        }
8630
8631        public final void addService(PackageParser.Service s) {
8632            mServices.put(s.getComponentName(), s);
8633            if (DEBUG_SHOW_INFO) {
8634                Log.v(TAG, "  "
8635                        + (s.info.nonLocalizedLabel != null
8636                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8637                Log.v(TAG, "    Class=" + s.info.name);
8638            }
8639            final int NI = s.intents.size();
8640            int j;
8641            for (j=0; j<NI; j++) {
8642                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8643                if (DEBUG_SHOW_INFO) {
8644                    Log.v(TAG, "    IntentFilter:");
8645                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8646                }
8647                if (!intent.debugCheck()) {
8648                    Log.w(TAG, "==> For Service " + s.info.name);
8649                }
8650                addFilter(intent);
8651            }
8652        }
8653
8654        public final void removeService(PackageParser.Service s) {
8655            mServices.remove(s.getComponentName());
8656            if (DEBUG_SHOW_INFO) {
8657                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
8658                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8659                Log.v(TAG, "    Class=" + s.info.name);
8660            }
8661            final int NI = s.intents.size();
8662            int j;
8663            for (j=0; j<NI; j++) {
8664                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8665                if (DEBUG_SHOW_INFO) {
8666                    Log.v(TAG, "    IntentFilter:");
8667                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8668                }
8669                removeFilter(intent);
8670            }
8671        }
8672
8673        @Override
8674        protected boolean allowFilterResult(
8675                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
8676            ServiceInfo filterSi = filter.service.info;
8677            for (int i=dest.size()-1; i>=0; i--) {
8678                ServiceInfo destAi = dest.get(i).serviceInfo;
8679                if (destAi.name == filterSi.name
8680                        && destAi.packageName == filterSi.packageName) {
8681                    return false;
8682                }
8683            }
8684            return true;
8685        }
8686
8687        @Override
8688        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
8689            return new PackageParser.ServiceIntentInfo[size];
8690        }
8691
8692        @Override
8693        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
8694            if (!sUserManager.exists(userId)) return true;
8695            PackageParser.Package p = filter.service.owner;
8696            if (p != null) {
8697                PackageSetting ps = (PackageSetting)p.mExtras;
8698                if (ps != null) {
8699                    // System apps are never considered stopped for purposes of
8700                    // filtering, because there may be no way for the user to
8701                    // actually re-launch them.
8702                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8703                            && ps.getStopped(userId);
8704                }
8705            }
8706            return false;
8707        }
8708
8709        @Override
8710        protected boolean isPackageForFilter(String packageName,
8711                PackageParser.ServiceIntentInfo info) {
8712            return packageName.equals(info.service.owner.packageName);
8713        }
8714
8715        @Override
8716        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
8717                int match, int userId) {
8718            if (!sUserManager.exists(userId)) return null;
8719            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
8720            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
8721                return null;
8722            }
8723            final PackageParser.Service service = info.service;
8724            if (mSafeMode && (service.info.applicationInfo.flags
8725                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8726                return null;
8727            }
8728            PackageSetting ps = (PackageSetting) service.owner.mExtras;
8729            if (ps == null) {
8730                return null;
8731            }
8732            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
8733                    ps.readUserState(userId), userId);
8734            if (si == null) {
8735                return null;
8736            }
8737            final ResolveInfo res = new ResolveInfo();
8738            res.serviceInfo = si;
8739            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8740                res.filter = filter;
8741            }
8742            res.priority = info.getPriority();
8743            res.preferredOrder = service.owner.mPreferredOrder;
8744            res.match = match;
8745            res.isDefault = info.hasDefault;
8746            res.labelRes = info.labelRes;
8747            res.nonLocalizedLabel = info.nonLocalizedLabel;
8748            res.icon = info.icon;
8749            res.system = res.serviceInfo.applicationInfo.isSystemApp();
8750            return res;
8751        }
8752
8753        @Override
8754        protected void sortResults(List<ResolveInfo> results) {
8755            Collections.sort(results, mResolvePrioritySorter);
8756        }
8757
8758        @Override
8759        protected void dumpFilter(PrintWriter out, String prefix,
8760                PackageParser.ServiceIntentInfo filter) {
8761            out.print(prefix); out.print(
8762                    Integer.toHexString(System.identityHashCode(filter.service)));
8763                    out.print(' ');
8764                    filter.service.printComponentShortName(out);
8765                    out.print(" filter ");
8766                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8767        }
8768
8769        @Override
8770        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
8771            return filter.service;
8772        }
8773
8774        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8775            PackageParser.Service service = (PackageParser.Service)label;
8776            out.print(prefix); out.print(
8777                    Integer.toHexString(System.identityHashCode(service)));
8778                    out.print(' ');
8779                    service.printComponentShortName(out);
8780            if (count > 1) {
8781                out.print(" ("); out.print(count); out.print(" filters)");
8782            }
8783            out.println();
8784        }
8785
8786//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8787//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8788//            final List<ResolveInfo> retList = Lists.newArrayList();
8789//            while (i.hasNext()) {
8790//                final ResolveInfo resolveInfo = (ResolveInfo) i;
8791//                if (isEnabledLP(resolveInfo.serviceInfo)) {
8792//                    retList.add(resolveInfo);
8793//                }
8794//            }
8795//            return retList;
8796//        }
8797
8798        // Keys are String (activity class name), values are Activity.
8799        private final ArrayMap<ComponentName, PackageParser.Service> mServices
8800                = new ArrayMap<ComponentName, PackageParser.Service>();
8801        private int mFlags;
8802    };
8803
8804    private final class ProviderIntentResolver
8805            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
8806        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8807                boolean defaultOnly, int userId) {
8808            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8809            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8810        }
8811
8812        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8813                int userId) {
8814            if (!sUserManager.exists(userId))
8815                return null;
8816            mFlags = flags;
8817            return super.queryIntent(intent, resolvedType,
8818                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8819        }
8820
8821        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8822                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
8823            if (!sUserManager.exists(userId))
8824                return null;
8825            if (packageProviders == null) {
8826                return null;
8827            }
8828            mFlags = flags;
8829            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
8830            final int N = packageProviders.size();
8831            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
8832                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
8833
8834            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
8835            for (int i = 0; i < N; ++i) {
8836                intentFilters = packageProviders.get(i).intents;
8837                if (intentFilters != null && intentFilters.size() > 0) {
8838                    PackageParser.ProviderIntentInfo[] array =
8839                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
8840                    intentFilters.toArray(array);
8841                    listCut.add(array);
8842                }
8843            }
8844            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8845        }
8846
8847        public final void addProvider(PackageParser.Provider p) {
8848            if (mProviders.containsKey(p.getComponentName())) {
8849                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
8850                return;
8851            }
8852
8853            mProviders.put(p.getComponentName(), p);
8854            if (DEBUG_SHOW_INFO) {
8855                Log.v(TAG, "  "
8856                        + (p.info.nonLocalizedLabel != null
8857                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
8858                Log.v(TAG, "    Class=" + p.info.name);
8859            }
8860            final int NI = p.intents.size();
8861            int j;
8862            for (j = 0; j < NI; j++) {
8863                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
8864                if (DEBUG_SHOW_INFO) {
8865                    Log.v(TAG, "    IntentFilter:");
8866                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8867                }
8868                if (!intent.debugCheck()) {
8869                    Log.w(TAG, "==> For Provider " + p.info.name);
8870                }
8871                addFilter(intent);
8872            }
8873        }
8874
8875        public final void removeProvider(PackageParser.Provider p) {
8876            mProviders.remove(p.getComponentName());
8877            if (DEBUG_SHOW_INFO) {
8878                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
8879                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
8880                Log.v(TAG, "    Class=" + p.info.name);
8881            }
8882            final int NI = p.intents.size();
8883            int j;
8884            for (j = 0; j < NI; j++) {
8885                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
8886                if (DEBUG_SHOW_INFO) {
8887                    Log.v(TAG, "    IntentFilter:");
8888                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8889                }
8890                removeFilter(intent);
8891            }
8892        }
8893
8894        @Override
8895        protected boolean allowFilterResult(
8896                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
8897            ProviderInfo filterPi = filter.provider.info;
8898            for (int i = dest.size() - 1; i >= 0; i--) {
8899                ProviderInfo destPi = dest.get(i).providerInfo;
8900                if (destPi.name == filterPi.name
8901                        && destPi.packageName == filterPi.packageName) {
8902                    return false;
8903                }
8904            }
8905            return true;
8906        }
8907
8908        @Override
8909        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
8910            return new PackageParser.ProviderIntentInfo[size];
8911        }
8912
8913        @Override
8914        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
8915            if (!sUserManager.exists(userId))
8916                return true;
8917            PackageParser.Package p = filter.provider.owner;
8918            if (p != null) {
8919                PackageSetting ps = (PackageSetting) p.mExtras;
8920                if (ps != null) {
8921                    // System apps are never considered stopped for purposes of
8922                    // filtering, because there may be no way for the user to
8923                    // actually re-launch them.
8924                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8925                            && ps.getStopped(userId);
8926                }
8927            }
8928            return false;
8929        }
8930
8931        @Override
8932        protected boolean isPackageForFilter(String packageName,
8933                PackageParser.ProviderIntentInfo info) {
8934            return packageName.equals(info.provider.owner.packageName);
8935        }
8936
8937        @Override
8938        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
8939                int match, int userId) {
8940            if (!sUserManager.exists(userId))
8941                return null;
8942            final PackageParser.ProviderIntentInfo info = filter;
8943            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
8944                return null;
8945            }
8946            final PackageParser.Provider provider = info.provider;
8947            if (mSafeMode && (provider.info.applicationInfo.flags
8948                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
8949                return null;
8950            }
8951            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
8952            if (ps == null) {
8953                return null;
8954            }
8955            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
8956                    ps.readUserState(userId), userId);
8957            if (pi == null) {
8958                return null;
8959            }
8960            final ResolveInfo res = new ResolveInfo();
8961            res.providerInfo = pi;
8962            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
8963                res.filter = filter;
8964            }
8965            res.priority = info.getPriority();
8966            res.preferredOrder = provider.owner.mPreferredOrder;
8967            res.match = match;
8968            res.isDefault = info.hasDefault;
8969            res.labelRes = info.labelRes;
8970            res.nonLocalizedLabel = info.nonLocalizedLabel;
8971            res.icon = info.icon;
8972            res.system = res.providerInfo.applicationInfo.isSystemApp();
8973            return res;
8974        }
8975
8976        @Override
8977        protected void sortResults(List<ResolveInfo> results) {
8978            Collections.sort(results, mResolvePrioritySorter);
8979        }
8980
8981        @Override
8982        protected void dumpFilter(PrintWriter out, String prefix,
8983                PackageParser.ProviderIntentInfo filter) {
8984            out.print(prefix);
8985            out.print(
8986                    Integer.toHexString(System.identityHashCode(filter.provider)));
8987            out.print(' ');
8988            filter.provider.printComponentShortName(out);
8989            out.print(" filter ");
8990            out.println(Integer.toHexString(System.identityHashCode(filter)));
8991        }
8992
8993        @Override
8994        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
8995            return filter.provider;
8996        }
8997
8998        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8999            PackageParser.Provider provider = (PackageParser.Provider)label;
9000            out.print(prefix); out.print(
9001                    Integer.toHexString(System.identityHashCode(provider)));
9002                    out.print(' ');
9003                    provider.printComponentShortName(out);
9004            if (count > 1) {
9005                out.print(" ("); out.print(count); out.print(" filters)");
9006            }
9007            out.println();
9008        }
9009
9010        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9011                = new ArrayMap<ComponentName, PackageParser.Provider>();
9012        private int mFlags;
9013    };
9014
9015    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9016            new Comparator<ResolveInfo>() {
9017        public int compare(ResolveInfo r1, ResolveInfo r2) {
9018            int v1 = r1.priority;
9019            int v2 = r2.priority;
9020            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9021            if (v1 != v2) {
9022                return (v1 > v2) ? -1 : 1;
9023            }
9024            v1 = r1.preferredOrder;
9025            v2 = r2.preferredOrder;
9026            if (v1 != v2) {
9027                return (v1 > v2) ? -1 : 1;
9028            }
9029            if (r1.isDefault != r2.isDefault) {
9030                return r1.isDefault ? -1 : 1;
9031            }
9032            v1 = r1.match;
9033            v2 = r2.match;
9034            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9035            if (v1 != v2) {
9036                return (v1 > v2) ? -1 : 1;
9037            }
9038            if (r1.system != r2.system) {
9039                return r1.system ? -1 : 1;
9040            }
9041            return 0;
9042        }
9043    };
9044
9045    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9046            new Comparator<ProviderInfo>() {
9047        public int compare(ProviderInfo p1, ProviderInfo p2) {
9048            final int v1 = p1.initOrder;
9049            final int v2 = p2.initOrder;
9050            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9051        }
9052    };
9053
9054    final void sendPackageBroadcast(final String action, final String pkg,
9055            final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
9056            final int[] userIds) {
9057        mHandler.post(new Runnable() {
9058            @Override
9059            public void run() {
9060                try {
9061                    final IActivityManager am = ActivityManagerNative.getDefault();
9062                    if (am == null) return;
9063                    final int[] resolvedUserIds;
9064                    if (userIds == null) {
9065                        resolvedUserIds = am.getRunningUserIds();
9066                    } else {
9067                        resolvedUserIds = userIds;
9068                    }
9069                    for (int id : resolvedUserIds) {
9070                        final Intent intent = new Intent(action,
9071                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9072                        if (extras != null) {
9073                            intent.putExtras(extras);
9074                        }
9075                        if (targetPkg != null) {
9076                            intent.setPackage(targetPkg);
9077                        }
9078                        // Modify the UID when posting to other users
9079                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9080                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9081                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9082                            intent.putExtra(Intent.EXTRA_UID, uid);
9083                        }
9084                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9085                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
9086                        if (DEBUG_BROADCASTS) {
9087                            RuntimeException here = new RuntimeException("here");
9088                            here.fillInStackTrace();
9089                            Slog.d(TAG, "Sending to user " + id + ": "
9090                                    + intent.toShortString(false, true, false, false)
9091                                    + " " + intent.getExtras(), here);
9092                        }
9093                        am.broadcastIntent(null, intent, null, finishedReceiver,
9094                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9095                                null, finishedReceiver != null, false, id);
9096                    }
9097                } catch (RemoteException ex) {
9098                }
9099            }
9100        });
9101    }
9102
9103    /**
9104     * Check if the external storage media is available. This is true if there
9105     * is a mounted external storage medium or if the external storage is
9106     * emulated.
9107     */
9108    private boolean isExternalMediaAvailable() {
9109        return mMediaMounted || Environment.isExternalStorageEmulated();
9110    }
9111
9112    @Override
9113    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9114        // writer
9115        synchronized (mPackages) {
9116            if (!isExternalMediaAvailable()) {
9117                // If the external storage is no longer mounted at this point,
9118                // the caller may not have been able to delete all of this
9119                // packages files and can not delete any more.  Bail.
9120                return null;
9121            }
9122            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9123            if (lastPackage != null) {
9124                pkgs.remove(lastPackage);
9125            }
9126            if (pkgs.size() > 0) {
9127                return pkgs.get(0);
9128            }
9129        }
9130        return null;
9131    }
9132
9133    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9134        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9135                userId, andCode ? 1 : 0, packageName);
9136        if (mSystemReady) {
9137            msg.sendToTarget();
9138        } else {
9139            if (mPostSystemReadyMessages == null) {
9140                mPostSystemReadyMessages = new ArrayList<>();
9141            }
9142            mPostSystemReadyMessages.add(msg);
9143        }
9144    }
9145
9146    void startCleaningPackages() {
9147        // reader
9148        synchronized (mPackages) {
9149            if (!isExternalMediaAvailable()) {
9150                return;
9151            }
9152            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9153                return;
9154            }
9155        }
9156        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9157        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9158        IActivityManager am = ActivityManagerNative.getDefault();
9159        if (am != null) {
9160            try {
9161                am.startService(null, intent, null, UserHandle.USER_OWNER);
9162            } catch (RemoteException e) {
9163            }
9164        }
9165    }
9166
9167    @Override
9168    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9169            int installFlags, String installerPackageName, VerificationParams verificationParams,
9170            String packageAbiOverride) {
9171        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9172                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9173    }
9174
9175    @Override
9176    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9177            int installFlags, String installerPackageName, VerificationParams verificationParams,
9178            String packageAbiOverride, int userId) {
9179        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9180
9181        final int callingUid = Binder.getCallingUid();
9182        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9183
9184        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9185            try {
9186                if (observer != null) {
9187                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9188                }
9189            } catch (RemoteException re) {
9190            }
9191            return;
9192        }
9193
9194        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9195            installFlags |= PackageManager.INSTALL_FROM_ADB;
9196
9197        } else {
9198            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9199            // about installerPackageName.
9200
9201            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9202            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9203        }
9204
9205        UserHandle user;
9206        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9207            user = UserHandle.ALL;
9208        } else {
9209            user = new UserHandle(userId);
9210        }
9211
9212        // Only system components can circumvent runtime permissions when installing.
9213        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9214                && mContext.checkCallingOrSelfPermission(Manifest.permission
9215                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9216            throw new SecurityException("You need the "
9217                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9218                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9219        }
9220
9221        verificationParams.setInstallerUid(callingUid);
9222
9223        final File originFile = new File(originPath);
9224        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9225
9226        final Message msg = mHandler.obtainMessage(INIT_COPY);
9227        msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName,
9228                null, verificationParams, user, packageAbiOverride);
9229        mHandler.sendMessage(msg);
9230    }
9231
9232    void installStage(String packageName, File stagedDir, String stagedCid,
9233            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
9234            String installerPackageName, int installerUid, UserHandle user) {
9235        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
9236                params.referrerUri, installerUid, null);
9237        verifParams.setInstallerUid(installerUid);
9238
9239        final OriginInfo origin;
9240        if (stagedDir != null) {
9241            origin = OriginInfo.fromStagedFile(stagedDir);
9242        } else {
9243            origin = OriginInfo.fromStagedContainer(stagedCid);
9244        }
9245
9246        final Message msg = mHandler.obtainMessage(INIT_COPY);
9247        msg.obj = new InstallParams(origin, null, observer, params.installFlags,
9248                installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride);
9249        mHandler.sendMessage(msg);
9250    }
9251
9252    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
9253        Bundle extras = new Bundle(1);
9254        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
9255
9256        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
9257                packageName, extras, null, null, new int[] {userId});
9258        try {
9259            IActivityManager am = ActivityManagerNative.getDefault();
9260            final boolean isSystem =
9261                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
9262            if (isSystem && am.isUserRunning(userId, false)) {
9263                // The just-installed/enabled app is bundled on the system, so presumed
9264                // to be able to run automatically without needing an explicit launch.
9265                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
9266                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
9267                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
9268                        .setPackage(packageName);
9269                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
9270                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
9271            }
9272        } catch (RemoteException e) {
9273            // shouldn't happen
9274            Slog.w(TAG, "Unable to bootstrap installed package", e);
9275        }
9276    }
9277
9278    @Override
9279    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9280            int userId) {
9281        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9282        PackageSetting pkgSetting;
9283        final int uid = Binder.getCallingUid();
9284        enforceCrossUserPermission(uid, userId, true, true,
9285                "setApplicationHiddenSetting for user " + userId);
9286
9287        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9288            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9289            return false;
9290        }
9291
9292        long callingId = Binder.clearCallingIdentity();
9293        try {
9294            boolean sendAdded = false;
9295            boolean sendRemoved = false;
9296            // writer
9297            synchronized (mPackages) {
9298                pkgSetting = mSettings.mPackages.get(packageName);
9299                if (pkgSetting == null) {
9300                    return false;
9301                }
9302                if (pkgSetting.getHidden(userId) != hidden) {
9303                    pkgSetting.setHidden(hidden, userId);
9304                    mSettings.writePackageRestrictionsLPr(userId);
9305                    if (hidden) {
9306                        sendRemoved = true;
9307                    } else {
9308                        sendAdded = true;
9309                    }
9310                }
9311            }
9312            if (sendAdded) {
9313                sendPackageAddedForUser(packageName, pkgSetting, userId);
9314                return true;
9315            }
9316            if (sendRemoved) {
9317                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
9318                        "hiding pkg");
9319                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
9320            }
9321        } finally {
9322            Binder.restoreCallingIdentity(callingId);
9323        }
9324        return false;
9325    }
9326
9327    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9328            int userId) {
9329        final PackageRemovedInfo info = new PackageRemovedInfo();
9330        info.removedPackage = packageName;
9331        info.removedUsers = new int[] {userId};
9332        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9333        info.sendBroadcast(false, false, false);
9334    }
9335
9336    /**
9337     * Returns true if application is not found or there was an error. Otherwise it returns
9338     * the hidden state of the package for the given user.
9339     */
9340    @Override
9341    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9342        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9343        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9344                false, "getApplicationHidden for user " + userId);
9345        PackageSetting pkgSetting;
9346        long callingId = Binder.clearCallingIdentity();
9347        try {
9348            // writer
9349            synchronized (mPackages) {
9350                pkgSetting = mSettings.mPackages.get(packageName);
9351                if (pkgSetting == null) {
9352                    return true;
9353                }
9354                return pkgSetting.getHidden(userId);
9355            }
9356        } finally {
9357            Binder.restoreCallingIdentity(callingId);
9358        }
9359    }
9360
9361    /**
9362     * @hide
9363     */
9364    @Override
9365    public int installExistingPackageAsUser(String packageName, int userId) {
9366        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9367                null);
9368        PackageSetting pkgSetting;
9369        final int uid = Binder.getCallingUid();
9370        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9371                + userId);
9372        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9373            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9374        }
9375
9376        long callingId = Binder.clearCallingIdentity();
9377        try {
9378            boolean sendAdded = false;
9379
9380            // writer
9381            synchronized (mPackages) {
9382                pkgSetting = mSettings.mPackages.get(packageName);
9383                if (pkgSetting == null) {
9384                    return PackageManager.INSTALL_FAILED_INVALID_URI;
9385                }
9386                if (!pkgSetting.getInstalled(userId)) {
9387                    pkgSetting.setInstalled(true, userId);
9388                    pkgSetting.setHidden(false, userId);
9389                    mSettings.writePackageRestrictionsLPr(userId);
9390                    sendAdded = true;
9391                }
9392            }
9393
9394            if (sendAdded) {
9395                sendPackageAddedForUser(packageName, pkgSetting, userId);
9396            }
9397        } finally {
9398            Binder.restoreCallingIdentity(callingId);
9399        }
9400
9401        return PackageManager.INSTALL_SUCCEEDED;
9402    }
9403
9404    boolean isUserRestricted(int userId, String restrictionKey) {
9405        Bundle restrictions = sUserManager.getUserRestrictions(userId);
9406        if (restrictions.getBoolean(restrictionKey, false)) {
9407            Log.w(TAG, "User is restricted: " + restrictionKey);
9408            return true;
9409        }
9410        return false;
9411    }
9412
9413    @Override
9414    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
9415        mContext.enforceCallingOrSelfPermission(
9416                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9417                "Only package verification agents can verify applications");
9418
9419        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9420        final PackageVerificationResponse response = new PackageVerificationResponse(
9421                verificationCode, Binder.getCallingUid());
9422        msg.arg1 = id;
9423        msg.obj = response;
9424        mHandler.sendMessage(msg);
9425    }
9426
9427    @Override
9428    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
9429            long millisecondsToDelay) {
9430        mContext.enforceCallingOrSelfPermission(
9431                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9432                "Only package verification agents can extend verification timeouts");
9433
9434        final PackageVerificationState state = mPendingVerification.get(id);
9435        final PackageVerificationResponse response = new PackageVerificationResponse(
9436                verificationCodeAtTimeout, Binder.getCallingUid());
9437
9438        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
9439            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
9440        }
9441        if (millisecondsToDelay < 0) {
9442            millisecondsToDelay = 0;
9443        }
9444        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9445                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9446            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9447        }
9448
9449        if ((state != null) && !state.timeoutExtended()) {
9450            state.extendTimeout();
9451
9452            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9453            msg.arg1 = id;
9454            msg.obj = response;
9455            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
9456        }
9457    }
9458
9459    private void broadcastPackageVerified(int verificationId, Uri packageUri,
9460            int verificationCode, UserHandle user) {
9461        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
9462        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
9463        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9464        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9465        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
9466
9467        mContext.sendBroadcastAsUser(intent, user,
9468                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
9469    }
9470
9471    private ComponentName matchComponentForVerifier(String packageName,
9472            List<ResolveInfo> receivers) {
9473        ActivityInfo targetReceiver = null;
9474
9475        final int NR = receivers.size();
9476        for (int i = 0; i < NR; i++) {
9477            final ResolveInfo info = receivers.get(i);
9478            if (info.activityInfo == null) {
9479                continue;
9480            }
9481
9482            if (packageName.equals(info.activityInfo.packageName)) {
9483                targetReceiver = info.activityInfo;
9484                break;
9485            }
9486        }
9487
9488        if (targetReceiver == null) {
9489            return null;
9490        }
9491
9492        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
9493    }
9494
9495    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
9496            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
9497        if (pkgInfo.verifiers.length == 0) {
9498            return null;
9499        }
9500
9501        final int N = pkgInfo.verifiers.length;
9502        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
9503        for (int i = 0; i < N; i++) {
9504            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
9505
9506            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
9507                    receivers);
9508            if (comp == null) {
9509                continue;
9510            }
9511
9512            final int verifierUid = getUidForVerifier(verifierInfo);
9513            if (verifierUid == -1) {
9514                continue;
9515            }
9516
9517            if (DEBUG_VERIFY) {
9518                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
9519                        + " with the correct signature");
9520            }
9521            sufficientVerifiers.add(comp);
9522            verificationState.addSufficientVerifier(verifierUid);
9523        }
9524
9525        return sufficientVerifiers;
9526    }
9527
9528    private int getUidForVerifier(VerifierInfo verifierInfo) {
9529        synchronized (mPackages) {
9530            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
9531            if (pkg == null) {
9532                return -1;
9533            } else if (pkg.mSignatures.length != 1) {
9534                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9535                        + " has more than one signature; ignoring");
9536                return -1;
9537            }
9538
9539            /*
9540             * If the public key of the package's signature does not match
9541             * our expected public key, then this is a different package and
9542             * we should skip.
9543             */
9544
9545            final byte[] expectedPublicKey;
9546            try {
9547                final Signature verifierSig = pkg.mSignatures[0];
9548                final PublicKey publicKey = verifierSig.getPublicKey();
9549                expectedPublicKey = publicKey.getEncoded();
9550            } catch (CertificateException e) {
9551                return -1;
9552            }
9553
9554            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
9555
9556            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
9557                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9558                        + " does not have the expected public key; ignoring");
9559                return -1;
9560            }
9561
9562            return pkg.applicationInfo.uid;
9563        }
9564    }
9565
9566    @Override
9567    public void finishPackageInstall(int token) {
9568        enforceSystemOrRoot("Only the system is allowed to finish installs");
9569
9570        if (DEBUG_INSTALL) {
9571            Slog.v(TAG, "BM finishing package install for " + token);
9572        }
9573
9574        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9575        mHandler.sendMessage(msg);
9576    }
9577
9578    /**
9579     * Get the verification agent timeout.
9580     *
9581     * @return verification timeout in milliseconds
9582     */
9583    private long getVerificationTimeout() {
9584        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
9585                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
9586                DEFAULT_VERIFICATION_TIMEOUT);
9587    }
9588
9589    /**
9590     * Get the default verification agent response code.
9591     *
9592     * @return default verification response code
9593     */
9594    private int getDefaultVerificationResponse() {
9595        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9596                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
9597                DEFAULT_VERIFICATION_RESPONSE);
9598    }
9599
9600    /**
9601     * Check whether or not package verification has been enabled.
9602     *
9603     * @return true if verification should be performed
9604     */
9605    private boolean isVerificationEnabled(int userId, int installFlags) {
9606        if (!DEFAULT_VERIFY_ENABLE) {
9607            return false;
9608        }
9609
9610        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
9611
9612        // Check if installing from ADB
9613        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
9614            // Do not run verification in a test harness environment
9615            if (ActivityManager.isRunningInTestHarness()) {
9616                return false;
9617            }
9618            if (ensureVerifyAppsEnabled) {
9619                return true;
9620            }
9621            // Check if the developer does not want package verification for ADB installs
9622            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9623                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
9624                return false;
9625            }
9626        }
9627
9628        if (ensureVerifyAppsEnabled) {
9629            return true;
9630        }
9631
9632        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9633                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9634    }
9635
9636    @Override
9637    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9638            throws RemoteException {
9639        mContext.enforceCallingOrSelfPermission(
9640                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9641                "Only intentfilter verification agents can verify applications");
9642
9643        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9644        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9645                Binder.getCallingUid(), verificationCode, failedDomains);
9646        msg.arg1 = id;
9647        msg.obj = response;
9648        mHandler.sendMessage(msg);
9649    }
9650
9651    @Override
9652    public int getIntentVerificationStatus(String packageName, int userId) {
9653        synchronized (mPackages) {
9654            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
9655        }
9656    }
9657
9658    @Override
9659    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
9660        mContext.enforceCallingOrSelfPermission(
9661                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9662
9663        boolean result = false;
9664        synchronized (mPackages) {
9665            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
9666        }
9667        if (result) {
9668            scheduleWritePackageRestrictionsLocked(userId);
9669        }
9670        return result;
9671    }
9672
9673    @Override
9674    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
9675        synchronized (mPackages) {
9676            return mSettings.getIntentFilterVerificationsLPr(packageName);
9677        }
9678    }
9679
9680    @Override
9681    public List<IntentFilter> getAllIntentFilters(String packageName) {
9682        if (TextUtils.isEmpty(packageName)) {
9683            return Collections.<IntentFilter>emptyList();
9684        }
9685        synchronized (mPackages) {
9686            PackageParser.Package pkg = mPackages.get(packageName);
9687            if (pkg == null || pkg.activities == null) {
9688                return Collections.<IntentFilter>emptyList();
9689            }
9690            final int count = pkg.activities.size();
9691            ArrayList<IntentFilter> result = new ArrayList<>();
9692            for (int n=0; n<count; n++) {
9693                PackageParser.Activity activity = pkg.activities.get(n);
9694                if (activity.intents != null || activity.intents.size() > 0) {
9695                    result.addAll(activity.intents);
9696                }
9697            }
9698            return result;
9699        }
9700    }
9701
9702    @Override
9703    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
9704        mContext.enforceCallingOrSelfPermission(
9705                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9706
9707        synchronized (mPackages) {
9708            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
9709            if (packageName != null) {
9710                result |= updateIntentVerificationStatus(packageName,
9711                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
9712                        UserHandle.myUserId());
9713                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
9714                        packageName, userId);
9715            }
9716            return result;
9717        }
9718    }
9719
9720    @Override
9721    public String getDefaultBrowserPackageName(int userId) {
9722        synchronized (mPackages) {
9723            return mSettings.getDefaultBrowserPackageNameLPw(userId);
9724        }
9725    }
9726
9727    /**
9728     * Get the "allow unknown sources" setting.
9729     *
9730     * @return the current "allow unknown sources" setting
9731     */
9732    private int getUnknownSourcesSettings() {
9733        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9734                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
9735                -1);
9736    }
9737
9738    @Override
9739    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
9740        final int uid = Binder.getCallingUid();
9741        // writer
9742        synchronized (mPackages) {
9743            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
9744            if (targetPackageSetting == null) {
9745                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
9746            }
9747
9748            PackageSetting installerPackageSetting;
9749            if (installerPackageName != null) {
9750                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
9751                if (installerPackageSetting == null) {
9752                    throw new IllegalArgumentException("Unknown installer package: "
9753                            + installerPackageName);
9754                }
9755            } else {
9756                installerPackageSetting = null;
9757            }
9758
9759            Signature[] callerSignature;
9760            Object obj = mSettings.getUserIdLPr(uid);
9761            if (obj != null) {
9762                if (obj instanceof SharedUserSetting) {
9763                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
9764                } else if (obj instanceof PackageSetting) {
9765                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
9766                } else {
9767                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
9768                }
9769            } else {
9770                throw new SecurityException("Unknown calling uid " + uid);
9771            }
9772
9773            // Verify: can't set installerPackageName to a package that is
9774            // not signed with the same cert as the caller.
9775            if (installerPackageSetting != null) {
9776                if (compareSignatures(callerSignature,
9777                        installerPackageSetting.signatures.mSignatures)
9778                        != PackageManager.SIGNATURE_MATCH) {
9779                    throw new SecurityException(
9780                            "Caller does not have same cert as new installer package "
9781                            + installerPackageName);
9782                }
9783            }
9784
9785            // Verify: if target already has an installer package, it must
9786            // be signed with the same cert as the caller.
9787            if (targetPackageSetting.installerPackageName != null) {
9788                PackageSetting setting = mSettings.mPackages.get(
9789                        targetPackageSetting.installerPackageName);
9790                // If the currently set package isn't valid, then it's always
9791                // okay to change it.
9792                if (setting != null) {
9793                    if (compareSignatures(callerSignature,
9794                            setting.signatures.mSignatures)
9795                            != PackageManager.SIGNATURE_MATCH) {
9796                        throw new SecurityException(
9797                                "Caller does not have same cert as old installer package "
9798                                + targetPackageSetting.installerPackageName);
9799                    }
9800                }
9801            }
9802
9803            // Okay!
9804            targetPackageSetting.installerPackageName = installerPackageName;
9805            scheduleWriteSettingsLocked();
9806        }
9807    }
9808
9809    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
9810        // Queue up an async operation since the package installation may take a little while.
9811        mHandler.post(new Runnable() {
9812            public void run() {
9813                mHandler.removeCallbacks(this);
9814                 // Result object to be returned
9815                PackageInstalledInfo res = new PackageInstalledInfo();
9816                res.returnCode = currentStatus;
9817                res.uid = -1;
9818                res.pkg = null;
9819                res.removedInfo = new PackageRemovedInfo();
9820                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
9821                    args.doPreInstall(res.returnCode);
9822                    synchronized (mInstallLock) {
9823                        installPackageLI(args, res);
9824                    }
9825                    args.doPostInstall(res.returnCode, res.uid);
9826                }
9827
9828                // A restore should be performed at this point if (a) the install
9829                // succeeded, (b) the operation is not an update, and (c) the new
9830                // package has not opted out of backup participation.
9831                final boolean update = res.removedInfo.removedPackage != null;
9832                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
9833                boolean doRestore = !update
9834                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
9835
9836                // Set up the post-install work request bookkeeping.  This will be used
9837                // and cleaned up by the post-install event handling regardless of whether
9838                // there's a restore pass performed.  Token values are >= 1.
9839                int token;
9840                if (mNextInstallToken < 0) mNextInstallToken = 1;
9841                token = mNextInstallToken++;
9842
9843                PostInstallData data = new PostInstallData(args, res);
9844                mRunningInstalls.put(token, data);
9845                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
9846
9847                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
9848                    // Pass responsibility to the Backup Manager.  It will perform a
9849                    // restore if appropriate, then pass responsibility back to the
9850                    // Package Manager to run the post-install observer callbacks
9851                    // and broadcasts.
9852                    IBackupManager bm = IBackupManager.Stub.asInterface(
9853                            ServiceManager.getService(Context.BACKUP_SERVICE));
9854                    if (bm != null) {
9855                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
9856                                + " to BM for possible restore");
9857                        try {
9858                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
9859                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
9860                            } else {
9861                                doRestore = false;
9862                            }
9863                        } catch (RemoteException e) {
9864                            // can't happen; the backup manager is local
9865                        } catch (Exception e) {
9866                            Slog.e(TAG, "Exception trying to enqueue restore", e);
9867                            doRestore = false;
9868                        }
9869                    } else {
9870                        Slog.e(TAG, "Backup Manager not found!");
9871                        doRestore = false;
9872                    }
9873                }
9874
9875                if (!doRestore) {
9876                    // No restore possible, or the Backup Manager was mysteriously not
9877                    // available -- just fire the post-install work request directly.
9878                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
9879                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9880                    mHandler.sendMessage(msg);
9881                }
9882            }
9883        });
9884    }
9885
9886    private abstract class HandlerParams {
9887        private static final int MAX_RETRIES = 4;
9888
9889        /**
9890         * Number of times startCopy() has been attempted and had a non-fatal
9891         * error.
9892         */
9893        private int mRetries = 0;
9894
9895        /** User handle for the user requesting the information or installation. */
9896        private final UserHandle mUser;
9897
9898        HandlerParams(UserHandle user) {
9899            mUser = user;
9900        }
9901
9902        UserHandle getUser() {
9903            return mUser;
9904        }
9905
9906        final boolean startCopy() {
9907            boolean res;
9908            try {
9909                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
9910
9911                if (++mRetries > MAX_RETRIES) {
9912                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
9913                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
9914                    handleServiceError();
9915                    return false;
9916                } else {
9917                    handleStartCopy();
9918                    res = true;
9919                }
9920            } catch (RemoteException e) {
9921                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
9922                mHandler.sendEmptyMessage(MCS_RECONNECT);
9923                res = false;
9924            }
9925            handleReturnCode();
9926            return res;
9927        }
9928
9929        final void serviceError() {
9930            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
9931            handleServiceError();
9932            handleReturnCode();
9933        }
9934
9935        abstract void handleStartCopy() throws RemoteException;
9936        abstract void handleServiceError();
9937        abstract void handleReturnCode();
9938    }
9939
9940    class MeasureParams extends HandlerParams {
9941        private final PackageStats mStats;
9942        private boolean mSuccess;
9943
9944        private final IPackageStatsObserver mObserver;
9945
9946        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
9947            super(new UserHandle(stats.userHandle));
9948            mObserver = observer;
9949            mStats = stats;
9950        }
9951
9952        @Override
9953        public String toString() {
9954            return "MeasureParams{"
9955                + Integer.toHexString(System.identityHashCode(this))
9956                + " " + mStats.packageName + "}";
9957        }
9958
9959        @Override
9960        void handleStartCopy() throws RemoteException {
9961            synchronized (mInstallLock) {
9962                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
9963            }
9964
9965            if (mSuccess) {
9966                final boolean mounted;
9967                if (Environment.isExternalStorageEmulated()) {
9968                    mounted = true;
9969                } else {
9970                    final String status = Environment.getExternalStorageState();
9971                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
9972                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
9973                }
9974
9975                if (mounted) {
9976                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
9977
9978                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
9979                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
9980
9981                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
9982                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
9983
9984                    // Always subtract cache size, since it's a subdirectory
9985                    mStats.externalDataSize -= mStats.externalCacheSize;
9986
9987                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
9988                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
9989
9990                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
9991                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
9992                }
9993            }
9994        }
9995
9996        @Override
9997        void handleReturnCode() {
9998            if (mObserver != null) {
9999                try {
10000                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10001                } catch (RemoteException e) {
10002                    Slog.i(TAG, "Observer no longer exists.");
10003                }
10004            }
10005        }
10006
10007        @Override
10008        void handleServiceError() {
10009            Slog.e(TAG, "Could not measure application " + mStats.packageName
10010                            + " external storage");
10011        }
10012    }
10013
10014    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10015            throws RemoteException {
10016        long result = 0;
10017        for (File path : paths) {
10018            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10019        }
10020        return result;
10021    }
10022
10023    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10024        for (File path : paths) {
10025            try {
10026                mcs.clearDirectory(path.getAbsolutePath());
10027            } catch (RemoteException e) {
10028            }
10029        }
10030    }
10031
10032    static class OriginInfo {
10033        /**
10034         * Location where install is coming from, before it has been
10035         * copied/renamed into place. This could be a single monolithic APK
10036         * file, or a cluster directory. This location may be untrusted.
10037         */
10038        final File file;
10039        final String cid;
10040
10041        /**
10042         * Flag indicating that {@link #file} or {@link #cid} has already been
10043         * staged, meaning downstream users don't need to defensively copy the
10044         * contents.
10045         */
10046        final boolean staged;
10047
10048        /**
10049         * Flag indicating that {@link #file} or {@link #cid} is an already
10050         * installed app that is being moved.
10051         */
10052        final boolean existing;
10053
10054        final String resolvedPath;
10055        final File resolvedFile;
10056
10057        static OriginInfo fromNothing() {
10058            return new OriginInfo(null, null, false, false);
10059        }
10060
10061        static OriginInfo fromUntrustedFile(File file) {
10062            return new OriginInfo(file, null, false, false);
10063        }
10064
10065        static OriginInfo fromExistingFile(File file) {
10066            return new OriginInfo(file, null, false, true);
10067        }
10068
10069        static OriginInfo fromStagedFile(File file) {
10070            return new OriginInfo(file, null, true, false);
10071        }
10072
10073        static OriginInfo fromStagedContainer(String cid) {
10074            return new OriginInfo(null, cid, true, false);
10075        }
10076
10077        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10078            this.file = file;
10079            this.cid = cid;
10080            this.staged = staged;
10081            this.existing = existing;
10082
10083            if (cid != null) {
10084                resolvedPath = PackageHelper.getSdDir(cid);
10085                resolvedFile = new File(resolvedPath);
10086            } else if (file != null) {
10087                resolvedPath = file.getAbsolutePath();
10088                resolvedFile = file;
10089            } else {
10090                resolvedPath = null;
10091                resolvedFile = null;
10092            }
10093        }
10094    }
10095
10096    class MoveInfo {
10097        final int moveId;
10098        final String fromUuid;
10099        final String toUuid;
10100        final String packageName;
10101        final String dataAppName;
10102        final int appId;
10103        final String seinfo;
10104
10105        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10106                String dataAppName, int appId, String seinfo) {
10107            this.moveId = moveId;
10108            this.fromUuid = fromUuid;
10109            this.toUuid = toUuid;
10110            this.packageName = packageName;
10111            this.dataAppName = dataAppName;
10112            this.appId = appId;
10113            this.seinfo = seinfo;
10114        }
10115    }
10116
10117    class InstallParams extends HandlerParams {
10118        final OriginInfo origin;
10119        final MoveInfo move;
10120        final IPackageInstallObserver2 observer;
10121        int installFlags;
10122        final String installerPackageName;
10123        final String volumeUuid;
10124        final VerificationParams verificationParams;
10125        private InstallArgs mArgs;
10126        private int mRet;
10127        final String packageAbiOverride;
10128
10129        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10130                int installFlags, String installerPackageName, String volumeUuid,
10131                VerificationParams verificationParams, UserHandle user, String packageAbiOverride) {
10132            super(user);
10133            this.origin = origin;
10134            this.move = move;
10135            this.observer = observer;
10136            this.installFlags = installFlags;
10137            this.installerPackageName = installerPackageName;
10138            this.volumeUuid = volumeUuid;
10139            this.verificationParams = verificationParams;
10140            this.packageAbiOverride = packageAbiOverride;
10141        }
10142
10143        @Override
10144        public String toString() {
10145            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10146                    + " file=" + origin.file + " cid=" + origin.cid + "}";
10147        }
10148
10149        public ManifestDigest getManifestDigest() {
10150            if (verificationParams == null) {
10151                return null;
10152            }
10153            return verificationParams.getManifestDigest();
10154        }
10155
10156        private int installLocationPolicy(PackageInfoLite pkgLite) {
10157            String packageName = pkgLite.packageName;
10158            int installLocation = pkgLite.installLocation;
10159            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10160            // reader
10161            synchronized (mPackages) {
10162                PackageParser.Package pkg = mPackages.get(packageName);
10163                if (pkg != null) {
10164                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10165                        // Check for downgrading.
10166                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10167                            try {
10168                                checkDowngrade(pkg, pkgLite);
10169                            } catch (PackageManagerException e) {
10170                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10171                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
10172                            }
10173                        }
10174                        // Check for updated system application.
10175                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10176                            if (onSd) {
10177                                Slog.w(TAG, "Cannot install update to system app on sdcard");
10178                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
10179                            }
10180                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10181                        } else {
10182                            if (onSd) {
10183                                // Install flag overrides everything.
10184                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10185                            }
10186                            // If current upgrade specifies particular preference
10187                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
10188                                // Application explicitly specified internal.
10189                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10190                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
10191                                // App explictly prefers external. Let policy decide
10192                            } else {
10193                                // Prefer previous location
10194                                if (isExternal(pkg)) {
10195                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10196                                }
10197                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10198                            }
10199                        }
10200                    } else {
10201                        // Invalid install. Return error code
10202                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
10203                    }
10204                }
10205            }
10206            // All the special cases have been taken care of.
10207            // Return result based on recommended install location.
10208            if (onSd) {
10209                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10210            }
10211            return pkgLite.recommendedInstallLocation;
10212        }
10213
10214        /*
10215         * Invoke remote method to get package information and install
10216         * location values. Override install location based on default
10217         * policy if needed and then create install arguments based
10218         * on the install location.
10219         */
10220        public void handleStartCopy() throws RemoteException {
10221            int ret = PackageManager.INSTALL_SUCCEEDED;
10222
10223            // If we're already staged, we've firmly committed to an install location
10224            if (origin.staged) {
10225                if (origin.file != null) {
10226                    installFlags |= PackageManager.INSTALL_INTERNAL;
10227                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10228                } else if (origin.cid != null) {
10229                    installFlags |= PackageManager.INSTALL_EXTERNAL;
10230                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
10231                } else {
10232                    throw new IllegalStateException("Invalid stage location");
10233                }
10234            }
10235
10236            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10237            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
10238
10239            PackageInfoLite pkgLite = null;
10240
10241            if (onInt && onSd) {
10242                // Check if both bits are set.
10243                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
10244                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10245            } else {
10246                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
10247                        packageAbiOverride);
10248
10249                /*
10250                 * If we have too little free space, try to free cache
10251                 * before giving up.
10252                 */
10253                if (!origin.staged && pkgLite.recommendedInstallLocation
10254                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10255                    // TODO: focus freeing disk space on the target device
10256                    final StorageManager storage = StorageManager.from(mContext);
10257                    final long lowThreshold = storage.getStorageLowBytes(
10258                            Environment.getDataDirectory());
10259
10260                    final long sizeBytes = mContainerService.calculateInstalledSize(
10261                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
10262
10263                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
10264                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
10265                                installFlags, packageAbiOverride);
10266                    }
10267
10268                    /*
10269                     * The cache free must have deleted the file we
10270                     * downloaded to install.
10271                     *
10272                     * TODO: fix the "freeCache" call to not delete
10273                     *       the file we care about.
10274                     */
10275                    if (pkgLite.recommendedInstallLocation
10276                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10277                        pkgLite.recommendedInstallLocation
10278                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
10279                    }
10280                }
10281            }
10282
10283            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10284                int loc = pkgLite.recommendedInstallLocation;
10285                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
10286                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10287                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
10288                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
10289                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10290                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10291                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
10292                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
10293                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10294                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
10295                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
10296                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
10297                } else {
10298                    // Override with defaults if needed.
10299                    loc = installLocationPolicy(pkgLite);
10300                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
10301                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
10302                    } else if (!onSd && !onInt) {
10303                        // Override install location with flags
10304                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
10305                            // Set the flag to install on external media.
10306                            installFlags |= PackageManager.INSTALL_EXTERNAL;
10307                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
10308                        } else {
10309                            // Make sure the flag for installing on external
10310                            // media is unset
10311                            installFlags |= PackageManager.INSTALL_INTERNAL;
10312                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10313                        }
10314                    }
10315                }
10316            }
10317
10318            final InstallArgs args = createInstallArgs(this);
10319            mArgs = args;
10320
10321            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10322                 /*
10323                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
10324                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
10325                 */
10326                int userIdentifier = getUser().getIdentifier();
10327                if (userIdentifier == UserHandle.USER_ALL
10328                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
10329                    userIdentifier = UserHandle.USER_OWNER;
10330                }
10331
10332                /*
10333                 * Determine if we have any installed package verifiers. If we
10334                 * do, then we'll defer to them to verify the packages.
10335                 */
10336                final int requiredUid = mRequiredVerifierPackage == null ? -1
10337                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
10338                if (!origin.existing && requiredUid != -1
10339                        && isVerificationEnabled(userIdentifier, installFlags)) {
10340                    final Intent verification = new Intent(
10341                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
10342                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10343                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
10344                            PACKAGE_MIME_TYPE);
10345                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10346
10347                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
10348                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10349                            0 /* TODO: Which userId? */);
10350
10351                    if (DEBUG_VERIFY) {
10352                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10353                                + verification.toString() + " with " + pkgLite.verifiers.length
10354                                + " optional verifiers");
10355                    }
10356
10357                    final int verificationId = mPendingVerificationToken++;
10358
10359                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10360
10361                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10362                            installerPackageName);
10363
10364                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10365                            installFlags);
10366
10367                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10368                            pkgLite.packageName);
10369
10370                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10371                            pkgLite.versionCode);
10372
10373                    if (verificationParams != null) {
10374                        if (verificationParams.getVerificationURI() != null) {
10375                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10376                                 verificationParams.getVerificationURI());
10377                        }
10378                        if (verificationParams.getOriginatingURI() != null) {
10379                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10380                                  verificationParams.getOriginatingURI());
10381                        }
10382                        if (verificationParams.getReferrer() != null) {
10383                            verification.putExtra(Intent.EXTRA_REFERRER,
10384                                  verificationParams.getReferrer());
10385                        }
10386                        if (verificationParams.getOriginatingUid() >= 0) {
10387                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
10388                                  verificationParams.getOriginatingUid());
10389                        }
10390                        if (verificationParams.getInstallerUid() >= 0) {
10391                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
10392                                  verificationParams.getInstallerUid());
10393                        }
10394                    }
10395
10396                    final PackageVerificationState verificationState = new PackageVerificationState(
10397                            requiredUid, args);
10398
10399                    mPendingVerification.append(verificationId, verificationState);
10400
10401                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
10402                            receivers, verificationState);
10403
10404                    /*
10405                     * If any sufficient verifiers were listed in the package
10406                     * manifest, attempt to ask them.
10407                     */
10408                    if (sufficientVerifiers != null) {
10409                        final int N = sufficientVerifiers.size();
10410                        if (N == 0) {
10411                            Slog.i(TAG, "Additional verifiers required, but none installed.");
10412                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
10413                        } else {
10414                            for (int i = 0; i < N; i++) {
10415                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
10416
10417                                final Intent sufficientIntent = new Intent(verification);
10418                                sufficientIntent.setComponent(verifierComponent);
10419
10420                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
10421                            }
10422                        }
10423                    }
10424
10425                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
10426                            mRequiredVerifierPackage, receivers);
10427                    if (ret == PackageManager.INSTALL_SUCCEEDED
10428                            && mRequiredVerifierPackage != null) {
10429                        /*
10430                         * Send the intent to the required verification agent,
10431                         * but only start the verification timeout after the
10432                         * target BroadcastReceivers have run.
10433                         */
10434                        verification.setComponent(requiredVerifierComponent);
10435                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
10436                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10437                                new BroadcastReceiver() {
10438                                    @Override
10439                                    public void onReceive(Context context, Intent intent) {
10440                                        final Message msg = mHandler
10441                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
10442                                        msg.arg1 = verificationId;
10443                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
10444                                    }
10445                                }, null, 0, null, null);
10446
10447                        /*
10448                         * We don't want the copy to proceed until verification
10449                         * succeeds, so null out this field.
10450                         */
10451                        mArgs = null;
10452                    }
10453                } else {
10454                    /*
10455                     * No package verification is enabled, so immediately start
10456                     * the remote call to initiate copy using temporary file.
10457                     */
10458                    ret = args.copyApk(mContainerService, true);
10459                }
10460            }
10461
10462            mRet = ret;
10463        }
10464
10465        @Override
10466        void handleReturnCode() {
10467            // If mArgs is null, then MCS couldn't be reached. When it
10468            // reconnects, it will try again to install. At that point, this
10469            // will succeed.
10470            if (mArgs != null) {
10471                processPendingInstall(mArgs, mRet);
10472            }
10473        }
10474
10475        @Override
10476        void handleServiceError() {
10477            mArgs = createInstallArgs(this);
10478            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10479        }
10480
10481        public boolean isForwardLocked() {
10482            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10483        }
10484    }
10485
10486    /**
10487     * Used during creation of InstallArgs
10488     *
10489     * @param installFlags package installation flags
10490     * @return true if should be installed on external storage
10491     */
10492    private static boolean installOnExternalAsec(int installFlags) {
10493        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
10494            return false;
10495        }
10496        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
10497            return true;
10498        }
10499        return false;
10500    }
10501
10502    /**
10503     * Used during creation of InstallArgs
10504     *
10505     * @param installFlags package installation flags
10506     * @return true if should be installed as forward locked
10507     */
10508    private static boolean installForwardLocked(int installFlags) {
10509        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10510    }
10511
10512    private InstallArgs createInstallArgs(InstallParams params) {
10513        if (params.move != null) {
10514            return new MoveInstallArgs(params);
10515        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
10516            return new AsecInstallArgs(params);
10517        } else {
10518            return new FileInstallArgs(params);
10519        }
10520    }
10521
10522    /**
10523     * Create args that describe an existing installed package. Typically used
10524     * when cleaning up old installs, or used as a move source.
10525     */
10526    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
10527            String resourcePath, String[] instructionSets) {
10528        final boolean isInAsec;
10529        if (installOnExternalAsec(installFlags)) {
10530            /* Apps on SD card are always in ASEC containers. */
10531            isInAsec = true;
10532        } else if (installForwardLocked(installFlags)
10533                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
10534            /*
10535             * Forward-locked apps are only in ASEC containers if they're the
10536             * new style
10537             */
10538            isInAsec = true;
10539        } else {
10540            isInAsec = false;
10541        }
10542
10543        if (isInAsec) {
10544            return new AsecInstallArgs(codePath, instructionSets,
10545                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
10546        } else {
10547            return new FileInstallArgs(codePath, resourcePath, instructionSets);
10548        }
10549    }
10550
10551    static abstract class InstallArgs {
10552        /** @see InstallParams#origin */
10553        final OriginInfo origin;
10554        /** @see InstallParams#move */
10555        final MoveInfo move;
10556
10557        final IPackageInstallObserver2 observer;
10558        // Always refers to PackageManager flags only
10559        final int installFlags;
10560        final String installerPackageName;
10561        final String volumeUuid;
10562        final ManifestDigest manifestDigest;
10563        final UserHandle user;
10564        final String abiOverride;
10565
10566        // The list of instruction sets supported by this app. This is currently
10567        // only used during the rmdex() phase to clean up resources. We can get rid of this
10568        // if we move dex files under the common app path.
10569        /* nullable */ String[] instructionSets;
10570
10571        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10572                int installFlags, String installerPackageName, String volumeUuid,
10573                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
10574                String abiOverride) {
10575            this.origin = origin;
10576            this.move = move;
10577            this.installFlags = installFlags;
10578            this.observer = observer;
10579            this.installerPackageName = installerPackageName;
10580            this.volumeUuid = volumeUuid;
10581            this.manifestDigest = manifestDigest;
10582            this.user = user;
10583            this.instructionSets = instructionSets;
10584            this.abiOverride = abiOverride;
10585        }
10586
10587        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
10588        abstract int doPreInstall(int status);
10589
10590        /**
10591         * Rename package into final resting place. All paths on the given
10592         * scanned package should be updated to reflect the rename.
10593         */
10594        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
10595        abstract int doPostInstall(int status, int uid);
10596
10597        /** @see PackageSettingBase#codePathString */
10598        abstract String getCodePath();
10599        /** @see PackageSettingBase#resourcePathString */
10600        abstract String getResourcePath();
10601
10602        // Need installer lock especially for dex file removal.
10603        abstract void cleanUpResourcesLI();
10604        abstract boolean doPostDeleteLI(boolean delete);
10605
10606        /**
10607         * Called before the source arguments are copied. This is used mostly
10608         * for MoveParams when it needs to read the source file to put it in the
10609         * destination.
10610         */
10611        int doPreCopy() {
10612            return PackageManager.INSTALL_SUCCEEDED;
10613        }
10614
10615        /**
10616         * Called after the source arguments are copied. This is used mostly for
10617         * MoveParams when it needs to read the source file to put it in the
10618         * destination.
10619         *
10620         * @return
10621         */
10622        int doPostCopy(int uid) {
10623            return PackageManager.INSTALL_SUCCEEDED;
10624        }
10625
10626        protected boolean isFwdLocked() {
10627            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10628        }
10629
10630        protected boolean isExternalAsec() {
10631            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10632        }
10633
10634        UserHandle getUser() {
10635            return user;
10636        }
10637    }
10638
10639    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
10640        if (!allCodePaths.isEmpty()) {
10641            if (instructionSets == null) {
10642                throw new IllegalStateException("instructionSet == null");
10643            }
10644            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
10645            for (String codePath : allCodePaths) {
10646                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
10647                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
10648                    if (retCode < 0) {
10649                        Slog.w(TAG, "Couldn't remove dex file for package: "
10650                                + " at location " + codePath + ", retcode=" + retCode);
10651                        // we don't consider this to be a failure of the core package deletion
10652                    }
10653                }
10654            }
10655        }
10656    }
10657
10658    /**
10659     * Logic to handle installation of non-ASEC applications, including copying
10660     * and renaming logic.
10661     */
10662    class FileInstallArgs extends InstallArgs {
10663        private File codeFile;
10664        private File resourceFile;
10665
10666        // Example topology:
10667        // /data/app/com.example/base.apk
10668        // /data/app/com.example/split_foo.apk
10669        // /data/app/com.example/lib/arm/libfoo.so
10670        // /data/app/com.example/lib/arm64/libfoo.so
10671        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
10672
10673        /** New install */
10674        FileInstallArgs(InstallParams params) {
10675            super(params.origin, params.move, params.observer, params.installFlags,
10676                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10677                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10678            if (isFwdLocked()) {
10679                throw new IllegalArgumentException("Forward locking only supported in ASEC");
10680            }
10681        }
10682
10683        /** Existing install */
10684        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
10685            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
10686                    null);
10687            this.codeFile = (codePath != null) ? new File(codePath) : null;
10688            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
10689        }
10690
10691        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10692            if (origin.staged) {
10693                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
10694                codeFile = origin.file;
10695                resourceFile = origin.file;
10696                return PackageManager.INSTALL_SUCCEEDED;
10697            }
10698
10699            try {
10700                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
10701                codeFile = tempDir;
10702                resourceFile = tempDir;
10703            } catch (IOException e) {
10704                Slog.w(TAG, "Failed to create copy file: " + e);
10705                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10706            }
10707
10708            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
10709                @Override
10710                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
10711                    if (!FileUtils.isValidExtFilename(name)) {
10712                        throw new IllegalArgumentException("Invalid filename: " + name);
10713                    }
10714                    try {
10715                        final File file = new File(codeFile, name);
10716                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
10717                                O_RDWR | O_CREAT, 0644);
10718                        Os.chmod(file.getAbsolutePath(), 0644);
10719                        return new ParcelFileDescriptor(fd);
10720                    } catch (ErrnoException e) {
10721                        throw new RemoteException("Failed to open: " + e.getMessage());
10722                    }
10723                }
10724            };
10725
10726            int ret = PackageManager.INSTALL_SUCCEEDED;
10727            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
10728            if (ret != PackageManager.INSTALL_SUCCEEDED) {
10729                Slog.e(TAG, "Failed to copy package");
10730                return ret;
10731            }
10732
10733            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
10734            NativeLibraryHelper.Handle handle = null;
10735            try {
10736                handle = NativeLibraryHelper.Handle.create(codeFile);
10737                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
10738                        abiOverride);
10739            } catch (IOException e) {
10740                Slog.e(TAG, "Copying native libraries failed", e);
10741                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10742            } finally {
10743                IoUtils.closeQuietly(handle);
10744            }
10745
10746            return ret;
10747        }
10748
10749        int doPreInstall(int status) {
10750            if (status != PackageManager.INSTALL_SUCCEEDED) {
10751                cleanUp();
10752            }
10753            return status;
10754        }
10755
10756        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10757            if (status != PackageManager.INSTALL_SUCCEEDED) {
10758                cleanUp();
10759                return false;
10760            }
10761
10762            final File targetDir = codeFile.getParentFile();
10763            final File beforeCodeFile = codeFile;
10764            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
10765
10766            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
10767            try {
10768                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
10769            } catch (ErrnoException e) {
10770                Slog.w(TAG, "Failed to rename", e);
10771                return false;
10772            }
10773
10774            if (!SELinux.restoreconRecursive(afterCodeFile)) {
10775                Slog.w(TAG, "Failed to restorecon");
10776                return false;
10777            }
10778
10779            // Reflect the rename internally
10780            codeFile = afterCodeFile;
10781            resourceFile = afterCodeFile;
10782
10783            // Reflect the rename in scanned details
10784            pkg.codePath = afterCodeFile.getAbsolutePath();
10785            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10786                    pkg.baseCodePath);
10787            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10788                    pkg.splitCodePaths);
10789
10790            // Reflect the rename in app info
10791            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10792            pkg.applicationInfo.setCodePath(pkg.codePath);
10793            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10794            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10795            pkg.applicationInfo.setResourcePath(pkg.codePath);
10796            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10797            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10798
10799            return true;
10800        }
10801
10802        int doPostInstall(int status, int uid) {
10803            if (status != PackageManager.INSTALL_SUCCEEDED) {
10804                cleanUp();
10805            }
10806            return status;
10807        }
10808
10809        @Override
10810        String getCodePath() {
10811            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
10812        }
10813
10814        @Override
10815        String getResourcePath() {
10816            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
10817        }
10818
10819        private boolean cleanUp() {
10820            if (codeFile == null || !codeFile.exists()) {
10821                return false;
10822            }
10823
10824            if (codeFile.isDirectory()) {
10825                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
10826            } else {
10827                codeFile.delete();
10828            }
10829
10830            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
10831                resourceFile.delete();
10832            }
10833
10834            return true;
10835        }
10836
10837        void cleanUpResourcesLI() {
10838            // Try enumerating all code paths before deleting
10839            List<String> allCodePaths = Collections.EMPTY_LIST;
10840            if (codeFile != null && codeFile.exists()) {
10841                try {
10842                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
10843                    allCodePaths = pkg.getAllCodePaths();
10844                } catch (PackageParserException e) {
10845                    // Ignored; we tried our best
10846                }
10847            }
10848
10849            cleanUp();
10850            removeDexFiles(allCodePaths, instructionSets);
10851        }
10852
10853        boolean doPostDeleteLI(boolean delete) {
10854            // XXX err, shouldn't we respect the delete flag?
10855            cleanUpResourcesLI();
10856            return true;
10857        }
10858    }
10859
10860    private boolean isAsecExternal(String cid) {
10861        final String asecPath = PackageHelper.getSdFilesystem(cid);
10862        return !asecPath.startsWith(mAsecInternalPath);
10863    }
10864
10865    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
10866            PackageManagerException {
10867        if (copyRet < 0) {
10868            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
10869                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
10870                throw new PackageManagerException(copyRet, message);
10871            }
10872        }
10873    }
10874
10875    /**
10876     * Extract the MountService "container ID" from the full code path of an
10877     * .apk.
10878     */
10879    static String cidFromCodePath(String fullCodePath) {
10880        int eidx = fullCodePath.lastIndexOf("/");
10881        String subStr1 = fullCodePath.substring(0, eidx);
10882        int sidx = subStr1.lastIndexOf("/");
10883        return subStr1.substring(sidx+1, eidx);
10884    }
10885
10886    /**
10887     * Logic to handle installation of ASEC applications, including copying and
10888     * renaming logic.
10889     */
10890    class AsecInstallArgs extends InstallArgs {
10891        static final String RES_FILE_NAME = "pkg.apk";
10892        static final String PUBLIC_RES_FILE_NAME = "res.zip";
10893
10894        String cid;
10895        String packagePath;
10896        String resourcePath;
10897
10898        /** New install */
10899        AsecInstallArgs(InstallParams params) {
10900            super(params.origin, params.move, params.observer, params.installFlags,
10901                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10902                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10903        }
10904
10905        /** Existing install */
10906        AsecInstallArgs(String fullCodePath, String[] instructionSets,
10907                        boolean isExternal, boolean isForwardLocked) {
10908            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
10909                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
10910                    instructionSets, null);
10911            // Hackily pretend we're still looking at a full code path
10912            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
10913                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
10914            }
10915
10916            // Extract cid from fullCodePath
10917            int eidx = fullCodePath.lastIndexOf("/");
10918            String subStr1 = fullCodePath.substring(0, eidx);
10919            int sidx = subStr1.lastIndexOf("/");
10920            cid = subStr1.substring(sidx+1, eidx);
10921            setMountPath(subStr1);
10922        }
10923
10924        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
10925            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
10926                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
10927                    instructionSets, null);
10928            this.cid = cid;
10929            setMountPath(PackageHelper.getSdDir(cid));
10930        }
10931
10932        void createCopyFile() {
10933            cid = mInstallerService.allocateExternalStageCidLegacy();
10934        }
10935
10936        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10937            if (origin.staged) {
10938                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
10939                cid = origin.cid;
10940                setMountPath(PackageHelper.getSdDir(cid));
10941                return PackageManager.INSTALL_SUCCEEDED;
10942            }
10943
10944            if (temp) {
10945                createCopyFile();
10946            } else {
10947                /*
10948                 * Pre-emptively destroy the container since it's destroyed if
10949                 * copying fails due to it existing anyway.
10950                 */
10951                PackageHelper.destroySdDir(cid);
10952            }
10953
10954            final String newMountPath = imcs.copyPackageToContainer(
10955                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
10956                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
10957
10958            if (newMountPath != null) {
10959                setMountPath(newMountPath);
10960                return PackageManager.INSTALL_SUCCEEDED;
10961            } else {
10962                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10963            }
10964        }
10965
10966        @Override
10967        String getCodePath() {
10968            return packagePath;
10969        }
10970
10971        @Override
10972        String getResourcePath() {
10973            return resourcePath;
10974        }
10975
10976        int doPreInstall(int status) {
10977            if (status != PackageManager.INSTALL_SUCCEEDED) {
10978                // Destroy container
10979                PackageHelper.destroySdDir(cid);
10980            } else {
10981                boolean mounted = PackageHelper.isContainerMounted(cid);
10982                if (!mounted) {
10983                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
10984                            Process.SYSTEM_UID);
10985                    if (newMountPath != null) {
10986                        setMountPath(newMountPath);
10987                    } else {
10988                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10989                    }
10990                }
10991            }
10992            return status;
10993        }
10994
10995        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10996            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
10997            String newMountPath = null;
10998            if (PackageHelper.isContainerMounted(cid)) {
10999                // Unmount the container
11000                if (!PackageHelper.unMountSdDir(cid)) {
11001                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11002                    return false;
11003                }
11004            }
11005            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11006                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11007                        " which might be stale. Will try to clean up.");
11008                // Clean up the stale container and proceed to recreate.
11009                if (!PackageHelper.destroySdDir(newCacheId)) {
11010                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11011                    return false;
11012                }
11013                // Successfully cleaned up stale container. Try to rename again.
11014                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11015                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11016                            + " inspite of cleaning it up.");
11017                    return false;
11018                }
11019            }
11020            if (!PackageHelper.isContainerMounted(newCacheId)) {
11021                Slog.w(TAG, "Mounting container " + newCacheId);
11022                newMountPath = PackageHelper.mountSdDir(newCacheId,
11023                        getEncryptKey(), Process.SYSTEM_UID);
11024            } else {
11025                newMountPath = PackageHelper.getSdDir(newCacheId);
11026            }
11027            if (newMountPath == null) {
11028                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11029                return false;
11030            }
11031            Log.i(TAG, "Succesfully renamed " + cid +
11032                    " to " + newCacheId +
11033                    " at new path: " + newMountPath);
11034            cid = newCacheId;
11035
11036            final File beforeCodeFile = new File(packagePath);
11037            setMountPath(newMountPath);
11038            final File afterCodeFile = new File(packagePath);
11039
11040            // Reflect the rename in scanned details
11041            pkg.codePath = afterCodeFile.getAbsolutePath();
11042            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11043                    pkg.baseCodePath);
11044            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11045                    pkg.splitCodePaths);
11046
11047            // Reflect the rename in app info
11048            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11049            pkg.applicationInfo.setCodePath(pkg.codePath);
11050            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11051            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11052            pkg.applicationInfo.setResourcePath(pkg.codePath);
11053            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11054            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11055
11056            return true;
11057        }
11058
11059        private void setMountPath(String mountPath) {
11060            final File mountFile = new File(mountPath);
11061
11062            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11063            if (monolithicFile.exists()) {
11064                packagePath = monolithicFile.getAbsolutePath();
11065                if (isFwdLocked()) {
11066                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11067                } else {
11068                    resourcePath = packagePath;
11069                }
11070            } else {
11071                packagePath = mountFile.getAbsolutePath();
11072                resourcePath = packagePath;
11073            }
11074        }
11075
11076        int doPostInstall(int status, int uid) {
11077            if (status != PackageManager.INSTALL_SUCCEEDED) {
11078                cleanUp();
11079            } else {
11080                final int groupOwner;
11081                final String protectedFile;
11082                if (isFwdLocked()) {
11083                    groupOwner = UserHandle.getSharedAppGid(uid);
11084                    protectedFile = RES_FILE_NAME;
11085                } else {
11086                    groupOwner = -1;
11087                    protectedFile = null;
11088                }
11089
11090                if (uid < Process.FIRST_APPLICATION_UID
11091                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11092                    Slog.e(TAG, "Failed to finalize " + cid);
11093                    PackageHelper.destroySdDir(cid);
11094                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11095                }
11096
11097                boolean mounted = PackageHelper.isContainerMounted(cid);
11098                if (!mounted) {
11099                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11100                }
11101            }
11102            return status;
11103        }
11104
11105        private void cleanUp() {
11106            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11107
11108            // Destroy secure container
11109            PackageHelper.destroySdDir(cid);
11110        }
11111
11112        private List<String> getAllCodePaths() {
11113            final File codeFile = new File(getCodePath());
11114            if (codeFile != null && codeFile.exists()) {
11115                try {
11116                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11117                    return pkg.getAllCodePaths();
11118                } catch (PackageParserException e) {
11119                    // Ignored; we tried our best
11120                }
11121            }
11122            return Collections.EMPTY_LIST;
11123        }
11124
11125        void cleanUpResourcesLI() {
11126            // Enumerate all code paths before deleting
11127            cleanUpResourcesLI(getAllCodePaths());
11128        }
11129
11130        private void cleanUpResourcesLI(List<String> allCodePaths) {
11131            cleanUp();
11132            removeDexFiles(allCodePaths, instructionSets);
11133        }
11134
11135        String getPackageName() {
11136            return getAsecPackageName(cid);
11137        }
11138
11139        boolean doPostDeleteLI(boolean delete) {
11140            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
11141            final List<String> allCodePaths = getAllCodePaths();
11142            boolean mounted = PackageHelper.isContainerMounted(cid);
11143            if (mounted) {
11144                // Unmount first
11145                if (PackageHelper.unMountSdDir(cid)) {
11146                    mounted = false;
11147                }
11148            }
11149            if (!mounted && delete) {
11150                cleanUpResourcesLI(allCodePaths);
11151            }
11152            return !mounted;
11153        }
11154
11155        @Override
11156        int doPreCopy() {
11157            if (isFwdLocked()) {
11158                if (!PackageHelper.fixSdPermissions(cid,
11159                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
11160                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11161                }
11162            }
11163
11164            return PackageManager.INSTALL_SUCCEEDED;
11165        }
11166
11167        @Override
11168        int doPostCopy(int uid) {
11169            if (isFwdLocked()) {
11170                if (uid < Process.FIRST_APPLICATION_UID
11171                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
11172                                RES_FILE_NAME)) {
11173                    Slog.e(TAG, "Failed to finalize " + cid);
11174                    PackageHelper.destroySdDir(cid);
11175                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11176                }
11177            }
11178
11179            return PackageManager.INSTALL_SUCCEEDED;
11180        }
11181    }
11182
11183    /**
11184     * Logic to handle movement of existing installed applications.
11185     */
11186    class MoveInstallArgs extends InstallArgs {
11187        private File codeFile;
11188        private File resourceFile;
11189
11190        /** New install */
11191        MoveInstallArgs(InstallParams params) {
11192            super(params.origin, params.move, params.observer, params.installFlags,
11193                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11194                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
11195        }
11196
11197        int copyApk(IMediaContainerService imcs, boolean temp) {
11198            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
11199                    + move.fromUuid + " to " + move.toUuid);
11200            synchronized (mInstaller) {
11201                if (mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
11202                        move.dataAppName, move.appId, move.seinfo) != 0) {
11203                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11204                }
11205            }
11206
11207            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
11208            resourceFile = codeFile;
11209            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
11210
11211            return PackageManager.INSTALL_SUCCEEDED;
11212        }
11213
11214        int doPreInstall(int status) {
11215            if (status != PackageManager.INSTALL_SUCCEEDED) {
11216                cleanUp();
11217            }
11218            return status;
11219        }
11220
11221        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11222            if (status != PackageManager.INSTALL_SUCCEEDED) {
11223                cleanUp();
11224                return false;
11225            }
11226
11227            // Reflect the move in app info
11228            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11229            pkg.applicationInfo.setCodePath(pkg.codePath);
11230            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11231            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11232            pkg.applicationInfo.setResourcePath(pkg.codePath);
11233            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11234            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11235
11236            return true;
11237        }
11238
11239        int doPostInstall(int status, int uid) {
11240            if (status != PackageManager.INSTALL_SUCCEEDED) {
11241                cleanUp();
11242            }
11243            return status;
11244        }
11245
11246        @Override
11247        String getCodePath() {
11248            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11249        }
11250
11251        @Override
11252        String getResourcePath() {
11253            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11254        }
11255
11256        private boolean cleanUp() {
11257            if (codeFile == null || !codeFile.exists()) {
11258                return false;
11259            }
11260
11261            if (codeFile.isDirectory()) {
11262                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11263            } else {
11264                codeFile.delete();
11265            }
11266
11267            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11268                resourceFile.delete();
11269            }
11270
11271            return true;
11272        }
11273
11274        void cleanUpResourcesLI() {
11275            cleanUp();
11276        }
11277
11278        boolean doPostDeleteLI(boolean delete) {
11279            // XXX err, shouldn't we respect the delete flag?
11280            cleanUpResourcesLI();
11281            return true;
11282        }
11283    }
11284
11285    static String getAsecPackageName(String packageCid) {
11286        int idx = packageCid.lastIndexOf("-");
11287        if (idx == -1) {
11288            return packageCid;
11289        }
11290        return packageCid.substring(0, idx);
11291    }
11292
11293    // Utility method used to create code paths based on package name and available index.
11294    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
11295        String idxStr = "";
11296        int idx = 1;
11297        // Fall back to default value of idx=1 if prefix is not
11298        // part of oldCodePath
11299        if (oldCodePath != null) {
11300            String subStr = oldCodePath;
11301            // Drop the suffix right away
11302            if (suffix != null && subStr.endsWith(suffix)) {
11303                subStr = subStr.substring(0, subStr.length() - suffix.length());
11304            }
11305            // If oldCodePath already contains prefix find out the
11306            // ending index to either increment or decrement.
11307            int sidx = subStr.lastIndexOf(prefix);
11308            if (sidx != -1) {
11309                subStr = subStr.substring(sidx + prefix.length());
11310                if (subStr != null) {
11311                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
11312                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
11313                    }
11314                    try {
11315                        idx = Integer.parseInt(subStr);
11316                        if (idx <= 1) {
11317                            idx++;
11318                        } else {
11319                            idx--;
11320                        }
11321                    } catch(NumberFormatException e) {
11322                    }
11323                }
11324            }
11325        }
11326        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
11327        return prefix + idxStr;
11328    }
11329
11330    private File getNextCodePath(File targetDir, String packageName) {
11331        int suffix = 1;
11332        File result;
11333        do {
11334            result = new File(targetDir, packageName + "-" + suffix);
11335            suffix++;
11336        } while (result.exists());
11337        return result;
11338    }
11339
11340    // Utility method that returns the relative package path with respect
11341    // to the installation directory. Like say for /data/data/com.test-1.apk
11342    // string com.test-1 is returned.
11343    static String deriveCodePathName(String codePath) {
11344        if (codePath == null) {
11345            return null;
11346        }
11347        final File codeFile = new File(codePath);
11348        final String name = codeFile.getName();
11349        if (codeFile.isDirectory()) {
11350            return name;
11351        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
11352            final int lastDot = name.lastIndexOf('.');
11353            return name.substring(0, lastDot);
11354        } else {
11355            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11356            return null;
11357        }
11358    }
11359
11360    class PackageInstalledInfo {
11361        String name;
11362        int uid;
11363        // The set of users that originally had this package installed.
11364        int[] origUsers;
11365        // The set of users that now have this package installed.
11366        int[] newUsers;
11367        PackageParser.Package pkg;
11368        int returnCode;
11369        String returnMsg;
11370        PackageRemovedInfo removedInfo;
11371
11372        public void setError(int code, String msg) {
11373            returnCode = code;
11374            returnMsg = msg;
11375            Slog.w(TAG, msg);
11376        }
11377
11378        public void setError(String msg, PackageParserException e) {
11379            returnCode = e.error;
11380            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11381            Slog.w(TAG, msg, e);
11382        }
11383
11384        public void setError(String msg, PackageManagerException e) {
11385            returnCode = e.error;
11386            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11387            Slog.w(TAG, msg, e);
11388        }
11389
11390        // In some error cases we want to convey more info back to the observer
11391        String origPackage;
11392        String origPermission;
11393    }
11394
11395    /*
11396     * Install a non-existing package.
11397     */
11398    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11399            UserHandle user, String installerPackageName, String volumeUuid,
11400            PackageInstalledInfo res) {
11401        // Remember this for later, in case we need to rollback this install
11402        String pkgName = pkg.packageName;
11403
11404        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
11405        final boolean dataDirExists = PackageManager.getDataDirForUser(volumeUuid, pkgName,
11406                UserHandle.USER_OWNER).exists();
11407        synchronized(mPackages) {
11408            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
11409                // A package with the same name is already installed, though
11410                // it has been renamed to an older name.  The package we
11411                // are trying to install should be installed as an update to
11412                // the existing one, but that has not been requested, so bail.
11413                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11414                        + " without first uninstalling package running as "
11415                        + mSettings.mRenamedPackages.get(pkgName));
11416                return;
11417            }
11418            if (mPackages.containsKey(pkgName)) {
11419                // Don't allow installation over an existing package with the same name.
11420                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11421                        + " without first uninstalling.");
11422                return;
11423            }
11424        }
11425
11426        try {
11427            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
11428                    System.currentTimeMillis(), user);
11429
11430            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
11431            // delete the partially installed application. the data directory will have to be
11432            // restored if it was already existing
11433            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11434                // remove package from internal structures.  Note that we want deletePackageX to
11435                // delete the package data and cache directories that it created in
11436                // scanPackageLocked, unless those directories existed before we even tried to
11437                // install.
11438                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
11439                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
11440                                res.removedInfo, true);
11441            }
11442
11443        } catch (PackageManagerException e) {
11444            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11445        }
11446    }
11447
11448    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
11449        // Can't rotate keys during boot or if sharedUser.
11450        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
11451                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
11452            return false;
11453        }
11454        // app is using upgradeKeySets; make sure all are valid
11455        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11456        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
11457        for (int i = 0; i < upgradeKeySets.length; i++) {
11458            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
11459                Slog.wtf(TAG, "Package "
11460                         + (oldPs.name != null ? oldPs.name : "<null>")
11461                         + " contains upgrade-key-set reference to unknown key-set: "
11462                         + upgradeKeySets[i]
11463                         + " reverting to signatures check.");
11464                return false;
11465            }
11466        }
11467        return true;
11468    }
11469
11470    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
11471        // Upgrade keysets are being used.  Determine if new package has a superset of the
11472        // required keys.
11473        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
11474        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11475        for (int i = 0; i < upgradeKeySets.length; i++) {
11476            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
11477            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
11478                return true;
11479            }
11480        }
11481        return false;
11482    }
11483
11484    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11485            UserHandle user, String installerPackageName, String volumeUuid,
11486            PackageInstalledInfo res) {
11487        final PackageParser.Package oldPackage;
11488        final String pkgName = pkg.packageName;
11489        final int[] allUsers;
11490        final boolean[] perUserInstalled;
11491        final boolean weFroze;
11492
11493        // First find the old package info and check signatures
11494        synchronized(mPackages) {
11495            oldPackage = mPackages.get(pkgName);
11496            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
11497            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11498            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11499                if(!checkUpgradeKeySetLP(ps, pkg)) {
11500                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11501                            "New package not signed by keys specified by upgrade-keysets: "
11502                            + pkgName);
11503                    return;
11504                }
11505            } else {
11506                // default to original signature matching
11507                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
11508                    != PackageManager.SIGNATURE_MATCH) {
11509                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11510                            "New package has a different signature: " + pkgName);
11511                    return;
11512                }
11513            }
11514
11515            // In case of rollback, remember per-user/profile install state
11516            allUsers = sUserManager.getUserIds();
11517            perUserInstalled = new boolean[allUsers.length];
11518            for (int i = 0; i < allUsers.length; i++) {
11519                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11520            }
11521
11522            // Mark the app as frozen to prevent launching during the upgrade
11523            // process, and then kill all running instances
11524            if (!ps.frozen) {
11525                ps.frozen = true;
11526                weFroze = true;
11527            } else {
11528                weFroze = false;
11529            }
11530        }
11531
11532        // Now that we're guarded by frozen state, kill app during upgrade
11533        killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg");
11534
11535        try {
11536            boolean sysPkg = (isSystemApp(oldPackage));
11537            if (sysPkg) {
11538                replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11539                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11540            } else {
11541                replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11542                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11543            }
11544        } finally {
11545            // Regardless of success or failure of upgrade steps above, always
11546            // unfreeze the package if we froze it
11547            if (weFroze) {
11548                unfreezePackage(pkgName);
11549            }
11550        }
11551    }
11552
11553    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
11554            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11555            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11556            String volumeUuid, PackageInstalledInfo res) {
11557        String pkgName = deletedPackage.packageName;
11558        boolean deletedPkg = true;
11559        boolean updatedSettings = false;
11560
11561        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
11562                + deletedPackage);
11563        long origUpdateTime;
11564        if (pkg.mExtras != null) {
11565            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
11566        } else {
11567            origUpdateTime = 0;
11568        }
11569
11570        // First delete the existing package while retaining the data directory
11571        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
11572                res.removedInfo, true)) {
11573            // If the existing package wasn't successfully deleted
11574            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
11575            deletedPkg = false;
11576        } else {
11577            // Successfully deleted the old package; proceed with replace.
11578
11579            // If deleted package lived in a container, give users a chance to
11580            // relinquish resources before killing.
11581            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
11582                if (DEBUG_INSTALL) {
11583                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
11584                }
11585                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
11586                final ArrayList<String> pkgList = new ArrayList<String>(1);
11587                pkgList.add(deletedPackage.applicationInfo.packageName);
11588                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
11589            }
11590
11591            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
11592            try {
11593                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
11594                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
11595                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11596                        perUserInstalled, res, user);
11597                updatedSettings = true;
11598            } catch (PackageManagerException e) {
11599                res.setError("Package couldn't be installed in " + pkg.codePath, e);
11600            }
11601        }
11602
11603        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11604            // remove package from internal structures.  Note that we want deletePackageX to
11605            // delete the package data and cache directories that it created in
11606            // scanPackageLocked, unless those directories existed before we even tried to
11607            // install.
11608            if(updatedSettings) {
11609                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
11610                deletePackageLI(
11611                        pkgName, null, true, allUsers, perUserInstalled,
11612                        PackageManager.DELETE_KEEP_DATA,
11613                                res.removedInfo, true);
11614            }
11615            // Since we failed to install the new package we need to restore the old
11616            // package that we deleted.
11617            if (deletedPkg) {
11618                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
11619                File restoreFile = new File(deletedPackage.codePath);
11620                // Parse old package
11621                boolean oldExternal = isExternal(deletedPackage);
11622                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
11623                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
11624                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11625                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
11626                try {
11627                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
11628                } catch (PackageManagerException e) {
11629                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
11630                            + e.getMessage());
11631                    return;
11632                }
11633                // Restore of old package succeeded. Update permissions.
11634                // writer
11635                synchronized (mPackages) {
11636                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
11637                            UPDATE_PERMISSIONS_ALL);
11638                    // can downgrade to reader
11639                    mSettings.writeLPr();
11640                }
11641                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
11642            }
11643        }
11644    }
11645
11646    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
11647            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11648            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11649            String volumeUuid, PackageInstalledInfo res) {
11650        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
11651                + ", old=" + deletedPackage);
11652        boolean disabledSystem = false;
11653        boolean updatedSettings = false;
11654        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
11655        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
11656                != 0) {
11657            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11658        }
11659        String packageName = deletedPackage.packageName;
11660        if (packageName == null) {
11661            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11662                    "Attempt to delete null packageName.");
11663            return;
11664        }
11665        PackageParser.Package oldPkg;
11666        PackageSetting oldPkgSetting;
11667        // reader
11668        synchronized (mPackages) {
11669            oldPkg = mPackages.get(packageName);
11670            oldPkgSetting = mSettings.mPackages.get(packageName);
11671            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
11672                    (oldPkgSetting == null)) {
11673                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11674                        "Couldn't find package:" + packageName + " information");
11675                return;
11676            }
11677        }
11678
11679        res.removedInfo.uid = oldPkg.applicationInfo.uid;
11680        res.removedInfo.removedPackage = packageName;
11681        // Remove existing system package
11682        removePackageLI(oldPkgSetting, true);
11683        // writer
11684        synchronized (mPackages) {
11685            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
11686            if (!disabledSystem && deletedPackage != null) {
11687                // We didn't need to disable the .apk as a current system package,
11688                // which means we are replacing another update that is already
11689                // installed.  We need to make sure to delete the older one's .apk.
11690                res.removedInfo.args = createInstallArgsForExisting(0,
11691                        deletedPackage.applicationInfo.getCodePath(),
11692                        deletedPackage.applicationInfo.getResourcePath(),
11693                        getAppDexInstructionSets(deletedPackage.applicationInfo));
11694            } else {
11695                res.removedInfo.args = null;
11696            }
11697        }
11698
11699        // Successfully disabled the old package. Now proceed with re-installation
11700        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
11701
11702        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11703        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
11704
11705        PackageParser.Package newPackage = null;
11706        try {
11707            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
11708            if (newPackage.mExtras != null) {
11709                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
11710                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
11711                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
11712
11713                // is the update attempting to change shared user? that isn't going to work...
11714                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
11715                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
11716                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
11717                            + " to " + newPkgSetting.sharedUser);
11718                    updatedSettings = true;
11719                }
11720            }
11721
11722            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11723                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11724                        perUserInstalled, res, user);
11725                updatedSettings = true;
11726            }
11727
11728        } catch (PackageManagerException e) {
11729            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11730        }
11731
11732        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11733            // Re installation failed. Restore old information
11734            // Remove new pkg information
11735            if (newPackage != null) {
11736                removeInstalledPackageLI(newPackage, true);
11737            }
11738            // Add back the old system package
11739            try {
11740                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
11741            } catch (PackageManagerException e) {
11742                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
11743            }
11744            // Restore the old system information in Settings
11745            synchronized (mPackages) {
11746                if (disabledSystem) {
11747                    mSettings.enableSystemPackageLPw(packageName);
11748                }
11749                if (updatedSettings) {
11750                    mSettings.setInstallerPackageName(packageName,
11751                            oldPkgSetting.installerPackageName);
11752                }
11753                mSettings.writeLPr();
11754            }
11755        }
11756    }
11757
11758    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
11759            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
11760            UserHandle user) {
11761        String pkgName = newPackage.packageName;
11762        synchronized (mPackages) {
11763            //write settings. the installStatus will be incomplete at this stage.
11764            //note that the new package setting would have already been
11765            //added to mPackages. It hasn't been persisted yet.
11766            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
11767            mSettings.writeLPr();
11768        }
11769
11770        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
11771
11772        synchronized (mPackages) {
11773            updatePermissionsLPw(newPackage.packageName, newPackage,
11774                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
11775                            ? UPDATE_PERMISSIONS_ALL : 0));
11776            // For system-bundled packages, we assume that installing an upgraded version
11777            // of the package implies that the user actually wants to run that new code,
11778            // so we enable the package.
11779            PackageSetting ps = mSettings.mPackages.get(pkgName);
11780            if (ps != null) {
11781                if (isSystemApp(newPackage)) {
11782                    // NB: implicit assumption that system package upgrades apply to all users
11783                    if (DEBUG_INSTALL) {
11784                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
11785                    }
11786                    if (res.origUsers != null) {
11787                        for (int userHandle : res.origUsers) {
11788                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
11789                                    userHandle, installerPackageName);
11790                        }
11791                    }
11792                    // Also convey the prior install/uninstall state
11793                    if (allUsers != null && perUserInstalled != null) {
11794                        for (int i = 0; i < allUsers.length; i++) {
11795                            if (DEBUG_INSTALL) {
11796                                Slog.d(TAG, "    user " + allUsers[i]
11797                                        + " => " + perUserInstalled[i]);
11798                            }
11799                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
11800                        }
11801                        // these install state changes will be persisted in the
11802                        // upcoming call to mSettings.writeLPr().
11803                    }
11804                }
11805                // It's implied that when a user requests installation, they want the app to be
11806                // installed and enabled.
11807                int userId = user.getIdentifier();
11808                if (userId != UserHandle.USER_ALL) {
11809                    ps.setInstalled(true, userId);
11810                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
11811                }
11812            }
11813            res.name = pkgName;
11814            res.uid = newPackage.applicationInfo.uid;
11815            res.pkg = newPackage;
11816            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
11817            mSettings.setInstallerPackageName(pkgName, installerPackageName);
11818            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11819            //to update install status
11820            mSettings.writeLPr();
11821        }
11822    }
11823
11824    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
11825        final int installFlags = args.installFlags;
11826        final String installerPackageName = args.installerPackageName;
11827        final String volumeUuid = args.volumeUuid;
11828        final File tmpPackageFile = new File(args.getCodePath());
11829        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
11830        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
11831                || (args.volumeUuid != null));
11832        boolean replace = false;
11833        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
11834        if (args.move != null) {
11835            // moving a complete application; perfom an initial scan on the new install location
11836            scanFlags |= SCAN_INITIAL;
11837        }
11838        // Result object to be returned
11839        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11840
11841        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
11842        // Retrieve PackageSettings and parse package
11843        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
11844                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
11845                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11846        PackageParser pp = new PackageParser();
11847        pp.setSeparateProcesses(mSeparateProcesses);
11848        pp.setDisplayMetrics(mMetrics);
11849
11850        final PackageParser.Package pkg;
11851        try {
11852            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
11853        } catch (PackageParserException e) {
11854            res.setError("Failed parse during installPackageLI", e);
11855            return;
11856        }
11857
11858        // Mark that we have an install time CPU ABI override.
11859        pkg.cpuAbiOverride = args.abiOverride;
11860
11861        String pkgName = res.name = pkg.packageName;
11862        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
11863            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
11864                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
11865                return;
11866            }
11867        }
11868
11869        try {
11870            pp.collectCertificates(pkg, parseFlags);
11871            pp.collectManifestDigest(pkg);
11872        } catch (PackageParserException e) {
11873            res.setError("Failed collect during installPackageLI", e);
11874            return;
11875        }
11876
11877        /* If the installer passed in a manifest digest, compare it now. */
11878        if (args.manifestDigest != null) {
11879            if (DEBUG_INSTALL) {
11880                final String parsedManifest = pkg.manifestDigest == null ? "null"
11881                        : pkg.manifestDigest.toString();
11882                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
11883                        + parsedManifest);
11884            }
11885
11886            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
11887                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
11888                return;
11889            }
11890        } else if (DEBUG_INSTALL) {
11891            final String parsedManifest = pkg.manifestDigest == null
11892                    ? "null" : pkg.manifestDigest.toString();
11893            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
11894        }
11895
11896        // Get rid of all references to package scan path via parser.
11897        pp = null;
11898        String oldCodePath = null;
11899        boolean systemApp = false;
11900        synchronized (mPackages) {
11901            // Check if installing already existing package
11902            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
11903                String oldName = mSettings.mRenamedPackages.get(pkgName);
11904                if (pkg.mOriginalPackages != null
11905                        && pkg.mOriginalPackages.contains(oldName)
11906                        && mPackages.containsKey(oldName)) {
11907                    // This package is derived from an original package,
11908                    // and this device has been updating from that original
11909                    // name.  We must continue using the original name, so
11910                    // rename the new package here.
11911                    pkg.setPackageName(oldName);
11912                    pkgName = pkg.packageName;
11913                    replace = true;
11914                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
11915                            + oldName + " pkgName=" + pkgName);
11916                } else if (mPackages.containsKey(pkgName)) {
11917                    // This package, under its official name, already exists
11918                    // on the device; we should replace it.
11919                    replace = true;
11920                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
11921                }
11922
11923                // Prevent apps opting out from runtime permissions
11924                if (replace) {
11925                    PackageParser.Package oldPackage = mPackages.get(pkgName);
11926                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
11927                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
11928                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
11929                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
11930                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
11931                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
11932                                        + " doesn't support runtime permissions but the old"
11933                                        + " target SDK " + oldTargetSdk + " does.");
11934                        return;
11935                    }
11936                }
11937            }
11938
11939            PackageSetting ps = mSettings.mPackages.get(pkgName);
11940            if (ps != null) {
11941                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
11942
11943                // Quick sanity check that we're signed correctly if updating;
11944                // we'll check this again later when scanning, but we want to
11945                // bail early here before tripping over redefined permissions.
11946                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11947                    if (!checkUpgradeKeySetLP(ps, pkg)) {
11948                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
11949                                + pkg.packageName + " upgrade keys do not match the "
11950                                + "previously installed version");
11951                        return;
11952                    }
11953                } else {
11954                    try {
11955                        verifySignaturesLP(ps, pkg);
11956                    } catch (PackageManagerException e) {
11957                        res.setError(e.error, e.getMessage());
11958                        return;
11959                    }
11960                }
11961
11962                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
11963                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
11964                    systemApp = (ps.pkg.applicationInfo.flags &
11965                            ApplicationInfo.FLAG_SYSTEM) != 0;
11966                }
11967                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
11968            }
11969
11970            // Check whether the newly-scanned package wants to define an already-defined perm
11971            int N = pkg.permissions.size();
11972            for (int i = N-1; i >= 0; i--) {
11973                PackageParser.Permission perm = pkg.permissions.get(i);
11974                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
11975                if (bp != null) {
11976                    // If the defining package is signed with our cert, it's okay.  This
11977                    // also includes the "updating the same package" case, of course.
11978                    // "updating same package" could also involve key-rotation.
11979                    final boolean sigsOk;
11980                    if (bp.sourcePackage.equals(pkg.packageName)
11981                            && (bp.packageSetting instanceof PackageSetting)
11982                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
11983                                    scanFlags))) {
11984                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
11985                    } else {
11986                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
11987                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
11988                    }
11989                    if (!sigsOk) {
11990                        // If the owning package is the system itself, we log but allow
11991                        // install to proceed; we fail the install on all other permission
11992                        // redefinitions.
11993                        if (!bp.sourcePackage.equals("android")) {
11994                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
11995                                    + pkg.packageName + " attempting to redeclare permission "
11996                                    + perm.info.name + " already owned by " + bp.sourcePackage);
11997                            res.origPermission = perm.info.name;
11998                            res.origPackage = bp.sourcePackage;
11999                            return;
12000                        } else {
12001                            Slog.w(TAG, "Package " + pkg.packageName
12002                                    + " attempting to redeclare system permission "
12003                                    + perm.info.name + "; ignoring new declaration");
12004                            pkg.permissions.remove(i);
12005                        }
12006                    }
12007                }
12008            }
12009
12010        }
12011
12012        if (systemApp && onExternal) {
12013            // Disable updates to system apps on sdcard
12014            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12015                    "Cannot install updates to system apps on sdcard");
12016            return;
12017        }
12018
12019        if (args.move != null) {
12020            // We did an in-place move, so dex is ready to roll
12021            scanFlags |= SCAN_NO_DEX;
12022            scanFlags |= SCAN_MOVE;
12023        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
12024            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
12025            scanFlags |= SCAN_NO_DEX;
12026
12027            try {
12028                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
12029                        true /* extract libs */);
12030            } catch (PackageManagerException pme) {
12031                Slog.e(TAG, "Error deriving application ABI", pme);
12032                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
12033                return;
12034            }
12035
12036            // Run dexopt before old package gets removed, to minimize time when app is unavailable
12037            int result = mPackageDexOptimizer
12038                    .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */,
12039                            false /* defer */, false /* inclDependencies */);
12040            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
12041                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
12042                return;
12043            }
12044        }
12045
12046        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
12047            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
12048            return;
12049        }
12050
12051        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
12052
12053        if (replace) {
12054            replacePackageLI(pkg, parseFlags, scanFlags, args.user,
12055                    installerPackageName, volumeUuid, res);
12056        } else {
12057            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
12058                    args.user, installerPackageName, volumeUuid, res);
12059        }
12060        synchronized (mPackages) {
12061            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12062            if (ps != null) {
12063                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12064            }
12065        }
12066    }
12067
12068    private void startIntentFilterVerifications(int userId, boolean replacing,
12069            PackageParser.Package pkg) {
12070        if (mIntentFilterVerifierComponent == null) {
12071            Slog.w(TAG, "No IntentFilter verification will not be done as "
12072                    + "there is no IntentFilterVerifier available!");
12073            return;
12074        }
12075
12076        final int verifierUid = getPackageUid(
12077                mIntentFilterVerifierComponent.getPackageName(),
12078                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
12079
12080        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
12081        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
12082        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
12083        mHandler.sendMessage(msg);
12084    }
12085
12086    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
12087            PackageParser.Package pkg) {
12088        int size = pkg.activities.size();
12089        if (size == 0) {
12090            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12091                    "No activity, so no need to verify any IntentFilter!");
12092            return;
12093        }
12094
12095        final boolean hasDomainURLs = hasDomainURLs(pkg);
12096        if (!hasDomainURLs) {
12097            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12098                    "No domain URLs, so no need to verify any IntentFilter!");
12099            return;
12100        }
12101
12102        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
12103                + " if any IntentFilter from the " + size
12104                + " Activities needs verification ...");
12105
12106        int count = 0;
12107        final String packageName = pkg.packageName;
12108
12109        synchronized (mPackages) {
12110            // If this is a new install and we see that we've already run verification for this
12111            // package, we have nothing to do: it means the state was restored from backup.
12112            if (!replacing) {
12113                IntentFilterVerificationInfo ivi =
12114                        mSettings.getIntentFilterVerificationLPr(packageName);
12115                if (ivi != null) {
12116                    if (DEBUG_DOMAIN_VERIFICATION) {
12117                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
12118                                + ivi.getStatusString());
12119                    }
12120                    return;
12121                }
12122            }
12123
12124            // If any filters need to be verified, then all need to be.
12125            boolean needToVerify = false;
12126            for (PackageParser.Activity a : pkg.activities) {
12127                for (ActivityIntentInfo filter : a.intents) {
12128                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
12129                        if (DEBUG_DOMAIN_VERIFICATION) {
12130                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
12131                        }
12132                        needToVerify = true;
12133                        break;
12134                    }
12135                }
12136            }
12137
12138            if (needToVerify) {
12139                final int verificationId = mIntentFilterVerificationToken++;
12140                for (PackageParser.Activity a : pkg.activities) {
12141                    for (ActivityIntentInfo filter : a.intents) {
12142                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
12143                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12144                                    "Verification needed for IntentFilter:" + filter.toString());
12145                            mIntentFilterVerifier.addOneIntentFilterVerification(
12146                                    verifierUid, userId, verificationId, filter, packageName);
12147                            count++;
12148                        }
12149                    }
12150                }
12151            }
12152        }
12153
12154        if (count > 0) {
12155            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
12156                    + " IntentFilter verification" + (count > 1 ? "s" : "")
12157                    +  " for userId:" + userId);
12158            mIntentFilterVerifier.startVerifications(userId);
12159        } else {
12160            if (DEBUG_DOMAIN_VERIFICATION) {
12161                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
12162            }
12163        }
12164    }
12165
12166    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
12167        final ComponentName cn  = filter.activity.getComponentName();
12168        final String packageName = cn.getPackageName();
12169
12170        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
12171                packageName);
12172        if (ivi == null) {
12173            return true;
12174        }
12175        int status = ivi.getStatus();
12176        switch (status) {
12177            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
12178            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
12179                return true;
12180
12181            default:
12182                // Nothing to do
12183                return false;
12184        }
12185    }
12186
12187    private static boolean isMultiArch(PackageSetting ps) {
12188        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12189    }
12190
12191    private static boolean isMultiArch(ApplicationInfo info) {
12192        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12193    }
12194
12195    private static boolean isExternal(PackageParser.Package pkg) {
12196        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12197    }
12198
12199    private static boolean isExternal(PackageSetting ps) {
12200        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12201    }
12202
12203    private static boolean isExternal(ApplicationInfo info) {
12204        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12205    }
12206
12207    private static boolean isSystemApp(PackageParser.Package pkg) {
12208        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
12209    }
12210
12211    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
12212        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
12213    }
12214
12215    private static boolean hasDomainURLs(PackageParser.Package pkg) {
12216        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
12217    }
12218
12219    private static boolean isSystemApp(PackageSetting ps) {
12220        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
12221    }
12222
12223    private static boolean isUpdatedSystemApp(PackageSetting ps) {
12224        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
12225    }
12226
12227    private int packageFlagsToInstallFlags(PackageSetting ps) {
12228        int installFlags = 0;
12229        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
12230            // This existing package was an external ASEC install when we have
12231            // the external flag without a UUID
12232            installFlags |= PackageManager.INSTALL_EXTERNAL;
12233        }
12234        if (ps.isForwardLocked()) {
12235            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12236        }
12237        return installFlags;
12238    }
12239
12240    private void deleteTempPackageFiles() {
12241        final FilenameFilter filter = new FilenameFilter() {
12242            public boolean accept(File dir, String name) {
12243                return name.startsWith("vmdl") && name.endsWith(".tmp");
12244            }
12245        };
12246        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
12247            file.delete();
12248        }
12249    }
12250
12251    @Override
12252    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
12253            int flags) {
12254        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
12255                flags);
12256    }
12257
12258    @Override
12259    public void deletePackage(final String packageName,
12260            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
12261        mContext.enforceCallingOrSelfPermission(
12262                android.Manifest.permission.DELETE_PACKAGES, null);
12263        final int uid = Binder.getCallingUid();
12264        if (UserHandle.getUserId(uid) != userId) {
12265            mContext.enforceCallingPermission(
12266                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
12267                    "deletePackage for user " + userId);
12268        }
12269        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
12270            try {
12271                observer.onPackageDeleted(packageName,
12272                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
12273            } catch (RemoteException re) {
12274            }
12275            return;
12276        }
12277
12278        boolean uninstallBlocked = false;
12279        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
12280            int[] users = sUserManager.getUserIds();
12281            for (int i = 0; i < users.length; ++i) {
12282                if (getBlockUninstallForUser(packageName, users[i])) {
12283                    uninstallBlocked = true;
12284                    break;
12285                }
12286            }
12287        } else {
12288            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
12289        }
12290        if (uninstallBlocked) {
12291            try {
12292                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
12293                        null);
12294            } catch (RemoteException re) {
12295            }
12296            return;
12297        }
12298
12299        if (DEBUG_REMOVE) {
12300            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
12301        }
12302        // Queue up an async operation since the package deletion may take a little while.
12303        mHandler.post(new Runnable() {
12304            public void run() {
12305                mHandler.removeCallbacks(this);
12306                final int returnCode = deletePackageX(packageName, userId, flags);
12307                if (observer != null) {
12308                    try {
12309                        observer.onPackageDeleted(packageName, returnCode, null);
12310                    } catch (RemoteException e) {
12311                        Log.i(TAG, "Observer no longer exists.");
12312                    } //end catch
12313                } //end if
12314            } //end run
12315        });
12316    }
12317
12318    private boolean isPackageDeviceAdmin(String packageName, int userId) {
12319        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12320                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12321        try {
12322            if (dpm != null) {
12323                if (dpm.isDeviceOwner(packageName)) {
12324                    return true;
12325                }
12326                int[] users;
12327                if (userId == UserHandle.USER_ALL) {
12328                    users = sUserManager.getUserIds();
12329                } else {
12330                    users = new int[]{userId};
12331                }
12332                for (int i = 0; i < users.length; ++i) {
12333                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
12334                        return true;
12335                    }
12336                }
12337            }
12338        } catch (RemoteException e) {
12339        }
12340        return false;
12341    }
12342
12343    /**
12344     *  This method is an internal method that could be get invoked either
12345     *  to delete an installed package or to clean up a failed installation.
12346     *  After deleting an installed package, a broadcast is sent to notify any
12347     *  listeners that the package has been installed. For cleaning up a failed
12348     *  installation, the broadcast is not necessary since the package's
12349     *  installation wouldn't have sent the initial broadcast either
12350     *  The key steps in deleting a package are
12351     *  deleting the package information in internal structures like mPackages,
12352     *  deleting the packages base directories through installd
12353     *  updating mSettings to reflect current status
12354     *  persisting settings for later use
12355     *  sending a broadcast if necessary
12356     */
12357    private int deletePackageX(String packageName, int userId, int flags) {
12358        final PackageRemovedInfo info = new PackageRemovedInfo();
12359        final boolean res;
12360
12361        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
12362                ? UserHandle.ALL : new UserHandle(userId);
12363
12364        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
12365            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
12366            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
12367        }
12368
12369        boolean removedForAllUsers = false;
12370        boolean systemUpdate = false;
12371
12372        // for the uninstall-updates case and restricted profiles, remember the per-
12373        // userhandle installed state
12374        int[] allUsers;
12375        boolean[] perUserInstalled;
12376        synchronized (mPackages) {
12377            PackageSetting ps = mSettings.mPackages.get(packageName);
12378            allUsers = sUserManager.getUserIds();
12379            perUserInstalled = new boolean[allUsers.length];
12380            for (int i = 0; i < allUsers.length; i++) {
12381                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12382            }
12383        }
12384
12385        synchronized (mInstallLock) {
12386            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
12387            res = deletePackageLI(packageName, removeForUser,
12388                    true, allUsers, perUserInstalled,
12389                    flags | REMOVE_CHATTY, info, true);
12390            systemUpdate = info.isRemovedPackageSystemUpdate;
12391            if (res && !systemUpdate && mPackages.get(packageName) == null) {
12392                removedForAllUsers = true;
12393            }
12394            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
12395                    + " removedForAllUsers=" + removedForAllUsers);
12396        }
12397
12398        if (res) {
12399            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
12400
12401            // If the removed package was a system update, the old system package
12402            // was re-enabled; we need to broadcast this information
12403            if (systemUpdate) {
12404                Bundle extras = new Bundle(1);
12405                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
12406                        ? info.removedAppId : info.uid);
12407                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12408
12409                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
12410                        extras, null, null, null);
12411                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
12412                        extras, null, null, null);
12413                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
12414                        null, packageName, null, null);
12415            }
12416        }
12417        // Force a gc here.
12418        Runtime.getRuntime().gc();
12419        // Delete the resources here after sending the broadcast to let
12420        // other processes clean up before deleting resources.
12421        if (info.args != null) {
12422            synchronized (mInstallLock) {
12423                info.args.doPostDeleteLI(true);
12424            }
12425        }
12426
12427        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
12428    }
12429
12430    class PackageRemovedInfo {
12431        String removedPackage;
12432        int uid = -1;
12433        int removedAppId = -1;
12434        int[] removedUsers = null;
12435        boolean isRemovedPackageSystemUpdate = false;
12436        // Clean up resources deleted packages.
12437        InstallArgs args = null;
12438
12439        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
12440            Bundle extras = new Bundle(1);
12441            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
12442            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
12443            if (replacing) {
12444                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12445            }
12446            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
12447            if (removedPackage != null) {
12448                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
12449                        extras, null, null, removedUsers);
12450                if (fullRemove && !replacing) {
12451                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
12452                            extras, null, null, removedUsers);
12453                }
12454            }
12455            if (removedAppId >= 0) {
12456                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
12457                        removedUsers);
12458            }
12459        }
12460    }
12461
12462    /*
12463     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
12464     * flag is not set, the data directory is removed as well.
12465     * make sure this flag is set for partially installed apps. If not its meaningless to
12466     * delete a partially installed application.
12467     */
12468    private void removePackageDataLI(PackageSetting ps,
12469            int[] allUserHandles, boolean[] perUserInstalled,
12470            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
12471        String packageName = ps.name;
12472        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
12473        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
12474        // Retrieve object to delete permissions for shared user later on
12475        final PackageSetting deletedPs;
12476        // reader
12477        synchronized (mPackages) {
12478            deletedPs = mSettings.mPackages.get(packageName);
12479            if (outInfo != null) {
12480                outInfo.removedPackage = packageName;
12481                outInfo.removedUsers = deletedPs != null
12482                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
12483                        : null;
12484            }
12485        }
12486        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12487            removeDataDirsLI(ps.volumeUuid, packageName);
12488            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
12489        }
12490        // writer
12491        synchronized (mPackages) {
12492            if (deletedPs != null) {
12493                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12494                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
12495                    clearDefaultBrowserIfNeeded(packageName);
12496                    if (outInfo != null) {
12497                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
12498                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
12499                    }
12500                    updatePermissionsLPw(deletedPs.name, null, 0);
12501                    if (deletedPs.sharedUser != null) {
12502                        // Remove permissions associated with package. Since runtime
12503                        // permissions are per user we have to kill the removed package
12504                        // or packages running under the shared user of the removed
12505                        // package if revoking the permissions requested only by the removed
12506                        // package is successful and this causes a change in gids.
12507                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12508                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
12509                                    userId);
12510                            if (userIdToKill == UserHandle.USER_ALL
12511                                    || userIdToKill >= UserHandle.USER_OWNER) {
12512                                // If gids changed for this user, kill all affected packages.
12513                                mHandler.post(new Runnable() {
12514                                    @Override
12515                                    public void run() {
12516                                        // This has to happen with no lock held.
12517                                        killSettingPackagesForUser(deletedPs, userIdToKill,
12518                                                KILL_APP_REASON_GIDS_CHANGED);
12519                                    }
12520                                });
12521                            break;
12522                            }
12523                        }
12524                    }
12525                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
12526                }
12527                // make sure to preserve per-user disabled state if this removal was just
12528                // a downgrade of a system app to the factory package
12529                if (allUserHandles != null && perUserInstalled != null) {
12530                    if (DEBUG_REMOVE) {
12531                        Slog.d(TAG, "Propagating install state across downgrade");
12532                    }
12533                    for (int i = 0; i < allUserHandles.length; i++) {
12534                        if (DEBUG_REMOVE) {
12535                            Slog.d(TAG, "    user " + allUserHandles[i]
12536                                    + " => " + perUserInstalled[i]);
12537                        }
12538                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12539                    }
12540                }
12541            }
12542            // can downgrade to reader
12543            if (writeSettings) {
12544                // Save settings now
12545                mSettings.writeLPr();
12546            }
12547        }
12548        if (outInfo != null) {
12549            // A user ID was deleted here. Go through all users and remove it
12550            // from KeyStore.
12551            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
12552        }
12553    }
12554
12555    static boolean locationIsPrivileged(File path) {
12556        try {
12557            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
12558                    .getCanonicalPath();
12559            return path.getCanonicalPath().startsWith(privilegedAppDir);
12560        } catch (IOException e) {
12561            Slog.e(TAG, "Unable to access code path " + path);
12562        }
12563        return false;
12564    }
12565
12566    /*
12567     * Tries to delete system package.
12568     */
12569    private boolean deleteSystemPackageLI(PackageSetting newPs,
12570            int[] allUserHandles, boolean[] perUserInstalled,
12571            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
12572        final boolean applyUserRestrictions
12573                = (allUserHandles != null) && (perUserInstalled != null);
12574        PackageSetting disabledPs = null;
12575        // Confirm if the system package has been updated
12576        // An updated system app can be deleted. This will also have to restore
12577        // the system pkg from system partition
12578        // reader
12579        synchronized (mPackages) {
12580            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
12581        }
12582        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
12583                + " disabledPs=" + disabledPs);
12584        if (disabledPs == null) {
12585            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
12586            return false;
12587        } else if (DEBUG_REMOVE) {
12588            Slog.d(TAG, "Deleting system pkg from data partition");
12589        }
12590        if (DEBUG_REMOVE) {
12591            if (applyUserRestrictions) {
12592                Slog.d(TAG, "Remembering install states:");
12593                for (int i = 0; i < allUserHandles.length; i++) {
12594                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
12595                }
12596            }
12597        }
12598        // Delete the updated package
12599        outInfo.isRemovedPackageSystemUpdate = true;
12600        if (disabledPs.versionCode < newPs.versionCode) {
12601            // Delete data for downgrades
12602            flags &= ~PackageManager.DELETE_KEEP_DATA;
12603        } else {
12604            // Preserve data by setting flag
12605            flags |= PackageManager.DELETE_KEEP_DATA;
12606        }
12607        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
12608                allUserHandles, perUserInstalled, outInfo, writeSettings);
12609        if (!ret) {
12610            return false;
12611        }
12612        // writer
12613        synchronized (mPackages) {
12614            // Reinstate the old system package
12615            mSettings.enableSystemPackageLPw(newPs.name);
12616            // Remove any native libraries from the upgraded package.
12617            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
12618        }
12619        // Install the system package
12620        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
12621        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
12622        if (locationIsPrivileged(disabledPs.codePath)) {
12623            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12624        }
12625
12626        final PackageParser.Package newPkg;
12627        try {
12628            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
12629        } catch (PackageManagerException e) {
12630            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
12631            return false;
12632        }
12633
12634        // writer
12635        synchronized (mPackages) {
12636            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
12637            updatePermissionsLPw(newPkg.packageName, newPkg,
12638                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
12639            if (applyUserRestrictions) {
12640                if (DEBUG_REMOVE) {
12641                    Slog.d(TAG, "Propagating install state across reinstall");
12642                }
12643                for (int i = 0; i < allUserHandles.length; i++) {
12644                    if (DEBUG_REMOVE) {
12645                        Slog.d(TAG, "    user " + allUserHandles[i]
12646                                + " => " + perUserInstalled[i]);
12647                    }
12648                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12649                }
12650                // Regardless of writeSettings we need to ensure that this restriction
12651                // state propagation is persisted
12652                mSettings.writeAllUsersPackageRestrictionsLPr();
12653            }
12654            // can downgrade to reader here
12655            if (writeSettings) {
12656                mSettings.writeLPr();
12657            }
12658        }
12659        return true;
12660    }
12661
12662    private boolean deleteInstalledPackageLI(PackageSetting ps,
12663            boolean deleteCodeAndResources, int flags,
12664            int[] allUserHandles, boolean[] perUserInstalled,
12665            PackageRemovedInfo outInfo, boolean writeSettings) {
12666        if (outInfo != null) {
12667            outInfo.uid = ps.appId;
12668        }
12669
12670        // Delete package data from internal structures and also remove data if flag is set
12671        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
12672
12673        // Delete application code and resources
12674        if (deleteCodeAndResources && (outInfo != null)) {
12675            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
12676                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
12677            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
12678        }
12679        return true;
12680    }
12681
12682    @Override
12683    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
12684            int userId) {
12685        mContext.enforceCallingOrSelfPermission(
12686                android.Manifest.permission.DELETE_PACKAGES, null);
12687        synchronized (mPackages) {
12688            PackageSetting ps = mSettings.mPackages.get(packageName);
12689            if (ps == null) {
12690                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
12691                return false;
12692            }
12693            if (!ps.getInstalled(userId)) {
12694                // Can't block uninstall for an app that is not installed or enabled.
12695                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
12696                return false;
12697            }
12698            ps.setBlockUninstall(blockUninstall, userId);
12699            mSettings.writePackageRestrictionsLPr(userId);
12700        }
12701        return true;
12702    }
12703
12704    @Override
12705    public boolean getBlockUninstallForUser(String packageName, int userId) {
12706        synchronized (mPackages) {
12707            PackageSetting ps = mSettings.mPackages.get(packageName);
12708            if (ps == null) {
12709                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
12710                return false;
12711            }
12712            return ps.getBlockUninstall(userId);
12713        }
12714    }
12715
12716    /*
12717     * This method handles package deletion in general
12718     */
12719    private boolean deletePackageLI(String packageName, UserHandle user,
12720            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
12721            int flags, PackageRemovedInfo outInfo,
12722            boolean writeSettings) {
12723        if (packageName == null) {
12724            Slog.w(TAG, "Attempt to delete null packageName.");
12725            return false;
12726        }
12727        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
12728        PackageSetting ps;
12729        boolean dataOnly = false;
12730        int removeUser = -1;
12731        int appId = -1;
12732        synchronized (mPackages) {
12733            ps = mSettings.mPackages.get(packageName);
12734            if (ps == null) {
12735                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12736                return false;
12737            }
12738            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
12739                    && user.getIdentifier() != UserHandle.USER_ALL) {
12740                // The caller is asking that the package only be deleted for a single
12741                // user.  To do this, we just mark its uninstalled state and delete
12742                // its data.  If this is a system app, we only allow this to happen if
12743                // they have set the special DELETE_SYSTEM_APP which requests different
12744                // semantics than normal for uninstalling system apps.
12745                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
12746                ps.setUserState(user.getIdentifier(),
12747                        COMPONENT_ENABLED_STATE_DEFAULT,
12748                        false, //installed
12749                        true,  //stopped
12750                        true,  //notLaunched
12751                        false, //hidden
12752                        null, null, null,
12753                        false, // blockUninstall
12754                        INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
12755                if (!isSystemApp(ps)) {
12756                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
12757                        // Other user still have this package installed, so all
12758                        // we need to do is clear this user's data and save that
12759                        // it is uninstalled.
12760                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
12761                        removeUser = user.getIdentifier();
12762                        appId = ps.appId;
12763                        scheduleWritePackageRestrictionsLocked(removeUser);
12764                    } else {
12765                        // We need to set it back to 'installed' so the uninstall
12766                        // broadcasts will be sent correctly.
12767                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
12768                        ps.setInstalled(true, user.getIdentifier());
12769                    }
12770                } else {
12771                    // This is a system app, so we assume that the
12772                    // other users still have this package installed, so all
12773                    // we need to do is clear this user's data and save that
12774                    // it is uninstalled.
12775                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
12776                    removeUser = user.getIdentifier();
12777                    appId = ps.appId;
12778                    scheduleWritePackageRestrictionsLocked(removeUser);
12779                }
12780            }
12781        }
12782
12783        if (removeUser >= 0) {
12784            // From above, we determined that we are deleting this only
12785            // for a single user.  Continue the work here.
12786            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
12787            if (outInfo != null) {
12788                outInfo.removedPackage = packageName;
12789                outInfo.removedAppId = appId;
12790                outInfo.removedUsers = new int[] {removeUser};
12791            }
12792            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
12793            removeKeystoreDataIfNeeded(removeUser, appId);
12794            schedulePackageCleaning(packageName, removeUser, false);
12795            synchronized (mPackages) {
12796                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
12797                    scheduleWritePackageRestrictionsLocked(removeUser);
12798                }
12799                revokeRuntimePermissionsAndClearAllFlagsLocked(ps.getPermissionsState(),
12800                        removeUser);
12801            }
12802            return true;
12803        }
12804
12805        if (dataOnly) {
12806            // Delete application data first
12807            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
12808            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
12809            return true;
12810        }
12811
12812        boolean ret = false;
12813        if (isSystemApp(ps)) {
12814            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
12815            // When an updated system application is deleted we delete the existing resources as well and
12816            // fall back to existing code in system partition
12817            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
12818                    flags, outInfo, writeSettings);
12819        } else {
12820            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
12821            // Kill application pre-emptively especially for apps on sd.
12822            killApplication(packageName, ps.appId, "uninstall pkg");
12823            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
12824                    allUserHandles, perUserInstalled,
12825                    outInfo, writeSettings);
12826        }
12827
12828        return ret;
12829    }
12830
12831    private final class ClearStorageConnection implements ServiceConnection {
12832        IMediaContainerService mContainerService;
12833
12834        @Override
12835        public void onServiceConnected(ComponentName name, IBinder service) {
12836            synchronized (this) {
12837                mContainerService = IMediaContainerService.Stub.asInterface(service);
12838                notifyAll();
12839            }
12840        }
12841
12842        @Override
12843        public void onServiceDisconnected(ComponentName name) {
12844        }
12845    }
12846
12847    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
12848        final boolean mounted;
12849        if (Environment.isExternalStorageEmulated()) {
12850            mounted = true;
12851        } else {
12852            final String status = Environment.getExternalStorageState();
12853
12854            mounted = status.equals(Environment.MEDIA_MOUNTED)
12855                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
12856        }
12857
12858        if (!mounted) {
12859            return;
12860        }
12861
12862        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
12863        int[] users;
12864        if (userId == UserHandle.USER_ALL) {
12865            users = sUserManager.getUserIds();
12866        } else {
12867            users = new int[] { userId };
12868        }
12869        final ClearStorageConnection conn = new ClearStorageConnection();
12870        if (mContext.bindServiceAsUser(
12871                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
12872            try {
12873                for (int curUser : users) {
12874                    long timeout = SystemClock.uptimeMillis() + 5000;
12875                    synchronized (conn) {
12876                        long now = SystemClock.uptimeMillis();
12877                        while (conn.mContainerService == null && now < timeout) {
12878                            try {
12879                                conn.wait(timeout - now);
12880                            } catch (InterruptedException e) {
12881                            }
12882                        }
12883                    }
12884                    if (conn.mContainerService == null) {
12885                        return;
12886                    }
12887
12888                    final UserEnvironment userEnv = new UserEnvironment(curUser);
12889                    clearDirectory(conn.mContainerService,
12890                            userEnv.buildExternalStorageAppCacheDirs(packageName));
12891                    if (allData) {
12892                        clearDirectory(conn.mContainerService,
12893                                userEnv.buildExternalStorageAppDataDirs(packageName));
12894                        clearDirectory(conn.mContainerService,
12895                                userEnv.buildExternalStorageAppMediaDirs(packageName));
12896                    }
12897                }
12898            } finally {
12899                mContext.unbindService(conn);
12900            }
12901        }
12902    }
12903
12904    @Override
12905    public void clearApplicationUserData(final String packageName,
12906            final IPackageDataObserver observer, final int userId) {
12907        mContext.enforceCallingOrSelfPermission(
12908                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
12909        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
12910        // Queue up an async operation since the package deletion may take a little while.
12911        mHandler.post(new Runnable() {
12912            public void run() {
12913                mHandler.removeCallbacks(this);
12914                final boolean succeeded;
12915                synchronized (mInstallLock) {
12916                    succeeded = clearApplicationUserDataLI(packageName, userId);
12917                }
12918                clearExternalStorageDataSync(packageName, userId, true);
12919                if (succeeded) {
12920                    // invoke DeviceStorageMonitor's update method to clear any notifications
12921                    DeviceStorageMonitorInternal
12922                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
12923                    if (dsm != null) {
12924                        dsm.checkMemory();
12925                    }
12926                }
12927                if(observer != null) {
12928                    try {
12929                        observer.onRemoveCompleted(packageName, succeeded);
12930                    } catch (RemoteException e) {
12931                        Log.i(TAG, "Observer no longer exists.");
12932                    }
12933                } //end if observer
12934            } //end run
12935        });
12936    }
12937
12938    private boolean clearApplicationUserDataLI(String packageName, int userId) {
12939        if (packageName == null) {
12940            Slog.w(TAG, "Attempt to delete null packageName.");
12941            return false;
12942        }
12943
12944        // Try finding details about the requested package
12945        PackageParser.Package pkg;
12946        synchronized (mPackages) {
12947            pkg = mPackages.get(packageName);
12948            if (pkg == null) {
12949                final PackageSetting ps = mSettings.mPackages.get(packageName);
12950                if (ps != null) {
12951                    pkg = ps.pkg;
12952                }
12953            }
12954
12955            if (pkg == null) {
12956                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12957                return false;
12958            }
12959
12960            PackageSetting ps = (PackageSetting) pkg.mExtras;
12961            PermissionsState permissionsState = ps.getPermissionsState();
12962            revokeRuntimePermissionsAndClearUserSetFlagsLocked(permissionsState, userId);
12963        }
12964
12965        // Always delete data directories for package, even if we found no other
12966        // record of app. This helps users recover from UID mismatches without
12967        // resorting to a full data wipe.
12968        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
12969        if (retCode < 0) {
12970            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
12971            return false;
12972        }
12973
12974        final int appId = pkg.applicationInfo.uid;
12975        removeKeystoreDataIfNeeded(userId, appId);
12976
12977        // Create a native library symlink only if we have native libraries
12978        // and if the native libraries are 32 bit libraries. We do not provide
12979        // this symlink for 64 bit libraries.
12980        if (pkg.applicationInfo.primaryCpuAbi != null &&
12981                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
12982            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
12983            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
12984                    nativeLibPath, userId) < 0) {
12985                Slog.w(TAG, "Failed linking native library dir");
12986                return false;
12987            }
12988        }
12989
12990        return true;
12991    }
12992
12993
12994    /**
12995     * Revokes granted runtime permissions and clears resettable flags
12996     * which are flags that can be set by a user interaction.
12997     *
12998     * @param permissionsState The permission state to reset.
12999     * @param userId The device user for which to do a reset.
13000     */
13001    private void revokeRuntimePermissionsAndClearUserSetFlagsLocked(
13002            PermissionsState permissionsState, int userId) {
13003        final int userSetFlags = PackageManager.FLAG_PERMISSION_USER_SET
13004                | PackageManager.FLAG_PERMISSION_USER_FIXED
13005                | PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13006
13007        revokeRuntimePermissionsAndClearFlagsLocked(permissionsState, userId, userSetFlags);
13008    }
13009
13010    /**
13011     * Revokes granted runtime permissions and clears all flags.
13012     *
13013     * @param permissionsState The permission state to reset.
13014     * @param userId The device user for which to do a reset.
13015     */
13016    private void revokeRuntimePermissionsAndClearAllFlagsLocked(
13017            PermissionsState permissionsState, int userId) {
13018        revokeRuntimePermissionsAndClearFlagsLocked(permissionsState, userId,
13019                PackageManager.MASK_PERMISSION_FLAGS);
13020    }
13021
13022    /**
13023     * Revokes granted runtime permissions and clears certain flags.
13024     *
13025     * @param permissionsState The permission state to reset.
13026     * @param userId The device user for which to do a reset.
13027     * @param flags The flags that is going to be reset.
13028     */
13029    private void revokeRuntimePermissionsAndClearFlagsLocked(
13030            PermissionsState permissionsState, final int userId, int flags) {
13031        boolean needsWrite = false;
13032
13033        for (PermissionState state : permissionsState.getRuntimePermissionStates(userId)) {
13034            BasePermission bp = mSettings.mPermissions.get(state.getName());
13035            if (bp != null) {
13036                permissionsState.revokeRuntimePermission(bp, userId);
13037                permissionsState.updatePermissionFlags(bp, userId, flags, 0);
13038                needsWrite = true;
13039            }
13040        }
13041
13042        // Ensure default permissions are never cleared.
13043        mHandler.post(new Runnable() {
13044            @Override
13045            public void run() {
13046                mDefaultPermissionPolicy.grantDefaultPermissions(userId);
13047            }
13048        });
13049
13050        if (needsWrite) {
13051            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
13052        }
13053    }
13054
13055    /**
13056     * Remove entries from the keystore daemon. Will only remove it if the
13057     * {@code appId} is valid.
13058     */
13059    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
13060        if (appId < 0) {
13061            return;
13062        }
13063
13064        final KeyStore keyStore = KeyStore.getInstance();
13065        if (keyStore != null) {
13066            if (userId == UserHandle.USER_ALL) {
13067                for (final int individual : sUserManager.getUserIds()) {
13068                    keyStore.clearUid(UserHandle.getUid(individual, appId));
13069                }
13070            } else {
13071                keyStore.clearUid(UserHandle.getUid(userId, appId));
13072            }
13073        } else {
13074            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
13075        }
13076    }
13077
13078    @Override
13079    public void deleteApplicationCacheFiles(final String packageName,
13080            final IPackageDataObserver observer) {
13081        mContext.enforceCallingOrSelfPermission(
13082                android.Manifest.permission.DELETE_CACHE_FILES, null);
13083        // Queue up an async operation since the package deletion may take a little while.
13084        final int userId = UserHandle.getCallingUserId();
13085        mHandler.post(new Runnable() {
13086            public void run() {
13087                mHandler.removeCallbacks(this);
13088                final boolean succeded;
13089                synchronized (mInstallLock) {
13090                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
13091                }
13092                clearExternalStorageDataSync(packageName, userId, false);
13093                if (observer != null) {
13094                    try {
13095                        observer.onRemoveCompleted(packageName, succeded);
13096                    } catch (RemoteException e) {
13097                        Log.i(TAG, "Observer no longer exists.");
13098                    }
13099                } //end if observer
13100            } //end run
13101        });
13102    }
13103
13104    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
13105        if (packageName == null) {
13106            Slog.w(TAG, "Attempt to delete null packageName.");
13107            return false;
13108        }
13109        PackageParser.Package p;
13110        synchronized (mPackages) {
13111            p = mPackages.get(packageName);
13112        }
13113        if (p == null) {
13114            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13115            return false;
13116        }
13117        final ApplicationInfo applicationInfo = p.applicationInfo;
13118        if (applicationInfo == null) {
13119            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13120            return false;
13121        }
13122        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
13123        if (retCode < 0) {
13124            Slog.w(TAG, "Couldn't remove cache files for package: "
13125                       + packageName + " u" + userId);
13126            return false;
13127        }
13128        return true;
13129    }
13130
13131    @Override
13132    public void getPackageSizeInfo(final String packageName, int userHandle,
13133            final IPackageStatsObserver observer) {
13134        mContext.enforceCallingOrSelfPermission(
13135                android.Manifest.permission.GET_PACKAGE_SIZE, null);
13136        if (packageName == null) {
13137            throw new IllegalArgumentException("Attempt to get size of null packageName");
13138        }
13139
13140        PackageStats stats = new PackageStats(packageName, userHandle);
13141
13142        /*
13143         * Queue up an async operation since the package measurement may take a
13144         * little while.
13145         */
13146        Message msg = mHandler.obtainMessage(INIT_COPY);
13147        msg.obj = new MeasureParams(stats, observer);
13148        mHandler.sendMessage(msg);
13149    }
13150
13151    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
13152            PackageStats pStats) {
13153        if (packageName == null) {
13154            Slog.w(TAG, "Attempt to get size of null packageName.");
13155            return false;
13156        }
13157        PackageParser.Package p;
13158        boolean dataOnly = false;
13159        String libDirRoot = null;
13160        String asecPath = null;
13161        PackageSetting ps = null;
13162        synchronized (mPackages) {
13163            p = mPackages.get(packageName);
13164            ps = mSettings.mPackages.get(packageName);
13165            if(p == null) {
13166                dataOnly = true;
13167                if((ps == null) || (ps.pkg == null)) {
13168                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13169                    return false;
13170                }
13171                p = ps.pkg;
13172            }
13173            if (ps != null) {
13174                libDirRoot = ps.legacyNativeLibraryPathString;
13175            }
13176            if (p != null && (isExternal(p) || p.isForwardLocked())) {
13177                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
13178                if (secureContainerId != null) {
13179                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
13180                }
13181            }
13182        }
13183        String publicSrcDir = null;
13184        if(!dataOnly) {
13185            final ApplicationInfo applicationInfo = p.applicationInfo;
13186            if (applicationInfo == null) {
13187                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13188                return false;
13189            }
13190            if (p.isForwardLocked()) {
13191                publicSrcDir = applicationInfo.getBaseResourcePath();
13192            }
13193        }
13194        // TODO: extend to measure size of split APKs
13195        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
13196        // not just the first level.
13197        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
13198        // just the primary.
13199        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
13200        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath,
13201                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
13202        if (res < 0) {
13203            return false;
13204        }
13205
13206        // Fix-up for forward-locked applications in ASEC containers.
13207        if (!isExternal(p)) {
13208            pStats.codeSize += pStats.externalCodeSize;
13209            pStats.externalCodeSize = 0L;
13210        }
13211
13212        return true;
13213    }
13214
13215
13216    @Override
13217    public void addPackageToPreferred(String packageName) {
13218        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
13219    }
13220
13221    @Override
13222    public void removePackageFromPreferred(String packageName) {
13223        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
13224    }
13225
13226    @Override
13227    public List<PackageInfo> getPreferredPackages(int flags) {
13228        return new ArrayList<PackageInfo>();
13229    }
13230
13231    private int getUidTargetSdkVersionLockedLPr(int uid) {
13232        Object obj = mSettings.getUserIdLPr(uid);
13233        if (obj instanceof SharedUserSetting) {
13234            final SharedUserSetting sus = (SharedUserSetting) obj;
13235            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
13236            final Iterator<PackageSetting> it = sus.packages.iterator();
13237            while (it.hasNext()) {
13238                final PackageSetting ps = it.next();
13239                if (ps.pkg != null) {
13240                    int v = ps.pkg.applicationInfo.targetSdkVersion;
13241                    if (v < vers) vers = v;
13242                }
13243            }
13244            return vers;
13245        } else if (obj instanceof PackageSetting) {
13246            final PackageSetting ps = (PackageSetting) obj;
13247            if (ps.pkg != null) {
13248                return ps.pkg.applicationInfo.targetSdkVersion;
13249            }
13250        }
13251        return Build.VERSION_CODES.CUR_DEVELOPMENT;
13252    }
13253
13254    @Override
13255    public void addPreferredActivity(IntentFilter filter, int match,
13256            ComponentName[] set, ComponentName activity, int userId) {
13257        addPreferredActivityInternal(filter, match, set, activity, true, userId,
13258                "Adding preferred");
13259    }
13260
13261    private void addPreferredActivityInternal(IntentFilter filter, int match,
13262            ComponentName[] set, ComponentName activity, boolean always, int userId,
13263            String opname) {
13264        // writer
13265        int callingUid = Binder.getCallingUid();
13266        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
13267        if (filter.countActions() == 0) {
13268            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13269            return;
13270        }
13271        synchronized (mPackages) {
13272            if (mContext.checkCallingOrSelfPermission(
13273                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13274                    != PackageManager.PERMISSION_GRANTED) {
13275                if (getUidTargetSdkVersionLockedLPr(callingUid)
13276                        < Build.VERSION_CODES.FROYO) {
13277                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
13278                            + callingUid);
13279                    return;
13280                }
13281                mContext.enforceCallingOrSelfPermission(
13282                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13283            }
13284
13285            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
13286            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
13287                    + userId + ":");
13288            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13289            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
13290            scheduleWritePackageRestrictionsLocked(userId);
13291        }
13292    }
13293
13294    @Override
13295    public void replacePreferredActivity(IntentFilter filter, int match,
13296            ComponentName[] set, ComponentName activity, int userId) {
13297        if (filter.countActions() != 1) {
13298            throw new IllegalArgumentException(
13299                    "replacePreferredActivity expects filter to have only 1 action.");
13300        }
13301        if (filter.countDataAuthorities() != 0
13302                || filter.countDataPaths() != 0
13303                || filter.countDataSchemes() > 1
13304                || filter.countDataTypes() != 0) {
13305            throw new IllegalArgumentException(
13306                    "replacePreferredActivity expects filter to have no data authorities, " +
13307                    "paths, or types; and at most one scheme.");
13308        }
13309
13310        final int callingUid = Binder.getCallingUid();
13311        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
13312        synchronized (mPackages) {
13313            if (mContext.checkCallingOrSelfPermission(
13314                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13315                    != PackageManager.PERMISSION_GRANTED) {
13316                if (getUidTargetSdkVersionLockedLPr(callingUid)
13317                        < Build.VERSION_CODES.FROYO) {
13318                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
13319                            + Binder.getCallingUid());
13320                    return;
13321                }
13322                mContext.enforceCallingOrSelfPermission(
13323                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13324            }
13325
13326            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13327            if (pir != null) {
13328                // Get all of the existing entries that exactly match this filter.
13329                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
13330                if (existing != null && existing.size() == 1) {
13331                    PreferredActivity cur = existing.get(0);
13332                    if (DEBUG_PREFERRED) {
13333                        Slog.i(TAG, "Checking replace of preferred:");
13334                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13335                        if (!cur.mPref.mAlways) {
13336                            Slog.i(TAG, "  -- CUR; not mAlways!");
13337                        } else {
13338                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
13339                            Slog.i(TAG, "  -- CUR: mSet="
13340                                    + Arrays.toString(cur.mPref.mSetComponents));
13341                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
13342                            Slog.i(TAG, "  -- NEW: mMatch="
13343                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
13344                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
13345                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
13346                        }
13347                    }
13348                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
13349                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
13350                            && cur.mPref.sameSet(set)) {
13351                        // Setting the preferred activity to what it happens to be already
13352                        if (DEBUG_PREFERRED) {
13353                            Slog.i(TAG, "Replacing with same preferred activity "
13354                                    + cur.mPref.mShortComponent + " for user "
13355                                    + userId + ":");
13356                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13357                        }
13358                        return;
13359                    }
13360                }
13361
13362                if (existing != null) {
13363                    if (DEBUG_PREFERRED) {
13364                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
13365                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13366                    }
13367                    for (int i = 0; i < existing.size(); i++) {
13368                        PreferredActivity pa = existing.get(i);
13369                        if (DEBUG_PREFERRED) {
13370                            Slog.i(TAG, "Removing existing preferred activity "
13371                                    + pa.mPref.mComponent + ":");
13372                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
13373                        }
13374                        pir.removeFilter(pa);
13375                    }
13376                }
13377            }
13378            addPreferredActivityInternal(filter, match, set, activity, true, userId,
13379                    "Replacing preferred");
13380        }
13381    }
13382
13383    @Override
13384    public void clearPackagePreferredActivities(String packageName) {
13385        final int uid = Binder.getCallingUid();
13386        // writer
13387        synchronized (mPackages) {
13388            PackageParser.Package pkg = mPackages.get(packageName);
13389            if (pkg == null || pkg.applicationInfo.uid != uid) {
13390                if (mContext.checkCallingOrSelfPermission(
13391                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13392                        != PackageManager.PERMISSION_GRANTED) {
13393                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
13394                            < Build.VERSION_CODES.FROYO) {
13395                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
13396                                + Binder.getCallingUid());
13397                        return;
13398                    }
13399                    mContext.enforceCallingOrSelfPermission(
13400                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13401                }
13402            }
13403
13404            int user = UserHandle.getCallingUserId();
13405            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
13406                scheduleWritePackageRestrictionsLocked(user);
13407            }
13408        }
13409    }
13410
13411    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13412    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
13413        ArrayList<PreferredActivity> removed = null;
13414        boolean changed = false;
13415        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13416            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
13417            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13418            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
13419                continue;
13420            }
13421            Iterator<PreferredActivity> it = pir.filterIterator();
13422            while (it.hasNext()) {
13423                PreferredActivity pa = it.next();
13424                // Mark entry for removal only if it matches the package name
13425                // and the entry is of type "always".
13426                if (packageName == null ||
13427                        (pa.mPref.mComponent.getPackageName().equals(packageName)
13428                                && pa.mPref.mAlways)) {
13429                    if (removed == null) {
13430                        removed = new ArrayList<PreferredActivity>();
13431                    }
13432                    removed.add(pa);
13433                }
13434            }
13435            if (removed != null) {
13436                for (int j=0; j<removed.size(); j++) {
13437                    PreferredActivity pa = removed.get(j);
13438                    pir.removeFilter(pa);
13439                }
13440                changed = true;
13441            }
13442        }
13443        return changed;
13444    }
13445
13446    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13447    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
13448        if (userId == UserHandle.USER_ALL) {
13449            if (mSettings.removeIntentFilterVerificationLPw(packageName,
13450                    sUserManager.getUserIds())) {
13451                for (int oneUserId : sUserManager.getUserIds()) {
13452                    scheduleWritePackageRestrictionsLocked(oneUserId);
13453                }
13454            }
13455        } else {
13456            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
13457                scheduleWritePackageRestrictionsLocked(userId);
13458            }
13459        }
13460    }
13461
13462
13463    void clearDefaultBrowserIfNeeded(String packageName) {
13464        for (int oneUserId : sUserManager.getUserIds()) {
13465            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
13466            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
13467            if (packageName.equals(defaultBrowserPackageName)) {
13468                setDefaultBrowserPackageName(null, oneUserId);
13469            }
13470        }
13471    }
13472
13473    @Override
13474    public void resetPreferredActivities(int userId) {
13475        mContext.enforceCallingOrSelfPermission(
13476                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13477        // writer
13478        synchronized (mPackages) {
13479            clearPackagePreferredActivitiesLPw(null, userId);
13480            mSettings.applyDefaultPreferredAppsLPw(this, userId);
13481            applyFactoryDefaultBrowserLPw(userId);
13482
13483            scheduleWritePackageRestrictionsLocked(userId);
13484        }
13485    }
13486
13487    @Override
13488    public int getPreferredActivities(List<IntentFilter> outFilters,
13489            List<ComponentName> outActivities, String packageName) {
13490
13491        int num = 0;
13492        final int userId = UserHandle.getCallingUserId();
13493        // reader
13494        synchronized (mPackages) {
13495            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13496            if (pir != null) {
13497                final Iterator<PreferredActivity> it = pir.filterIterator();
13498                while (it.hasNext()) {
13499                    final PreferredActivity pa = it.next();
13500                    if (packageName == null
13501                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
13502                                    && pa.mPref.mAlways)) {
13503                        if (outFilters != null) {
13504                            outFilters.add(new IntentFilter(pa));
13505                        }
13506                        if (outActivities != null) {
13507                            outActivities.add(pa.mPref.mComponent);
13508                        }
13509                    }
13510                }
13511            }
13512        }
13513
13514        return num;
13515    }
13516
13517    @Override
13518    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
13519            int userId) {
13520        int callingUid = Binder.getCallingUid();
13521        if (callingUid != Process.SYSTEM_UID) {
13522            throw new SecurityException(
13523                    "addPersistentPreferredActivity can only be run by the system");
13524        }
13525        if (filter.countActions() == 0) {
13526            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13527            return;
13528        }
13529        synchronized (mPackages) {
13530            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
13531                    " :");
13532            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13533            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
13534                    new PersistentPreferredActivity(filter, activity));
13535            scheduleWritePackageRestrictionsLocked(userId);
13536        }
13537    }
13538
13539    @Override
13540    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
13541        int callingUid = Binder.getCallingUid();
13542        if (callingUid != Process.SYSTEM_UID) {
13543            throw new SecurityException(
13544                    "clearPackagePersistentPreferredActivities can only be run by the system");
13545        }
13546        ArrayList<PersistentPreferredActivity> removed = null;
13547        boolean changed = false;
13548        synchronized (mPackages) {
13549            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
13550                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
13551                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
13552                        .valueAt(i);
13553                if (userId != thisUserId) {
13554                    continue;
13555                }
13556                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
13557                while (it.hasNext()) {
13558                    PersistentPreferredActivity ppa = it.next();
13559                    // Mark entry for removal only if it matches the package name.
13560                    if (ppa.mComponent.getPackageName().equals(packageName)) {
13561                        if (removed == null) {
13562                            removed = new ArrayList<PersistentPreferredActivity>();
13563                        }
13564                        removed.add(ppa);
13565                    }
13566                }
13567                if (removed != null) {
13568                    for (int j=0; j<removed.size(); j++) {
13569                        PersistentPreferredActivity ppa = removed.get(j);
13570                        ppir.removeFilter(ppa);
13571                    }
13572                    changed = true;
13573                }
13574            }
13575
13576            if (changed) {
13577                scheduleWritePackageRestrictionsLocked(userId);
13578            }
13579        }
13580    }
13581
13582    /**
13583     * Common machinery for picking apart a restored XML blob and passing
13584     * it to a caller-supplied functor to be applied to the running system.
13585     */
13586    private void restoreFromXml(XmlPullParser parser, int userId,
13587            String expectedStartTag, BlobXmlRestorer functor)
13588            throws IOException, XmlPullParserException {
13589        int type;
13590        while ((type = parser.next()) != XmlPullParser.START_TAG
13591                && type != XmlPullParser.END_DOCUMENT) {
13592        }
13593        if (type != XmlPullParser.START_TAG) {
13594            // oops didn't find a start tag?!
13595            if (DEBUG_BACKUP) {
13596                Slog.e(TAG, "Didn't find start tag during restore");
13597            }
13598            return;
13599        }
13600
13601        // this is supposed to be TAG_PREFERRED_BACKUP
13602        if (!expectedStartTag.equals(parser.getName())) {
13603            if (DEBUG_BACKUP) {
13604                Slog.e(TAG, "Found unexpected tag " + parser.getName());
13605            }
13606            return;
13607        }
13608
13609        // skip interfering stuff, then we're aligned with the backing implementation
13610        while ((type = parser.next()) == XmlPullParser.TEXT) { }
13611        functor.apply(parser, userId);
13612    }
13613
13614    private interface BlobXmlRestorer {
13615        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
13616    }
13617
13618    /**
13619     * Non-Binder method, support for the backup/restore mechanism: write the
13620     * full set of preferred activities in its canonical XML format.  Returns the
13621     * XML output as a byte array, or null if there is none.
13622     */
13623    @Override
13624    public byte[] getPreferredActivityBackup(int userId) {
13625        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13626            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
13627        }
13628
13629        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13630        try {
13631            final XmlSerializer serializer = new FastXmlSerializer();
13632            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13633            serializer.startDocument(null, true);
13634            serializer.startTag(null, TAG_PREFERRED_BACKUP);
13635
13636            synchronized (mPackages) {
13637                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
13638            }
13639
13640            serializer.endTag(null, TAG_PREFERRED_BACKUP);
13641            serializer.endDocument();
13642            serializer.flush();
13643        } catch (Exception e) {
13644            if (DEBUG_BACKUP) {
13645                Slog.e(TAG, "Unable to write preferred activities for backup", e);
13646            }
13647            return null;
13648        }
13649
13650        return dataStream.toByteArray();
13651    }
13652
13653    @Override
13654    public void restorePreferredActivities(byte[] backup, int userId) {
13655        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13656            throw new SecurityException("Only the system may call restorePreferredActivities()");
13657        }
13658
13659        try {
13660            final XmlPullParser parser = Xml.newPullParser();
13661            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13662            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
13663                    new BlobXmlRestorer() {
13664                        @Override
13665                        public void apply(XmlPullParser parser, int userId)
13666                                throws XmlPullParserException, IOException {
13667                            synchronized (mPackages) {
13668                                mSettings.readPreferredActivitiesLPw(parser, userId);
13669                            }
13670                        }
13671                    } );
13672        } catch (Exception e) {
13673            if (DEBUG_BACKUP) {
13674                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
13675            }
13676        }
13677    }
13678
13679    /**
13680     * Non-Binder method, support for the backup/restore mechanism: write the
13681     * default browser (etc) settings in its canonical XML format.  Returns the default
13682     * browser XML representation as a byte array, or null if there is none.
13683     */
13684    @Override
13685    public byte[] getDefaultAppsBackup(int userId) {
13686        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13687            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
13688        }
13689
13690        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13691        try {
13692            final XmlSerializer serializer = new FastXmlSerializer();
13693            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13694            serializer.startDocument(null, true);
13695            serializer.startTag(null, TAG_DEFAULT_APPS);
13696
13697            synchronized (mPackages) {
13698                mSettings.writeDefaultAppsLPr(serializer, userId);
13699            }
13700
13701            serializer.endTag(null, TAG_DEFAULT_APPS);
13702            serializer.endDocument();
13703            serializer.flush();
13704        } catch (Exception e) {
13705            if (DEBUG_BACKUP) {
13706                Slog.e(TAG, "Unable to write default apps for backup", e);
13707            }
13708            return null;
13709        }
13710
13711        return dataStream.toByteArray();
13712    }
13713
13714    @Override
13715    public void restoreDefaultApps(byte[] backup, int userId) {
13716        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13717            throw new SecurityException("Only the system may call restoreDefaultApps()");
13718        }
13719
13720        try {
13721            final XmlPullParser parser = Xml.newPullParser();
13722            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13723            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
13724                    new BlobXmlRestorer() {
13725                        @Override
13726                        public void apply(XmlPullParser parser, int userId)
13727                                throws XmlPullParserException, IOException {
13728                            synchronized (mPackages) {
13729                                mSettings.readDefaultAppsLPw(parser, userId);
13730                            }
13731                        }
13732                    } );
13733        } catch (Exception e) {
13734            if (DEBUG_BACKUP) {
13735                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
13736            }
13737        }
13738    }
13739
13740    @Override
13741    public byte[] getIntentFilterVerificationBackup(int userId) {
13742        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13743            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
13744        }
13745
13746        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13747        try {
13748            final XmlSerializer serializer = new FastXmlSerializer();
13749            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13750            serializer.startDocument(null, true);
13751            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
13752
13753            synchronized (mPackages) {
13754                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
13755            }
13756
13757            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
13758            serializer.endDocument();
13759            serializer.flush();
13760        } catch (Exception e) {
13761            if (DEBUG_BACKUP) {
13762                Slog.e(TAG, "Unable to write default apps for backup", e);
13763            }
13764            return null;
13765        }
13766
13767        return dataStream.toByteArray();
13768    }
13769
13770    @Override
13771    public void restoreIntentFilterVerification(byte[] backup, int userId) {
13772        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13773            throw new SecurityException("Only the system may call restorePreferredActivities()");
13774        }
13775
13776        try {
13777            final XmlPullParser parser = Xml.newPullParser();
13778            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13779            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
13780                    new BlobXmlRestorer() {
13781                        @Override
13782                        public void apply(XmlPullParser parser, int userId)
13783                                throws XmlPullParserException, IOException {
13784                            synchronized (mPackages) {
13785                                mSettings.readAllDomainVerificationsLPr(parser, userId);
13786                                mSettings.writeLPr();
13787                            }
13788                        }
13789                    } );
13790        } catch (Exception e) {
13791            if (DEBUG_BACKUP) {
13792                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
13793            }
13794        }
13795    }
13796
13797    @Override
13798    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
13799            int sourceUserId, int targetUserId, int flags) {
13800        mContext.enforceCallingOrSelfPermission(
13801                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
13802        int callingUid = Binder.getCallingUid();
13803        enforceOwnerRights(ownerPackage, callingUid);
13804        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
13805        if (intentFilter.countActions() == 0) {
13806            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
13807            return;
13808        }
13809        synchronized (mPackages) {
13810            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
13811                    ownerPackage, targetUserId, flags);
13812            CrossProfileIntentResolver resolver =
13813                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
13814            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
13815            // We have all those whose filter is equal. Now checking if the rest is equal as well.
13816            if (existing != null) {
13817                int size = existing.size();
13818                for (int i = 0; i < size; i++) {
13819                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
13820                        return;
13821                    }
13822                }
13823            }
13824            resolver.addFilter(newFilter);
13825            scheduleWritePackageRestrictionsLocked(sourceUserId);
13826        }
13827    }
13828
13829    @Override
13830    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
13831        mContext.enforceCallingOrSelfPermission(
13832                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
13833        int callingUid = Binder.getCallingUid();
13834        enforceOwnerRights(ownerPackage, callingUid);
13835        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
13836        synchronized (mPackages) {
13837            CrossProfileIntentResolver resolver =
13838                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
13839            ArraySet<CrossProfileIntentFilter> set =
13840                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
13841            for (CrossProfileIntentFilter filter : set) {
13842                if (filter.getOwnerPackage().equals(ownerPackage)) {
13843                    resolver.removeFilter(filter);
13844                }
13845            }
13846            scheduleWritePackageRestrictionsLocked(sourceUserId);
13847        }
13848    }
13849
13850    // Enforcing that callingUid is owning pkg on userId
13851    private void enforceOwnerRights(String pkg, int callingUid) {
13852        // The system owns everything.
13853        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
13854            return;
13855        }
13856        int callingUserId = UserHandle.getUserId(callingUid);
13857        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
13858        if (pi == null) {
13859            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
13860                    + callingUserId);
13861        }
13862        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
13863            throw new SecurityException("Calling uid " + callingUid
13864                    + " does not own package " + pkg);
13865        }
13866    }
13867
13868    @Override
13869    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
13870        Intent intent = new Intent(Intent.ACTION_MAIN);
13871        intent.addCategory(Intent.CATEGORY_HOME);
13872
13873        final int callingUserId = UserHandle.getCallingUserId();
13874        List<ResolveInfo> list = queryIntentActivities(intent, null,
13875                PackageManager.GET_META_DATA, callingUserId);
13876        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
13877                true, false, false, callingUserId);
13878
13879        allHomeCandidates.clear();
13880        if (list != null) {
13881            for (ResolveInfo ri : list) {
13882                allHomeCandidates.add(ri);
13883            }
13884        }
13885        return (preferred == null || preferred.activityInfo == null)
13886                ? null
13887                : new ComponentName(preferred.activityInfo.packageName,
13888                        preferred.activityInfo.name);
13889    }
13890
13891    @Override
13892    public void setApplicationEnabledSetting(String appPackageName,
13893            int newState, int flags, int userId, String callingPackage) {
13894        if (!sUserManager.exists(userId)) return;
13895        if (callingPackage == null) {
13896            callingPackage = Integer.toString(Binder.getCallingUid());
13897        }
13898        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
13899    }
13900
13901    @Override
13902    public void setComponentEnabledSetting(ComponentName componentName,
13903            int newState, int flags, int userId) {
13904        if (!sUserManager.exists(userId)) return;
13905        setEnabledSetting(componentName.getPackageName(),
13906                componentName.getClassName(), newState, flags, userId, null);
13907    }
13908
13909    private void setEnabledSetting(final String packageName, String className, int newState,
13910            final int flags, int userId, String callingPackage) {
13911        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
13912              || newState == COMPONENT_ENABLED_STATE_ENABLED
13913              || newState == COMPONENT_ENABLED_STATE_DISABLED
13914              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
13915              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
13916            throw new IllegalArgumentException("Invalid new component state: "
13917                    + newState);
13918        }
13919        PackageSetting pkgSetting;
13920        final int uid = Binder.getCallingUid();
13921        final int permission = mContext.checkCallingOrSelfPermission(
13922                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
13923        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
13924        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
13925        boolean sendNow = false;
13926        boolean isApp = (className == null);
13927        String componentName = isApp ? packageName : className;
13928        int packageUid = -1;
13929        ArrayList<String> components;
13930
13931        // writer
13932        synchronized (mPackages) {
13933            pkgSetting = mSettings.mPackages.get(packageName);
13934            if (pkgSetting == null) {
13935                if (className == null) {
13936                    throw new IllegalArgumentException(
13937                            "Unknown package: " + packageName);
13938                }
13939                throw new IllegalArgumentException(
13940                        "Unknown component: " + packageName
13941                        + "/" + className);
13942            }
13943            // Allow root and verify that userId is not being specified by a different user
13944            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
13945                throw new SecurityException(
13946                        "Permission Denial: attempt to change component state from pid="
13947                        + Binder.getCallingPid()
13948                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
13949            }
13950            if (className == null) {
13951                // We're dealing with an application/package level state change
13952                if (pkgSetting.getEnabled(userId) == newState) {
13953                    // Nothing to do
13954                    return;
13955                }
13956                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
13957                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
13958                    // Don't care about who enables an app.
13959                    callingPackage = null;
13960                }
13961                pkgSetting.setEnabled(newState, userId, callingPackage);
13962                // pkgSetting.pkg.mSetEnabled = newState;
13963            } else {
13964                // We're dealing with a component level state change
13965                // First, verify that this is a valid class name.
13966                PackageParser.Package pkg = pkgSetting.pkg;
13967                if (pkg == null || !pkg.hasComponentClassName(className)) {
13968                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
13969                        throw new IllegalArgumentException("Component class " + className
13970                                + " does not exist in " + packageName);
13971                    } else {
13972                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
13973                                + className + " does not exist in " + packageName);
13974                    }
13975                }
13976                switch (newState) {
13977                case COMPONENT_ENABLED_STATE_ENABLED:
13978                    if (!pkgSetting.enableComponentLPw(className, userId)) {
13979                        return;
13980                    }
13981                    break;
13982                case COMPONENT_ENABLED_STATE_DISABLED:
13983                    if (!pkgSetting.disableComponentLPw(className, userId)) {
13984                        return;
13985                    }
13986                    break;
13987                case COMPONENT_ENABLED_STATE_DEFAULT:
13988                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
13989                        return;
13990                    }
13991                    break;
13992                default:
13993                    Slog.e(TAG, "Invalid new component state: " + newState);
13994                    return;
13995                }
13996            }
13997            scheduleWritePackageRestrictionsLocked(userId);
13998            components = mPendingBroadcasts.get(userId, packageName);
13999            final boolean newPackage = components == null;
14000            if (newPackage) {
14001                components = new ArrayList<String>();
14002            }
14003            if (!components.contains(componentName)) {
14004                components.add(componentName);
14005            }
14006            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
14007                sendNow = true;
14008                // Purge entry from pending broadcast list if another one exists already
14009                // since we are sending one right away.
14010                mPendingBroadcasts.remove(userId, packageName);
14011            } else {
14012                if (newPackage) {
14013                    mPendingBroadcasts.put(userId, packageName, components);
14014                }
14015                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
14016                    // Schedule a message
14017                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
14018                }
14019            }
14020        }
14021
14022        long callingId = Binder.clearCallingIdentity();
14023        try {
14024            if (sendNow) {
14025                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
14026                sendPackageChangedBroadcast(packageName,
14027                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
14028            }
14029        } finally {
14030            Binder.restoreCallingIdentity(callingId);
14031        }
14032    }
14033
14034    private void sendPackageChangedBroadcast(String packageName,
14035            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
14036        if (DEBUG_INSTALL)
14037            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
14038                    + componentNames);
14039        Bundle extras = new Bundle(4);
14040        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
14041        String nameList[] = new String[componentNames.size()];
14042        componentNames.toArray(nameList);
14043        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
14044        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
14045        extras.putInt(Intent.EXTRA_UID, packageUid);
14046        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
14047                new int[] {UserHandle.getUserId(packageUid)});
14048    }
14049
14050    @Override
14051    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
14052        if (!sUserManager.exists(userId)) return;
14053        final int uid = Binder.getCallingUid();
14054        final int permission = mContext.checkCallingOrSelfPermission(
14055                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14056        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14057        enforceCrossUserPermission(uid, userId, true, true, "stop package");
14058        // writer
14059        synchronized (mPackages) {
14060            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
14061                    allowedByPermission, uid, userId)) {
14062                scheduleWritePackageRestrictionsLocked(userId);
14063            }
14064        }
14065    }
14066
14067    @Override
14068    public String getInstallerPackageName(String packageName) {
14069        // reader
14070        synchronized (mPackages) {
14071            return mSettings.getInstallerPackageNameLPr(packageName);
14072        }
14073    }
14074
14075    @Override
14076    public int getApplicationEnabledSetting(String packageName, int userId) {
14077        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14078        int uid = Binder.getCallingUid();
14079        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
14080        // reader
14081        synchronized (mPackages) {
14082            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
14083        }
14084    }
14085
14086    @Override
14087    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
14088        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14089        int uid = Binder.getCallingUid();
14090        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
14091        // reader
14092        synchronized (mPackages) {
14093            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
14094        }
14095    }
14096
14097    @Override
14098    public void enterSafeMode() {
14099        enforceSystemOrRoot("Only the system can request entering safe mode");
14100
14101        if (!mSystemReady) {
14102            mSafeMode = true;
14103        }
14104    }
14105
14106    @Override
14107    public void systemReady() {
14108        mSystemReady = true;
14109
14110        // Read the compatibilty setting when the system is ready.
14111        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
14112                mContext.getContentResolver(),
14113                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
14114        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
14115        if (DEBUG_SETTINGS) {
14116            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
14117        }
14118
14119        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
14120
14121        synchronized (mPackages) {
14122            // Verify that all of the preferred activity components actually
14123            // exist.  It is possible for applications to be updated and at
14124            // that point remove a previously declared activity component that
14125            // had been set as a preferred activity.  We try to clean this up
14126            // the next time we encounter that preferred activity, but it is
14127            // possible for the user flow to never be able to return to that
14128            // situation so here we do a sanity check to make sure we haven't
14129            // left any junk around.
14130            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
14131            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14132                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14133                removed.clear();
14134                for (PreferredActivity pa : pir.filterSet()) {
14135                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
14136                        removed.add(pa);
14137                    }
14138                }
14139                if (removed.size() > 0) {
14140                    for (int r=0; r<removed.size(); r++) {
14141                        PreferredActivity pa = removed.get(r);
14142                        Slog.w(TAG, "Removing dangling preferred activity: "
14143                                + pa.mPref.mComponent);
14144                        pir.removeFilter(pa);
14145                    }
14146                    mSettings.writePackageRestrictionsLPr(
14147                            mSettings.mPreferredActivities.keyAt(i));
14148                }
14149            }
14150
14151            for (int userId : UserManagerService.getInstance().getUserIds()) {
14152                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
14153                    grantPermissionsUserIds = ArrayUtils.appendInt(
14154                            grantPermissionsUserIds, userId);
14155                }
14156            }
14157        }
14158        sUserManager.systemReady();
14159
14160        // If we upgraded grant all default permissions before kicking off.
14161        for (int userId : grantPermissionsUserIds) {
14162            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
14163        }
14164
14165        // Kick off any messages waiting for system ready
14166        if (mPostSystemReadyMessages != null) {
14167            for (Message msg : mPostSystemReadyMessages) {
14168                msg.sendToTarget();
14169            }
14170            mPostSystemReadyMessages = null;
14171        }
14172
14173        // Watch for external volumes that come and go over time
14174        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14175        storage.registerListener(mStorageListener);
14176
14177        mInstallerService.systemReady();
14178        mPackageDexOptimizer.systemReady();
14179    }
14180
14181    @Override
14182    public boolean isSafeMode() {
14183        return mSafeMode;
14184    }
14185
14186    @Override
14187    public boolean hasSystemUidErrors() {
14188        return mHasSystemUidErrors;
14189    }
14190
14191    static String arrayToString(int[] array) {
14192        StringBuffer buf = new StringBuffer(128);
14193        buf.append('[');
14194        if (array != null) {
14195            for (int i=0; i<array.length; i++) {
14196                if (i > 0) buf.append(", ");
14197                buf.append(array[i]);
14198            }
14199        }
14200        buf.append(']');
14201        return buf.toString();
14202    }
14203
14204    static class DumpState {
14205        public static final int DUMP_LIBS = 1 << 0;
14206        public static final int DUMP_FEATURES = 1 << 1;
14207        public static final int DUMP_RESOLVERS = 1 << 2;
14208        public static final int DUMP_PERMISSIONS = 1 << 3;
14209        public static final int DUMP_PACKAGES = 1 << 4;
14210        public static final int DUMP_SHARED_USERS = 1 << 5;
14211        public static final int DUMP_MESSAGES = 1 << 6;
14212        public static final int DUMP_PROVIDERS = 1 << 7;
14213        public static final int DUMP_VERIFIERS = 1 << 8;
14214        public static final int DUMP_PREFERRED = 1 << 9;
14215        public static final int DUMP_PREFERRED_XML = 1 << 10;
14216        public static final int DUMP_KEYSETS = 1 << 11;
14217        public static final int DUMP_VERSION = 1 << 12;
14218        public static final int DUMP_INSTALLS = 1 << 13;
14219        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
14220        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
14221
14222        public static final int OPTION_SHOW_FILTERS = 1 << 0;
14223
14224        private int mTypes;
14225
14226        private int mOptions;
14227
14228        private boolean mTitlePrinted;
14229
14230        private SharedUserSetting mSharedUser;
14231
14232        public boolean isDumping(int type) {
14233            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
14234                return true;
14235            }
14236
14237            return (mTypes & type) != 0;
14238        }
14239
14240        public void setDump(int type) {
14241            mTypes |= type;
14242        }
14243
14244        public boolean isOptionEnabled(int option) {
14245            return (mOptions & option) != 0;
14246        }
14247
14248        public void setOptionEnabled(int option) {
14249            mOptions |= option;
14250        }
14251
14252        public boolean onTitlePrinted() {
14253            final boolean printed = mTitlePrinted;
14254            mTitlePrinted = true;
14255            return printed;
14256        }
14257
14258        public boolean getTitlePrinted() {
14259            return mTitlePrinted;
14260        }
14261
14262        public void setTitlePrinted(boolean enabled) {
14263            mTitlePrinted = enabled;
14264        }
14265
14266        public SharedUserSetting getSharedUser() {
14267            return mSharedUser;
14268        }
14269
14270        public void setSharedUser(SharedUserSetting user) {
14271            mSharedUser = user;
14272        }
14273    }
14274
14275    @Override
14276    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
14277        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
14278                != PackageManager.PERMISSION_GRANTED) {
14279            pw.println("Permission Denial: can't dump ActivityManager from from pid="
14280                    + Binder.getCallingPid()
14281                    + ", uid=" + Binder.getCallingUid()
14282                    + " without permission "
14283                    + android.Manifest.permission.DUMP);
14284            return;
14285        }
14286
14287        DumpState dumpState = new DumpState();
14288        boolean fullPreferred = false;
14289        boolean checkin = false;
14290
14291        String packageName = null;
14292        ArraySet<String> permissionNames = null;
14293
14294        int opti = 0;
14295        while (opti < args.length) {
14296            String opt = args[opti];
14297            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
14298                break;
14299            }
14300            opti++;
14301
14302            if ("-a".equals(opt)) {
14303                // Right now we only know how to print all.
14304            } else if ("-h".equals(opt)) {
14305                pw.println("Package manager dump options:");
14306                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
14307                pw.println("    --checkin: dump for a checkin");
14308                pw.println("    -f: print details of intent filters");
14309                pw.println("    -h: print this help");
14310                pw.println("  cmd may be one of:");
14311                pw.println("    l[ibraries]: list known shared libraries");
14312                pw.println("    f[ibraries]: list device features");
14313                pw.println("    k[eysets]: print known keysets");
14314                pw.println("    r[esolvers]: dump intent resolvers");
14315                pw.println("    perm[issions]: dump permissions");
14316                pw.println("    permission [name ...]: dump declaration and use of given permission");
14317                pw.println("    pref[erred]: print preferred package settings");
14318                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
14319                pw.println("    prov[iders]: dump content providers");
14320                pw.println("    p[ackages]: dump installed packages");
14321                pw.println("    s[hared-users]: dump shared user IDs");
14322                pw.println("    m[essages]: print collected runtime messages");
14323                pw.println("    v[erifiers]: print package verifier info");
14324                pw.println("    version: print database version info");
14325                pw.println("    write: write current settings now");
14326                pw.println("    <package.name>: info about given package");
14327                pw.println("    installs: details about install sessions");
14328                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
14329                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
14330                return;
14331            } else if ("--checkin".equals(opt)) {
14332                checkin = true;
14333            } else if ("-f".equals(opt)) {
14334                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14335            } else {
14336                pw.println("Unknown argument: " + opt + "; use -h for help");
14337            }
14338        }
14339
14340        // Is the caller requesting to dump a particular piece of data?
14341        if (opti < args.length) {
14342            String cmd = args[opti];
14343            opti++;
14344            // Is this a package name?
14345            if ("android".equals(cmd) || cmd.contains(".")) {
14346                packageName = cmd;
14347                // When dumping a single package, we always dump all of its
14348                // filter information since the amount of data will be reasonable.
14349                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14350            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
14351                dumpState.setDump(DumpState.DUMP_LIBS);
14352            } else if ("f".equals(cmd) || "features".equals(cmd)) {
14353                dumpState.setDump(DumpState.DUMP_FEATURES);
14354            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
14355                dumpState.setDump(DumpState.DUMP_RESOLVERS);
14356            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
14357                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
14358            } else if ("permission".equals(cmd)) {
14359                if (opti >= args.length) {
14360                    pw.println("Error: permission requires permission name");
14361                    return;
14362                }
14363                permissionNames = new ArraySet<>();
14364                while (opti < args.length) {
14365                    permissionNames.add(args[opti]);
14366                    opti++;
14367                }
14368                dumpState.setDump(DumpState.DUMP_PERMISSIONS
14369                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
14370            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
14371                dumpState.setDump(DumpState.DUMP_PREFERRED);
14372            } else if ("preferred-xml".equals(cmd)) {
14373                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
14374                if (opti < args.length && "--full".equals(args[opti])) {
14375                    fullPreferred = true;
14376                    opti++;
14377                }
14378            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
14379                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
14380            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
14381                dumpState.setDump(DumpState.DUMP_PACKAGES);
14382            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
14383                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
14384            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
14385                dumpState.setDump(DumpState.DUMP_PROVIDERS);
14386            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
14387                dumpState.setDump(DumpState.DUMP_MESSAGES);
14388            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
14389                dumpState.setDump(DumpState.DUMP_VERIFIERS);
14390            } else if ("i".equals(cmd) || "ifv".equals(cmd)
14391                    || "intent-filter-verifiers".equals(cmd)) {
14392                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
14393            } else if ("version".equals(cmd)) {
14394                dumpState.setDump(DumpState.DUMP_VERSION);
14395            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
14396                dumpState.setDump(DumpState.DUMP_KEYSETS);
14397            } else if ("installs".equals(cmd)) {
14398                dumpState.setDump(DumpState.DUMP_INSTALLS);
14399            } else if ("write".equals(cmd)) {
14400                synchronized (mPackages) {
14401                    mSettings.writeLPr();
14402                    pw.println("Settings written.");
14403                    return;
14404                }
14405            }
14406        }
14407
14408        if (checkin) {
14409            pw.println("vers,1");
14410        }
14411
14412        // reader
14413        synchronized (mPackages) {
14414            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
14415                if (!checkin) {
14416                    if (dumpState.onTitlePrinted())
14417                        pw.println();
14418                    pw.println("Database versions:");
14419                    pw.print("  SDK Version:");
14420                    pw.print(" internal=");
14421                    pw.print(mSettings.mInternalSdkPlatform);
14422                    pw.print(" external=");
14423                    pw.println(mSettings.mExternalSdkPlatform);
14424                    pw.print("  DB Version:");
14425                    pw.print(" internal=");
14426                    pw.print(mSettings.mInternalDatabaseVersion);
14427                    pw.print(" external=");
14428                    pw.println(mSettings.mExternalDatabaseVersion);
14429                }
14430            }
14431
14432            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
14433                if (!checkin) {
14434                    if (dumpState.onTitlePrinted())
14435                        pw.println();
14436                    pw.println("Verifiers:");
14437                    pw.print("  Required: ");
14438                    pw.print(mRequiredVerifierPackage);
14439                    pw.print(" (uid=");
14440                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
14441                    pw.println(")");
14442                } else if (mRequiredVerifierPackage != null) {
14443                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
14444                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
14445                }
14446            }
14447
14448            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
14449                    packageName == null) {
14450                if (mIntentFilterVerifierComponent != null) {
14451                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
14452                    if (!checkin) {
14453                        if (dumpState.onTitlePrinted())
14454                            pw.println();
14455                        pw.println("Intent Filter Verifier:");
14456                        pw.print("  Using: ");
14457                        pw.print(verifierPackageName);
14458                        pw.print(" (uid=");
14459                        pw.print(getPackageUid(verifierPackageName, 0));
14460                        pw.println(")");
14461                    } else if (verifierPackageName != null) {
14462                        pw.print("ifv,"); pw.print(verifierPackageName);
14463                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
14464                    }
14465                } else {
14466                    pw.println();
14467                    pw.println("No Intent Filter Verifier available!");
14468                }
14469            }
14470
14471            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
14472                boolean printedHeader = false;
14473                final Iterator<String> it = mSharedLibraries.keySet().iterator();
14474                while (it.hasNext()) {
14475                    String name = it.next();
14476                    SharedLibraryEntry ent = mSharedLibraries.get(name);
14477                    if (!checkin) {
14478                        if (!printedHeader) {
14479                            if (dumpState.onTitlePrinted())
14480                                pw.println();
14481                            pw.println("Libraries:");
14482                            printedHeader = true;
14483                        }
14484                        pw.print("  ");
14485                    } else {
14486                        pw.print("lib,");
14487                    }
14488                    pw.print(name);
14489                    if (!checkin) {
14490                        pw.print(" -> ");
14491                    }
14492                    if (ent.path != null) {
14493                        if (!checkin) {
14494                            pw.print("(jar) ");
14495                            pw.print(ent.path);
14496                        } else {
14497                            pw.print(",jar,");
14498                            pw.print(ent.path);
14499                        }
14500                    } else {
14501                        if (!checkin) {
14502                            pw.print("(apk) ");
14503                            pw.print(ent.apk);
14504                        } else {
14505                            pw.print(",apk,");
14506                            pw.print(ent.apk);
14507                        }
14508                    }
14509                    pw.println();
14510                }
14511            }
14512
14513            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
14514                if (dumpState.onTitlePrinted())
14515                    pw.println();
14516                if (!checkin) {
14517                    pw.println("Features:");
14518                }
14519                Iterator<String> it = mAvailableFeatures.keySet().iterator();
14520                while (it.hasNext()) {
14521                    String name = it.next();
14522                    if (!checkin) {
14523                        pw.print("  ");
14524                    } else {
14525                        pw.print("feat,");
14526                    }
14527                    pw.println(name);
14528                }
14529            }
14530
14531            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
14532                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
14533                        : "Activity Resolver Table:", "  ", packageName,
14534                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14535                    dumpState.setTitlePrinted(true);
14536                }
14537                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
14538                        : "Receiver Resolver Table:", "  ", packageName,
14539                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14540                    dumpState.setTitlePrinted(true);
14541                }
14542                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
14543                        : "Service Resolver Table:", "  ", packageName,
14544                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14545                    dumpState.setTitlePrinted(true);
14546                }
14547                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
14548                        : "Provider Resolver Table:", "  ", packageName,
14549                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14550                    dumpState.setTitlePrinted(true);
14551                }
14552            }
14553
14554            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
14555                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14556                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14557                    int user = mSettings.mPreferredActivities.keyAt(i);
14558                    if (pir.dump(pw,
14559                            dumpState.getTitlePrinted()
14560                                ? "\nPreferred Activities User " + user + ":"
14561                                : "Preferred Activities User " + user + ":", "  ",
14562                            packageName, true, false)) {
14563                        dumpState.setTitlePrinted(true);
14564                    }
14565                }
14566            }
14567
14568            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
14569                pw.flush();
14570                FileOutputStream fout = new FileOutputStream(fd);
14571                BufferedOutputStream str = new BufferedOutputStream(fout);
14572                XmlSerializer serializer = new FastXmlSerializer();
14573                try {
14574                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
14575                    serializer.startDocument(null, true);
14576                    serializer.setFeature(
14577                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
14578                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
14579                    serializer.endDocument();
14580                    serializer.flush();
14581                } catch (IllegalArgumentException e) {
14582                    pw.println("Failed writing: " + e);
14583                } catch (IllegalStateException e) {
14584                    pw.println("Failed writing: " + e);
14585                } catch (IOException e) {
14586                    pw.println("Failed writing: " + e);
14587                }
14588            }
14589
14590            if (!checkin
14591                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
14592                    && packageName == null) {
14593                pw.println();
14594                int count = mSettings.mPackages.size();
14595                if (count == 0) {
14596                    pw.println("No domain preferred apps!");
14597                    pw.println();
14598                } else {
14599                    final String prefix = "  ";
14600                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
14601                    if (allPackageSettings.size() == 0) {
14602                        pw.println("No domain preferred apps!");
14603                        pw.println();
14604                    } else {
14605                        pw.println("Domain preferred apps status:");
14606                        pw.println();
14607                        count = 0;
14608                        for (PackageSetting ps : allPackageSettings) {
14609                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
14610                            if (ivi == null || ivi.getPackageName() == null) continue;
14611                            pw.println(prefix + "Package Name: " + ivi.getPackageName());
14612                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
14613                            pw.println(prefix + "Status: " + ivi.getStatusString());
14614                            pw.println();
14615                            count++;
14616                        }
14617                        if (count == 0) {
14618                            pw.println(prefix + "No domain preferred app status!");
14619                            pw.println();
14620                        }
14621                        for (int userId : sUserManager.getUserIds()) {
14622                            pw.println("Domain preferred apps for User " + userId + ":");
14623                            pw.println();
14624                            count = 0;
14625                            for (PackageSetting ps : allPackageSettings) {
14626                                IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
14627                                if (ivi == null || ivi.getPackageName() == null) {
14628                                    continue;
14629                                }
14630                                final int status = ps.getDomainVerificationStatusForUser(userId);
14631                                if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
14632                                    continue;
14633                                }
14634                                pw.println(prefix + "Package Name: " + ivi.getPackageName());
14635                                pw.println(prefix + "Domains: " + ivi.getDomainsString());
14636                                String statusStr = IntentFilterVerificationInfo.
14637                                        getStatusStringFromValue(status);
14638                                pw.println(prefix + "Status: " + statusStr);
14639                                pw.println();
14640                                count++;
14641                            }
14642                            if (count == 0) {
14643                                pw.println(prefix + "No domain preferred apps!");
14644                                pw.println();
14645                            }
14646                        }
14647                    }
14648                }
14649            }
14650
14651            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
14652                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
14653                if (packageName == null && permissionNames == null) {
14654                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
14655                        if (iperm == 0) {
14656                            if (dumpState.onTitlePrinted())
14657                                pw.println();
14658                            pw.println("AppOp Permissions:");
14659                        }
14660                        pw.print("  AppOp Permission ");
14661                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
14662                        pw.println(":");
14663                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
14664                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
14665                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
14666                        }
14667                    }
14668                }
14669            }
14670
14671            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
14672                boolean printedSomething = false;
14673                for (PackageParser.Provider p : mProviders.mProviders.values()) {
14674                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14675                        continue;
14676                    }
14677                    if (!printedSomething) {
14678                        if (dumpState.onTitlePrinted())
14679                            pw.println();
14680                        pw.println("Registered ContentProviders:");
14681                        printedSomething = true;
14682                    }
14683                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
14684                    pw.print("    "); pw.println(p.toString());
14685                }
14686                printedSomething = false;
14687                for (Map.Entry<String, PackageParser.Provider> entry :
14688                        mProvidersByAuthority.entrySet()) {
14689                    PackageParser.Provider p = entry.getValue();
14690                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14691                        continue;
14692                    }
14693                    if (!printedSomething) {
14694                        if (dumpState.onTitlePrinted())
14695                            pw.println();
14696                        pw.println("ContentProvider Authorities:");
14697                        printedSomething = true;
14698                    }
14699                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
14700                    pw.print("    "); pw.println(p.toString());
14701                    if (p.info != null && p.info.applicationInfo != null) {
14702                        final String appInfo = p.info.applicationInfo.toString();
14703                        pw.print("      applicationInfo="); pw.println(appInfo);
14704                    }
14705                }
14706            }
14707
14708            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
14709                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
14710            }
14711
14712            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
14713                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
14714            }
14715
14716            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
14717                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
14718            }
14719
14720            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
14721                // XXX should handle packageName != null by dumping only install data that
14722                // the given package is involved with.
14723                if (dumpState.onTitlePrinted()) pw.println();
14724                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
14725            }
14726
14727            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
14728                if (dumpState.onTitlePrinted()) pw.println();
14729                mSettings.dumpReadMessagesLPr(pw, dumpState);
14730
14731                pw.println();
14732                pw.println("Package warning messages:");
14733                BufferedReader in = null;
14734                String line = null;
14735                try {
14736                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
14737                    while ((line = in.readLine()) != null) {
14738                        if (line.contains("ignored: updated version")) continue;
14739                        pw.println(line);
14740                    }
14741                } catch (IOException ignored) {
14742                } finally {
14743                    IoUtils.closeQuietly(in);
14744                }
14745            }
14746
14747            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
14748                BufferedReader in = null;
14749                String line = null;
14750                try {
14751                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
14752                    while ((line = in.readLine()) != null) {
14753                        if (line.contains("ignored: updated version")) continue;
14754                        pw.print("msg,");
14755                        pw.println(line);
14756                    }
14757                } catch (IOException ignored) {
14758                } finally {
14759                    IoUtils.closeQuietly(in);
14760                }
14761            }
14762        }
14763    }
14764
14765    // ------- apps on sdcard specific code -------
14766    static final boolean DEBUG_SD_INSTALL = false;
14767
14768    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
14769
14770    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
14771
14772    private boolean mMediaMounted = false;
14773
14774    static String getEncryptKey() {
14775        try {
14776            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
14777                    SD_ENCRYPTION_KEYSTORE_NAME);
14778            if (sdEncKey == null) {
14779                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
14780                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
14781                if (sdEncKey == null) {
14782                    Slog.e(TAG, "Failed to create encryption keys");
14783                    return null;
14784                }
14785            }
14786            return sdEncKey;
14787        } catch (NoSuchAlgorithmException nsae) {
14788            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
14789            return null;
14790        } catch (IOException ioe) {
14791            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
14792            return null;
14793        }
14794    }
14795
14796    /*
14797     * Update media status on PackageManager.
14798     */
14799    @Override
14800    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
14801        int callingUid = Binder.getCallingUid();
14802        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
14803            throw new SecurityException("Media status can only be updated by the system");
14804        }
14805        // reader; this apparently protects mMediaMounted, but should probably
14806        // be a different lock in that case.
14807        synchronized (mPackages) {
14808            Log.i(TAG, "Updating external media status from "
14809                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
14810                    + (mediaStatus ? "mounted" : "unmounted"));
14811            if (DEBUG_SD_INSTALL)
14812                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
14813                        + ", mMediaMounted=" + mMediaMounted);
14814            if (mediaStatus == mMediaMounted) {
14815                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
14816                        : 0, -1);
14817                mHandler.sendMessage(msg);
14818                return;
14819            }
14820            mMediaMounted = mediaStatus;
14821        }
14822        // Queue up an async operation since the package installation may take a
14823        // little while.
14824        mHandler.post(new Runnable() {
14825            public void run() {
14826                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
14827            }
14828        });
14829    }
14830
14831    /**
14832     * Called by MountService when the initial ASECs to scan are available.
14833     * Should block until all the ASEC containers are finished being scanned.
14834     */
14835    public void scanAvailableAsecs() {
14836        updateExternalMediaStatusInner(true, false, false);
14837        if (mShouldRestoreconData) {
14838            SELinuxMMAC.setRestoreconDone();
14839            mShouldRestoreconData = false;
14840        }
14841    }
14842
14843    /*
14844     * Collect information of applications on external media, map them against
14845     * existing containers and update information based on current mount status.
14846     * Please note that we always have to report status if reportStatus has been
14847     * set to true especially when unloading packages.
14848     */
14849    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
14850            boolean externalStorage) {
14851        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
14852        int[] uidArr = EmptyArray.INT;
14853
14854        final String[] list = PackageHelper.getSecureContainerList();
14855        if (ArrayUtils.isEmpty(list)) {
14856            Log.i(TAG, "No secure containers found");
14857        } else {
14858            // Process list of secure containers and categorize them
14859            // as active or stale based on their package internal state.
14860
14861            // reader
14862            synchronized (mPackages) {
14863                for (String cid : list) {
14864                    // Leave stages untouched for now; installer service owns them
14865                    if (PackageInstallerService.isStageName(cid)) continue;
14866
14867                    if (DEBUG_SD_INSTALL)
14868                        Log.i(TAG, "Processing container " + cid);
14869                    String pkgName = getAsecPackageName(cid);
14870                    if (pkgName == null) {
14871                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
14872                        continue;
14873                    }
14874                    if (DEBUG_SD_INSTALL)
14875                        Log.i(TAG, "Looking for pkg : " + pkgName);
14876
14877                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
14878                    if (ps == null) {
14879                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
14880                        continue;
14881                    }
14882
14883                    /*
14884                     * Skip packages that are not external if we're unmounting
14885                     * external storage.
14886                     */
14887                    if (externalStorage && !isMounted && !isExternal(ps)) {
14888                        continue;
14889                    }
14890
14891                    final AsecInstallArgs args = new AsecInstallArgs(cid,
14892                            getAppDexInstructionSets(ps), ps.isForwardLocked());
14893                    // The package status is changed only if the code path
14894                    // matches between settings and the container id.
14895                    if (ps.codePathString != null
14896                            && ps.codePathString.startsWith(args.getCodePath())) {
14897                        if (DEBUG_SD_INSTALL) {
14898                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
14899                                    + " at code path: " + ps.codePathString);
14900                        }
14901
14902                        // We do have a valid package installed on sdcard
14903                        processCids.put(args, ps.codePathString);
14904                        final int uid = ps.appId;
14905                        if (uid != -1) {
14906                            uidArr = ArrayUtils.appendInt(uidArr, uid);
14907                        }
14908                    } else {
14909                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
14910                                + ps.codePathString);
14911                    }
14912                }
14913            }
14914
14915            Arrays.sort(uidArr);
14916        }
14917
14918        // Process packages with valid entries.
14919        if (isMounted) {
14920            if (DEBUG_SD_INSTALL)
14921                Log.i(TAG, "Loading packages");
14922            loadMediaPackages(processCids, uidArr);
14923            startCleaningPackages();
14924            mInstallerService.onSecureContainersAvailable();
14925        } else {
14926            if (DEBUG_SD_INSTALL)
14927                Log.i(TAG, "Unloading packages");
14928            unloadMediaPackages(processCids, uidArr, reportStatus);
14929        }
14930    }
14931
14932    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14933            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
14934        final int size = infos.size();
14935        final String[] packageNames = new String[size];
14936        final int[] packageUids = new int[size];
14937        for (int i = 0; i < size; i++) {
14938            final ApplicationInfo info = infos.get(i);
14939            packageNames[i] = info.packageName;
14940            packageUids[i] = info.uid;
14941        }
14942        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
14943                finishedReceiver);
14944    }
14945
14946    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14947            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
14948        sendResourcesChangedBroadcast(mediaStatus, replacing,
14949                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
14950    }
14951
14952    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14953            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
14954        int size = pkgList.length;
14955        if (size > 0) {
14956            // Send broadcasts here
14957            Bundle extras = new Bundle();
14958            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14959            if (uidArr != null) {
14960                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
14961            }
14962            if (replacing) {
14963                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
14964            }
14965            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
14966                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
14967            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
14968        }
14969    }
14970
14971   /*
14972     * Look at potentially valid container ids from processCids If package
14973     * information doesn't match the one on record or package scanning fails,
14974     * the cid is added to list of removeCids. We currently don't delete stale
14975     * containers.
14976     */
14977    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
14978        ArrayList<String> pkgList = new ArrayList<String>();
14979        Set<AsecInstallArgs> keys = processCids.keySet();
14980
14981        for (AsecInstallArgs args : keys) {
14982            String codePath = processCids.get(args);
14983            if (DEBUG_SD_INSTALL)
14984                Log.i(TAG, "Loading container : " + args.cid);
14985            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14986            try {
14987                // Make sure there are no container errors first.
14988                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
14989                    Slog.e(TAG, "Failed to mount cid : " + args.cid
14990                            + " when installing from sdcard");
14991                    continue;
14992                }
14993                // Check code path here.
14994                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
14995                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
14996                            + " does not match one in settings " + codePath);
14997                    continue;
14998                }
14999                // Parse package
15000                int parseFlags = mDefParseFlags;
15001                if (args.isExternalAsec()) {
15002                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
15003                }
15004                if (args.isFwdLocked()) {
15005                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
15006                }
15007
15008                synchronized (mInstallLock) {
15009                    PackageParser.Package pkg = null;
15010                    try {
15011                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
15012                    } catch (PackageManagerException e) {
15013                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
15014                    }
15015                    // Scan the package
15016                    if (pkg != null) {
15017                        /*
15018                         * TODO why is the lock being held? doPostInstall is
15019                         * called in other places without the lock. This needs
15020                         * to be straightened out.
15021                         */
15022                        // writer
15023                        synchronized (mPackages) {
15024                            retCode = PackageManager.INSTALL_SUCCEEDED;
15025                            pkgList.add(pkg.packageName);
15026                            // Post process args
15027                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
15028                                    pkg.applicationInfo.uid);
15029                        }
15030                    } else {
15031                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
15032                    }
15033                }
15034
15035            } finally {
15036                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
15037                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
15038                }
15039            }
15040        }
15041        // writer
15042        synchronized (mPackages) {
15043            // If the platform SDK has changed since the last time we booted,
15044            // we need to re-grant app permission to catch any new ones that
15045            // appear. This is really a hack, and means that apps can in some
15046            // cases get permissions that the user didn't initially explicitly
15047            // allow... it would be nice to have some better way to handle
15048            // this situation.
15049            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
15050            if (regrantPermissions)
15051                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
15052                        + mSdkVersion + "; regranting permissions for external storage");
15053            mSettings.mExternalSdkPlatform = mSdkVersion;
15054
15055            // Make sure group IDs have been assigned, and any permission
15056            // changes in other apps are accounted for
15057            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
15058                    | (regrantPermissions
15059                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
15060                            : 0));
15061
15062            mSettings.updateExternalDatabaseVersion();
15063
15064            // can downgrade to reader
15065            // Persist settings
15066            mSettings.writeLPr();
15067        }
15068        // Send a broadcast to let everyone know we are done processing
15069        if (pkgList.size() > 0) {
15070            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
15071        }
15072    }
15073
15074   /*
15075     * Utility method to unload a list of specified containers
15076     */
15077    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
15078        // Just unmount all valid containers.
15079        for (AsecInstallArgs arg : cidArgs) {
15080            synchronized (mInstallLock) {
15081                arg.doPostDeleteLI(false);
15082           }
15083       }
15084   }
15085
15086    /*
15087     * Unload packages mounted on external media. This involves deleting package
15088     * data from internal structures, sending broadcasts about diabled packages,
15089     * gc'ing to free up references, unmounting all secure containers
15090     * corresponding to packages on external media, and posting a
15091     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
15092     * that we always have to post this message if status has been requested no
15093     * matter what.
15094     */
15095    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
15096            final boolean reportStatus) {
15097        if (DEBUG_SD_INSTALL)
15098            Log.i(TAG, "unloading media packages");
15099        ArrayList<String> pkgList = new ArrayList<String>();
15100        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
15101        final Set<AsecInstallArgs> keys = processCids.keySet();
15102        for (AsecInstallArgs args : keys) {
15103            String pkgName = args.getPackageName();
15104            if (DEBUG_SD_INSTALL)
15105                Log.i(TAG, "Trying to unload pkg : " + pkgName);
15106            // Delete package internally
15107            PackageRemovedInfo outInfo = new PackageRemovedInfo();
15108            synchronized (mInstallLock) {
15109                boolean res = deletePackageLI(pkgName, null, false, null, null,
15110                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
15111                if (res) {
15112                    pkgList.add(pkgName);
15113                } else {
15114                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
15115                    failedList.add(args);
15116                }
15117            }
15118        }
15119
15120        // reader
15121        synchronized (mPackages) {
15122            // We didn't update the settings after removing each package;
15123            // write them now for all packages.
15124            mSettings.writeLPr();
15125        }
15126
15127        // We have to absolutely send UPDATED_MEDIA_STATUS only
15128        // after confirming that all the receivers processed the ordered
15129        // broadcast when packages get disabled, force a gc to clean things up.
15130        // and unload all the containers.
15131        if (pkgList.size() > 0) {
15132            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
15133                    new IIntentReceiver.Stub() {
15134                public void performReceive(Intent intent, int resultCode, String data,
15135                        Bundle extras, boolean ordered, boolean sticky,
15136                        int sendingUser) throws RemoteException {
15137                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
15138                            reportStatus ? 1 : 0, 1, keys);
15139                    mHandler.sendMessage(msg);
15140                }
15141            });
15142        } else {
15143            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
15144                    keys);
15145            mHandler.sendMessage(msg);
15146        }
15147    }
15148
15149    private void loadPrivatePackages(VolumeInfo vol) {
15150        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
15151        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
15152        synchronized (mInstallLock) {
15153        synchronized (mPackages) {
15154            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15155            for (PackageSetting ps : packages) {
15156                final PackageParser.Package pkg;
15157                try {
15158                    pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null);
15159                    loaded.add(pkg.applicationInfo);
15160                } catch (PackageManagerException e) {
15161                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
15162                }
15163            }
15164
15165            // TODO: regrant any permissions that changed based since original install
15166
15167            mSettings.writeLPr();
15168        }
15169        }
15170
15171        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
15172        sendResourcesChangedBroadcast(true, false, loaded, null);
15173    }
15174
15175    private void unloadPrivatePackages(VolumeInfo vol) {
15176        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
15177        synchronized (mInstallLock) {
15178        synchronized (mPackages) {
15179            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15180            for (PackageSetting ps : packages) {
15181                if (ps.pkg == null) continue;
15182
15183                final ApplicationInfo info = ps.pkg.applicationInfo;
15184                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
15185                if (deletePackageLI(ps.name, null, false, null, null,
15186                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
15187                    unloaded.add(info);
15188                } else {
15189                    Slog.w(TAG, "Failed to unload " + ps.codePath);
15190                }
15191            }
15192
15193            mSettings.writeLPr();
15194        }
15195        }
15196
15197        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
15198        sendResourcesChangedBroadcast(false, false, unloaded, null);
15199    }
15200
15201    private void unfreezePackage(String packageName) {
15202        synchronized (mPackages) {
15203            final PackageSetting ps = mSettings.mPackages.get(packageName);
15204            if (ps != null) {
15205                ps.frozen = false;
15206            }
15207        }
15208    }
15209
15210    @Override
15211    public int movePackage(final String packageName, final String volumeUuid) {
15212        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15213
15214        final int moveId = mNextMoveId.getAndIncrement();
15215        try {
15216            movePackageInternal(packageName, volumeUuid, moveId);
15217        } catch (PackageManagerException e) {
15218            Slog.w(TAG, "Failed to move " + packageName, e);
15219            mMoveCallbacks.notifyStatusChanged(moveId,
15220                    PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15221        }
15222        return moveId;
15223    }
15224
15225    private void movePackageInternal(final String packageName, final String volumeUuid,
15226            final int moveId) throws PackageManagerException {
15227        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
15228        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15229        final PackageManager pm = mContext.getPackageManager();
15230
15231        final boolean currentAsec;
15232        final String currentVolumeUuid;
15233        final File codeFile;
15234        final String installerPackageName;
15235        final String packageAbiOverride;
15236        final int appId;
15237        final String seinfo;
15238        final String label;
15239
15240        // reader
15241        synchronized (mPackages) {
15242            final PackageParser.Package pkg = mPackages.get(packageName);
15243            final PackageSetting ps = mSettings.mPackages.get(packageName);
15244            if (pkg == null || ps == null) {
15245                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
15246            }
15247
15248            if (pkg.applicationInfo.isSystemApp()) {
15249                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
15250                        "Cannot move system application");
15251            }
15252
15253            if (Objects.equals(ps.volumeUuid, volumeUuid)) {
15254                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15255                        "Package already moved to " + volumeUuid);
15256            }
15257
15258            final File probe = new File(pkg.codePath);
15259            final File probeOat = new File(probe, "oat");
15260            if (!probe.isDirectory() || !probeOat.isDirectory()) {
15261                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15262                        "Move only supported for modern cluster style installs");
15263            }
15264
15265            if (ps.frozen) {
15266                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
15267                        "Failed to move already frozen package");
15268            }
15269            ps.frozen = true;
15270
15271            currentAsec = pkg.applicationInfo.isForwardLocked()
15272                    || pkg.applicationInfo.isExternalAsec();
15273            currentVolumeUuid = ps.volumeUuid;
15274            codeFile = new File(pkg.codePath);
15275            installerPackageName = ps.installerPackageName;
15276            packageAbiOverride = ps.cpuAbiOverrideString;
15277            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
15278            seinfo = pkg.applicationInfo.seinfo;
15279            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
15280        }
15281
15282        // Now that we're guarded by frozen state, kill app during move
15283        killApplication(packageName, appId, "move pkg");
15284
15285        final Bundle extras = new Bundle();
15286        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
15287        extras.putString(Intent.EXTRA_TITLE, label);
15288        mMoveCallbacks.notifyCreated(moveId, extras);
15289
15290        int installFlags;
15291        final boolean moveCompleteApp;
15292        final File measurePath;
15293
15294        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
15295            installFlags = INSTALL_INTERNAL;
15296            moveCompleteApp = !currentAsec;
15297            measurePath = Environment.getDataAppDirectory(volumeUuid);
15298        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
15299            installFlags = INSTALL_EXTERNAL;
15300            moveCompleteApp = false;
15301            measurePath = storage.getPrimaryPhysicalVolume().getPath();
15302        } else {
15303            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
15304            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
15305                    || !volume.isMountedWritable()) {
15306                unfreezePackage(packageName);
15307                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15308                        "Move location not mounted private volume");
15309            }
15310
15311            Preconditions.checkState(!currentAsec);
15312
15313            installFlags = INSTALL_INTERNAL;
15314            moveCompleteApp = true;
15315            measurePath = Environment.getDataAppDirectory(volumeUuid);
15316        }
15317
15318        final PackageStats stats = new PackageStats(null, -1);
15319        synchronized (mInstaller) {
15320            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
15321                unfreezePackage(packageName);
15322                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15323                        "Failed to measure package size");
15324            }
15325        }
15326
15327        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
15328                + stats.dataSize);
15329
15330        final long startFreeBytes = measurePath.getFreeSpace();
15331        final long sizeBytes;
15332        if (moveCompleteApp) {
15333            sizeBytes = stats.codeSize + stats.dataSize;
15334        } else {
15335            sizeBytes = stats.codeSize;
15336        }
15337
15338        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
15339            unfreezePackage(packageName);
15340            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15341                    "Not enough free space to move");
15342        }
15343
15344        mMoveCallbacks.notifyStatusChanged(moveId, 10);
15345
15346        final CountDownLatch installedLatch = new CountDownLatch(1);
15347        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
15348            @Override
15349            public void onUserActionRequired(Intent intent) throws RemoteException {
15350                throw new IllegalStateException();
15351            }
15352
15353            @Override
15354            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
15355                    Bundle extras) throws RemoteException {
15356                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
15357                        + PackageManager.installStatusToString(returnCode, msg));
15358
15359                installedLatch.countDown();
15360
15361                // Regardless of success or failure of the move operation,
15362                // always unfreeze the package
15363                unfreezePackage(packageName);
15364
15365                final int status = PackageManager.installStatusToPublicStatus(returnCode);
15366                switch (status) {
15367                    case PackageInstaller.STATUS_SUCCESS:
15368                        mMoveCallbacks.notifyStatusChanged(moveId,
15369                                PackageManager.MOVE_SUCCEEDED);
15370                        break;
15371                    case PackageInstaller.STATUS_FAILURE_STORAGE:
15372                        mMoveCallbacks.notifyStatusChanged(moveId,
15373                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
15374                        break;
15375                    default:
15376                        mMoveCallbacks.notifyStatusChanged(moveId,
15377                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15378                        break;
15379                }
15380            }
15381        };
15382
15383        final MoveInfo move;
15384        if (moveCompleteApp) {
15385            // Kick off a thread to report progress estimates
15386            new Thread() {
15387                @Override
15388                public void run() {
15389                    while (true) {
15390                        try {
15391                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
15392                                break;
15393                            }
15394                        } catch (InterruptedException ignored) {
15395                        }
15396
15397                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
15398                        final int progress = 10 + (int) MathUtils.constrain(
15399                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
15400                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
15401                    }
15402                }
15403            }.start();
15404
15405            final String dataAppName = codeFile.getName();
15406            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
15407                    dataAppName, appId, seinfo);
15408        } else {
15409            move = null;
15410        }
15411
15412        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
15413
15414        final Message msg = mHandler.obtainMessage(INIT_COPY);
15415        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
15416        msg.obj = new InstallParams(origin, move, installObserver, installFlags,
15417                installerPackageName, volumeUuid, null, user, packageAbiOverride);
15418        mHandler.sendMessage(msg);
15419    }
15420
15421    @Override
15422    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
15423        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15424
15425        final int realMoveId = mNextMoveId.getAndIncrement();
15426        final Bundle extras = new Bundle();
15427        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
15428        mMoveCallbacks.notifyCreated(realMoveId, extras);
15429
15430        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
15431            @Override
15432            public void onCreated(int moveId, Bundle extras) {
15433                // Ignored
15434            }
15435
15436            @Override
15437            public void onStatusChanged(int moveId, int status, long estMillis) {
15438                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
15439            }
15440        };
15441
15442        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15443        storage.setPrimaryStorageUuid(volumeUuid, callback);
15444        return realMoveId;
15445    }
15446
15447    @Override
15448    public int getMoveStatus(int moveId) {
15449        mContext.enforceCallingOrSelfPermission(
15450                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15451        return mMoveCallbacks.mLastStatus.get(moveId);
15452    }
15453
15454    @Override
15455    public void registerMoveCallback(IPackageMoveObserver callback) {
15456        mContext.enforceCallingOrSelfPermission(
15457                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15458        mMoveCallbacks.register(callback);
15459    }
15460
15461    @Override
15462    public void unregisterMoveCallback(IPackageMoveObserver callback) {
15463        mContext.enforceCallingOrSelfPermission(
15464                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15465        mMoveCallbacks.unregister(callback);
15466    }
15467
15468    @Override
15469    public boolean setInstallLocation(int loc) {
15470        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
15471                null);
15472        if (getInstallLocation() == loc) {
15473            return true;
15474        }
15475        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
15476                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
15477            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
15478                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
15479            return true;
15480        }
15481        return false;
15482   }
15483
15484    @Override
15485    public int getInstallLocation() {
15486        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15487                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
15488                PackageHelper.APP_INSTALL_AUTO);
15489    }
15490
15491    /** Called by UserManagerService */
15492    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
15493        mDirtyUsers.remove(userHandle);
15494        mSettings.removeUserLPw(userHandle);
15495        mPendingBroadcasts.remove(userHandle);
15496        if (mInstaller != null) {
15497            // Technically, we shouldn't be doing this with the package lock
15498            // held.  However, this is very rare, and there is already so much
15499            // other disk I/O going on, that we'll let it slide for now.
15500            final StorageManager storage = StorageManager.from(mContext);
15501            final List<VolumeInfo> vols = storage.getVolumes();
15502            for (VolumeInfo vol : vols) {
15503                if (vol.getType() == VolumeInfo.TYPE_PRIVATE && vol.isMountedWritable()) {
15504                    final String volumeUuid = vol.getFsUuid();
15505                    if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
15506                    mInstaller.removeUserDataDirs(volumeUuid, userHandle);
15507                }
15508            }
15509        }
15510        mUserNeedsBadging.delete(userHandle);
15511        removeUnusedPackagesLILPw(userManager, userHandle);
15512    }
15513
15514    /**
15515     * We're removing userHandle and would like to remove any downloaded packages
15516     * that are no longer in use by any other user.
15517     * @param userHandle the user being removed
15518     */
15519    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
15520        final boolean DEBUG_CLEAN_APKS = false;
15521        int [] users = userManager.getUserIdsLPr();
15522        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
15523        while (psit.hasNext()) {
15524            PackageSetting ps = psit.next();
15525            if (ps.pkg == null) {
15526                continue;
15527            }
15528            final String packageName = ps.pkg.packageName;
15529            // Skip over if system app
15530            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15531                continue;
15532            }
15533            if (DEBUG_CLEAN_APKS) {
15534                Slog.i(TAG, "Checking package " + packageName);
15535            }
15536            boolean keep = false;
15537            for (int i = 0; i < users.length; i++) {
15538                if (users[i] != userHandle && ps.getInstalled(users[i])) {
15539                    keep = true;
15540                    if (DEBUG_CLEAN_APKS) {
15541                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
15542                                + users[i]);
15543                    }
15544                    break;
15545                }
15546            }
15547            if (!keep) {
15548                if (DEBUG_CLEAN_APKS) {
15549                    Slog.i(TAG, "  Removing package " + packageName);
15550                }
15551                mHandler.post(new Runnable() {
15552                    public void run() {
15553                        deletePackageX(packageName, userHandle, 0);
15554                    } //end run
15555                });
15556            }
15557        }
15558    }
15559
15560    /** Called by UserManagerService */
15561    void createNewUserLILPw(int userHandle, File path) {
15562        if (mInstaller != null) {
15563            mInstaller.createUserConfig(userHandle);
15564            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
15565            applyFactoryDefaultBrowserLPw(userHandle);
15566        }
15567    }
15568
15569    void newUserCreatedLILPw(final int userHandle) {
15570        // We cannot grant the default permissions with a lock held as
15571        // we query providers from other components for default handlers
15572        // such as enabled IMEs, etc.
15573        mHandler.post(new Runnable() {
15574            @Override
15575            public void run() {
15576                mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
15577            }
15578        });
15579    }
15580
15581    @Override
15582    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
15583        mContext.enforceCallingOrSelfPermission(
15584                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15585                "Only package verification agents can read the verifier device identity");
15586
15587        synchronized (mPackages) {
15588            return mSettings.getVerifierDeviceIdentityLPw();
15589        }
15590    }
15591
15592    @Override
15593    public void setPermissionEnforced(String permission, boolean enforced) {
15594        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
15595        if (READ_EXTERNAL_STORAGE.equals(permission)) {
15596            synchronized (mPackages) {
15597                if (mSettings.mReadExternalStorageEnforced == null
15598                        || mSettings.mReadExternalStorageEnforced != enforced) {
15599                    mSettings.mReadExternalStorageEnforced = enforced;
15600                    mSettings.writeLPr();
15601                }
15602            }
15603            // kill any non-foreground processes so we restart them and
15604            // grant/revoke the GID.
15605            final IActivityManager am = ActivityManagerNative.getDefault();
15606            if (am != null) {
15607                final long token = Binder.clearCallingIdentity();
15608                try {
15609                    am.killProcessesBelowForeground("setPermissionEnforcement");
15610                } catch (RemoteException e) {
15611                } finally {
15612                    Binder.restoreCallingIdentity(token);
15613                }
15614            }
15615        } else {
15616            throw new IllegalArgumentException("No selective enforcement for " + permission);
15617        }
15618    }
15619
15620    @Override
15621    @Deprecated
15622    public boolean isPermissionEnforced(String permission) {
15623        return true;
15624    }
15625
15626    @Override
15627    public boolean isStorageLow() {
15628        final long token = Binder.clearCallingIdentity();
15629        try {
15630            final DeviceStorageMonitorInternal
15631                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
15632            if (dsm != null) {
15633                return dsm.isMemoryLow();
15634            } else {
15635                return false;
15636            }
15637        } finally {
15638            Binder.restoreCallingIdentity(token);
15639        }
15640    }
15641
15642    @Override
15643    public IPackageInstaller getPackageInstaller() {
15644        return mInstallerService;
15645    }
15646
15647    private boolean userNeedsBadging(int userId) {
15648        int index = mUserNeedsBadging.indexOfKey(userId);
15649        if (index < 0) {
15650            final UserInfo userInfo;
15651            final long token = Binder.clearCallingIdentity();
15652            try {
15653                userInfo = sUserManager.getUserInfo(userId);
15654            } finally {
15655                Binder.restoreCallingIdentity(token);
15656            }
15657            final boolean b;
15658            if (userInfo != null && userInfo.isManagedProfile()) {
15659                b = true;
15660            } else {
15661                b = false;
15662            }
15663            mUserNeedsBadging.put(userId, b);
15664            return b;
15665        }
15666        return mUserNeedsBadging.valueAt(index);
15667    }
15668
15669    @Override
15670    public KeySet getKeySetByAlias(String packageName, String alias) {
15671        if (packageName == null || alias == null) {
15672            return null;
15673        }
15674        synchronized(mPackages) {
15675            final PackageParser.Package pkg = mPackages.get(packageName);
15676            if (pkg == null) {
15677                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15678                throw new IllegalArgumentException("Unknown package: " + packageName);
15679            }
15680            KeySetManagerService ksms = mSettings.mKeySetManagerService;
15681            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
15682        }
15683    }
15684
15685    @Override
15686    public KeySet getSigningKeySet(String packageName) {
15687        if (packageName == null) {
15688            return null;
15689        }
15690        synchronized(mPackages) {
15691            final PackageParser.Package pkg = mPackages.get(packageName);
15692            if (pkg == null) {
15693                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15694                throw new IllegalArgumentException("Unknown package: " + packageName);
15695            }
15696            if (pkg.applicationInfo.uid != Binder.getCallingUid()
15697                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
15698                throw new SecurityException("May not access signing KeySet of other apps.");
15699            }
15700            KeySetManagerService ksms = mSettings.mKeySetManagerService;
15701            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
15702        }
15703    }
15704
15705    @Override
15706    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
15707        if (packageName == null || ks == null) {
15708            return false;
15709        }
15710        synchronized(mPackages) {
15711            final PackageParser.Package pkg = mPackages.get(packageName);
15712            if (pkg == null) {
15713                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15714                throw new IllegalArgumentException("Unknown package: " + packageName);
15715            }
15716            IBinder ksh = ks.getToken();
15717            if (ksh instanceof KeySetHandle) {
15718                KeySetManagerService ksms = mSettings.mKeySetManagerService;
15719                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
15720            }
15721            return false;
15722        }
15723    }
15724
15725    @Override
15726    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
15727        if (packageName == null || ks == null) {
15728            return false;
15729        }
15730        synchronized(mPackages) {
15731            final PackageParser.Package pkg = mPackages.get(packageName);
15732            if (pkg == null) {
15733                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15734                throw new IllegalArgumentException("Unknown package: " + packageName);
15735            }
15736            IBinder ksh = ks.getToken();
15737            if (ksh instanceof KeySetHandle) {
15738                KeySetManagerService ksms = mSettings.mKeySetManagerService;
15739                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
15740            }
15741            return false;
15742        }
15743    }
15744
15745    public void getUsageStatsIfNoPackageUsageInfo() {
15746        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
15747            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
15748            if (usm == null) {
15749                throw new IllegalStateException("UsageStatsManager must be initialized");
15750            }
15751            long now = System.currentTimeMillis();
15752            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
15753            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
15754                String packageName = entry.getKey();
15755                PackageParser.Package pkg = mPackages.get(packageName);
15756                if (pkg == null) {
15757                    continue;
15758                }
15759                UsageStats usage = entry.getValue();
15760                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
15761                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
15762            }
15763        }
15764    }
15765
15766    /**
15767     * Check and throw if the given before/after packages would be considered a
15768     * downgrade.
15769     */
15770    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
15771            throws PackageManagerException {
15772        if (after.versionCode < before.mVersionCode) {
15773            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15774                    "Update version code " + after.versionCode + " is older than current "
15775                    + before.mVersionCode);
15776        } else if (after.versionCode == before.mVersionCode) {
15777            if (after.baseRevisionCode < before.baseRevisionCode) {
15778                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15779                        "Update base revision code " + after.baseRevisionCode
15780                        + " is older than current " + before.baseRevisionCode);
15781            }
15782
15783            if (!ArrayUtils.isEmpty(after.splitNames)) {
15784                for (int i = 0; i < after.splitNames.length; i++) {
15785                    final String splitName = after.splitNames[i];
15786                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
15787                    if (j != -1) {
15788                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
15789                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15790                                    "Update split " + splitName + " revision code "
15791                                    + after.splitRevisionCodes[i] + " is older than current "
15792                                    + before.splitRevisionCodes[j]);
15793                        }
15794                    }
15795                }
15796            }
15797        }
15798    }
15799
15800    private static class MoveCallbacks extends Handler {
15801        private static final int MSG_CREATED = 1;
15802        private static final int MSG_STATUS_CHANGED = 2;
15803
15804        private final RemoteCallbackList<IPackageMoveObserver>
15805                mCallbacks = new RemoteCallbackList<>();
15806
15807        private final SparseIntArray mLastStatus = new SparseIntArray();
15808
15809        public MoveCallbacks(Looper looper) {
15810            super(looper);
15811        }
15812
15813        public void register(IPackageMoveObserver callback) {
15814            mCallbacks.register(callback);
15815        }
15816
15817        public void unregister(IPackageMoveObserver callback) {
15818            mCallbacks.unregister(callback);
15819        }
15820
15821        @Override
15822        public void handleMessage(Message msg) {
15823            final SomeArgs args = (SomeArgs) msg.obj;
15824            final int n = mCallbacks.beginBroadcast();
15825            for (int i = 0; i < n; i++) {
15826                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
15827                try {
15828                    invokeCallback(callback, msg.what, args);
15829                } catch (RemoteException ignored) {
15830                }
15831            }
15832            mCallbacks.finishBroadcast();
15833            args.recycle();
15834        }
15835
15836        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
15837                throws RemoteException {
15838            switch (what) {
15839                case MSG_CREATED: {
15840                    callback.onCreated(args.argi1, (Bundle) args.arg2);
15841                    break;
15842                }
15843                case MSG_STATUS_CHANGED: {
15844                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
15845                    break;
15846                }
15847            }
15848        }
15849
15850        private void notifyCreated(int moveId, Bundle extras) {
15851            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
15852
15853            final SomeArgs args = SomeArgs.obtain();
15854            args.argi1 = moveId;
15855            args.arg2 = extras;
15856            obtainMessage(MSG_CREATED, args).sendToTarget();
15857        }
15858
15859        private void notifyStatusChanged(int moveId, int status) {
15860            notifyStatusChanged(moveId, status, -1);
15861        }
15862
15863        private void notifyStatusChanged(int moveId, int status, long estMillis) {
15864            Slog.v(TAG, "Move " + moveId + " status " + status);
15865
15866            final SomeArgs args = SomeArgs.obtain();
15867            args.argi1 = moveId;
15868            args.argi2 = status;
15869            args.arg3 = estMillis;
15870            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
15871
15872            synchronized (mLastStatus) {
15873                mLastStatus.put(moveId, status);
15874            }
15875        }
15876    }
15877
15878    private final class OnPermissionChangeListeners extends Handler {
15879        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
15880
15881        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
15882                new RemoteCallbackList<>();
15883
15884        public OnPermissionChangeListeners(Looper looper) {
15885            super(looper);
15886        }
15887
15888        @Override
15889        public void handleMessage(Message msg) {
15890            switch (msg.what) {
15891                case MSG_ON_PERMISSIONS_CHANGED: {
15892                    final int uid = msg.arg1;
15893                    handleOnPermissionsChanged(uid);
15894                } break;
15895            }
15896        }
15897
15898        public void addListenerLocked(IOnPermissionsChangeListener listener) {
15899            mPermissionListeners.register(listener);
15900
15901        }
15902
15903        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
15904            mPermissionListeners.unregister(listener);
15905        }
15906
15907        public void onPermissionsChanged(int uid) {
15908            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
15909                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
15910            }
15911        }
15912
15913        private void handleOnPermissionsChanged(int uid) {
15914            final int count = mPermissionListeners.beginBroadcast();
15915            try {
15916                for (int i = 0; i < count; i++) {
15917                    IOnPermissionsChangeListener callback = mPermissionListeners
15918                            .getBroadcastItem(i);
15919                    try {
15920                        callback.onPermissionsChanged(uid);
15921                    } catch (RemoteException e) {
15922                        Log.e(TAG, "Permission listener is dead", e);
15923                    }
15924                }
15925            } finally {
15926                mPermissionListeners.finishBroadcast();
15927            }
15928        }
15929    }
15930
15931    private class PackageManagerInternalImpl extends PackageManagerInternal {
15932        @Override
15933        public void setLocationPackagesProvider(PackagesProvider provider) {
15934            synchronized (mPackages) {
15935                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
15936            }
15937        }
15938
15939        @Override
15940        public void setImePackagesProvider(PackagesProvider provider) {
15941            synchronized (mPackages) {
15942                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
15943            }
15944        }
15945
15946        @Override
15947        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
15948            synchronized (mPackages) {
15949                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
15950            }
15951        }
15952
15953        @Override
15954        public void setSmsAppPackagesProvider(PackagesProvider provider) {
15955            synchronized (mPackages) {
15956                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
15957            }
15958        }
15959
15960        @Override
15961        public void setDialerAppPackagesProvider(PackagesProvider provider) {
15962            synchronized (mPackages) {
15963                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
15964            }
15965        }
15966
15967        @Override
15968        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
15969            synchronized (mPackages) {
15970                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
15971                        packageName, userId);
15972            }
15973        }
15974
15975        @Override
15976        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
15977            synchronized (mPackages) {
15978                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
15979                        packageName, userId);
15980            }
15981        }
15982    }
15983
15984    @Override
15985    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
15986        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
15987        synchronized (mPackages) {
15988            mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
15989                    packageNames, userId);
15990        }
15991    }
15992
15993    private static void enforceSystemOrPhoneCaller(String tag) {
15994        int callingUid = Binder.getCallingUid();
15995        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
15996            throw new SecurityException(
15997                    "Cannot call " + tag + " from UID " + callingUid);
15998        }
15999    }
16000}
16001