PackageManagerService.java revision 2956363244ecb61f48729d93b510ffadac591cae
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.GRANT_REVOKE_PERMISSIONS;
20import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
21import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
27import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
28import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
29import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
30import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT;
31import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
32import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
33import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
34import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
35import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
36import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
37import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
38import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
39import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
40import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
41import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
42import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED;
43import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
44import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
45import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
46import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
47import static android.content.pm.PackageManager.INSTALL_INTERNAL;
48import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
49import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
50import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
51import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
52import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
53import static android.content.pm.PackageManager.MATCH_ALL;
54import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
55import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
56import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
57import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
58import static android.content.pm.PackageManager.PERMISSION_GRANTED;
59import static android.content.pm.PackageParser.isApkFile;
60import static android.os.Process.PACKAGE_INFO_GID;
61import static android.os.Process.SYSTEM_UID;
62import static android.system.OsConstants.O_CREAT;
63import static android.system.OsConstants.O_RDWR;
64import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
65import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER;
66import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
67import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
68import static com.android.internal.util.ArrayUtils.appendInt;
69import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
70import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
71import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
72import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
73import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
74
75import android.Manifest;
76import android.app.ActivityManager;
77import android.app.ActivityManagerNative;
78import android.app.AppGlobals;
79import android.app.IActivityManager;
80import android.app.admin.IDevicePolicyManager;
81import android.app.backup.IBackupManager;
82import android.app.usage.UsageStats;
83import android.app.usage.UsageStatsManager;
84import android.content.BroadcastReceiver;
85import android.content.ComponentName;
86import android.content.Context;
87import android.content.IIntentReceiver;
88import android.content.Intent;
89import android.content.IntentFilter;
90import android.content.IntentSender;
91import android.content.IntentSender.SendIntentException;
92import android.content.ServiceConnection;
93import android.content.pm.ActivityInfo;
94import android.content.pm.ApplicationInfo;
95import android.content.pm.FeatureInfo;
96import android.content.pm.IOnPermissionsChangeListener;
97import android.content.pm.IPackageDataObserver;
98import android.content.pm.IPackageDeleteObserver;
99import android.content.pm.IPackageDeleteObserver2;
100import android.content.pm.IPackageInstallObserver2;
101import android.content.pm.IPackageInstaller;
102import android.content.pm.IPackageManager;
103import android.content.pm.IPackageMoveObserver;
104import android.content.pm.IPackageStatsObserver;
105import android.content.pm.InstrumentationInfo;
106import android.content.pm.IntentFilterVerificationInfo;
107import android.content.pm.KeySet;
108import android.content.pm.ManifestDigest;
109import android.content.pm.PackageCleanItem;
110import android.content.pm.PackageInfo;
111import android.content.pm.PackageInfoLite;
112import android.content.pm.PackageInstaller;
113import android.content.pm.PackageManager;
114import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
115import android.content.pm.PackageManagerInternal;
116import android.content.pm.PackageParser;
117import android.content.pm.PackageParser.ActivityIntentInfo;
118import android.content.pm.PackageParser.PackageLite;
119import android.content.pm.PackageParser.PackageParserException;
120import android.content.pm.PackageStats;
121import android.content.pm.PackageUserState;
122import android.content.pm.ParceledListSlice;
123import android.content.pm.PermissionGroupInfo;
124import android.content.pm.PermissionInfo;
125import android.content.pm.ProviderInfo;
126import android.content.pm.ResolveInfo;
127import android.content.pm.ServiceInfo;
128import android.content.pm.Signature;
129import android.content.pm.UserInfo;
130import android.content.pm.VerificationParams;
131import android.content.pm.VerifierDeviceIdentity;
132import android.content.pm.VerifierInfo;
133import android.content.res.Resources;
134import android.hardware.display.DisplayManager;
135import android.net.Uri;
136import android.os.Binder;
137import android.os.Build;
138import android.os.Bundle;
139import android.os.Debug;
140import android.os.Environment;
141import android.os.Environment.UserEnvironment;
142import android.os.FileUtils;
143import android.os.Handler;
144import android.os.IBinder;
145import android.os.Looper;
146import android.os.Message;
147import android.os.Parcel;
148import android.os.ParcelFileDescriptor;
149import android.os.Process;
150import android.os.RemoteCallbackList;
151import android.os.RemoteException;
152import android.os.SELinux;
153import android.os.ServiceManager;
154import android.os.SystemClock;
155import android.os.SystemProperties;
156import android.os.UserHandle;
157import android.os.UserManager;
158import android.os.storage.IMountService;
159import android.os.storage.StorageEventListener;
160import android.os.storage.StorageManager;
161import android.os.storage.VolumeInfo;
162import android.os.storage.VolumeRecord;
163import android.security.KeyStore;
164import android.security.SystemKeyStore;
165import android.system.ErrnoException;
166import android.system.Os;
167import android.system.StructStat;
168import android.text.TextUtils;
169import android.text.format.DateUtils;
170import android.util.ArrayMap;
171import android.util.ArraySet;
172import android.util.AtomicFile;
173import android.util.DisplayMetrics;
174import android.util.EventLog;
175import android.util.ExceptionUtils;
176import android.util.Log;
177import android.util.LogPrinter;
178import android.util.MathUtils;
179import android.util.PrintStreamPrinter;
180import android.util.Slog;
181import android.util.SparseArray;
182import android.util.SparseBooleanArray;
183import android.util.SparseIntArray;
184import android.util.Xml;
185import android.view.Display;
186
187import dalvik.system.DexFile;
188import dalvik.system.VMRuntime;
189
190import libcore.io.IoUtils;
191import libcore.util.EmptyArray;
192
193import com.android.internal.R;
194import com.android.internal.app.IMediaContainerService;
195import com.android.internal.app.ResolverActivity;
196import com.android.internal.content.NativeLibraryHelper;
197import com.android.internal.content.PackageHelper;
198import com.android.internal.os.IParcelFileDescriptorFactory;
199import com.android.internal.os.SomeArgs;
200import com.android.internal.os.Zygote;
201import com.android.internal.util.ArrayUtils;
202import com.android.internal.util.FastPrintWriter;
203import com.android.internal.util.FastXmlSerializer;
204import com.android.internal.util.IndentingPrintWriter;
205import com.android.internal.util.Preconditions;
206import com.android.server.EventLogTags;
207import com.android.server.FgThread;
208import com.android.server.IntentResolver;
209import com.android.server.LocalServices;
210import com.android.server.ServiceThread;
211import com.android.server.SystemConfig;
212import com.android.server.Watchdog;
213import com.android.server.pm.PermissionsState.PermissionState;
214import com.android.server.pm.Settings.DatabaseVersion;
215import com.android.server.storage.DeviceStorageMonitorInternal;
216
217import org.xmlpull.v1.XmlPullParser;
218import org.xmlpull.v1.XmlPullParserException;
219import org.xmlpull.v1.XmlSerializer;
220
221import java.io.BufferedInputStream;
222import java.io.BufferedOutputStream;
223import java.io.BufferedReader;
224import java.io.ByteArrayInputStream;
225import java.io.ByteArrayOutputStream;
226import java.io.File;
227import java.io.FileDescriptor;
228import java.io.FileNotFoundException;
229import java.io.FileOutputStream;
230import java.io.FileReader;
231import java.io.FilenameFilter;
232import java.io.IOException;
233import java.io.InputStream;
234import java.io.PrintWriter;
235import java.nio.charset.StandardCharsets;
236import java.security.NoSuchAlgorithmException;
237import java.security.PublicKey;
238import java.security.cert.CertificateEncodingException;
239import java.security.cert.CertificateException;
240import java.text.SimpleDateFormat;
241import java.util.ArrayList;
242import java.util.Arrays;
243import java.util.Collection;
244import java.util.Collections;
245import java.util.Comparator;
246import java.util.Date;
247import java.util.Iterator;
248import java.util.List;
249import java.util.Map;
250import java.util.Objects;
251import java.util.Set;
252import java.util.concurrent.CountDownLatch;
253import java.util.concurrent.TimeUnit;
254import java.util.concurrent.atomic.AtomicBoolean;
255import java.util.concurrent.atomic.AtomicInteger;
256import java.util.concurrent.atomic.AtomicLong;
257
258/**
259 * Keep track of all those .apks everywhere.
260 *
261 * This is very central to the platform's security; please run the unit
262 * tests whenever making modifications here:
263 *
264mmm frameworks/base/tests/AndroidTests
265adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
266adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
267 *
268 * {@hide}
269 */
270public class PackageManagerService extends IPackageManager.Stub {
271    static final String TAG = "PackageManager";
272    static final boolean DEBUG_SETTINGS = false;
273    static final boolean DEBUG_PREFERRED = false;
274    static final boolean DEBUG_UPGRADE = false;
275    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
276    private static final boolean DEBUG_BACKUP = true;
277    private static final boolean DEBUG_INSTALL = false;
278    private static final boolean DEBUG_REMOVE = false;
279    private static final boolean DEBUG_BROADCASTS = false;
280    private static final boolean DEBUG_SHOW_INFO = false;
281    private static final boolean DEBUG_PACKAGE_INFO = false;
282    private static final boolean DEBUG_INTENT_MATCHING = false;
283    private static final boolean DEBUG_PACKAGE_SCANNING = false;
284    private static final boolean DEBUG_VERIFY = false;
285    private static final boolean DEBUG_DEXOPT = false;
286    private static final boolean DEBUG_ABI_SELECTION = false;
287
288    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = Build.IS_DEBUGGABLE;
289
290    private static final int RADIO_UID = Process.PHONE_UID;
291    private static final int LOG_UID = Process.LOG_UID;
292    private static final int NFC_UID = Process.NFC_UID;
293    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
294    private static final int SHELL_UID = Process.SHELL_UID;
295
296    // Cap the size of permission trees that 3rd party apps can define
297    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
298
299    // Suffix used during package installation when copying/moving
300    // package apks to install directory.
301    private static final String INSTALL_PACKAGE_SUFFIX = "-";
302
303    static final int SCAN_NO_DEX = 1<<1;
304    static final int SCAN_FORCE_DEX = 1<<2;
305    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
306    static final int SCAN_NEW_INSTALL = 1<<4;
307    static final int SCAN_NO_PATHS = 1<<5;
308    static final int SCAN_UPDATE_TIME = 1<<6;
309    static final int SCAN_DEFER_DEX = 1<<7;
310    static final int SCAN_BOOTING = 1<<8;
311    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
312    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
313    static final int SCAN_REQUIRE_KNOWN = 1<<12;
314    static final int SCAN_MOVE = 1<<13;
315    static final int SCAN_INITIAL = 1<<14;
316
317    static final int REMOVE_CHATTY = 1<<16;
318
319    private static final int[] EMPTY_INT_ARRAY = new int[0];
320
321    /**
322     * Timeout (in milliseconds) after which the watchdog should declare that
323     * our handler thread is wedged.  The usual default for such things is one
324     * minute but we sometimes do very lengthy I/O operations on this thread,
325     * such as installing multi-gigabyte applications, so ours needs to be longer.
326     */
327    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
328
329    /**
330     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
331     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
332     * settings entry if available, otherwise we use the hardcoded default.  If it's been
333     * more than this long since the last fstrim, we force one during the boot sequence.
334     *
335     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
336     * one gets run at the next available charging+idle time.  This final mandatory
337     * no-fstrim check kicks in only of the other scheduling criteria is never met.
338     */
339    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
340
341    /**
342     * Whether verification is enabled by default.
343     */
344    private static final boolean DEFAULT_VERIFY_ENABLE = true;
345
346    /**
347     * The default maximum time to wait for the verification agent to return in
348     * milliseconds.
349     */
350    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
351
352    /**
353     * The default response for package verification timeout.
354     *
355     * This can be either PackageManager.VERIFICATION_ALLOW or
356     * PackageManager.VERIFICATION_REJECT.
357     */
358    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
359
360    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
361
362    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
363            DEFAULT_CONTAINER_PACKAGE,
364            "com.android.defcontainer.DefaultContainerService");
365
366    private static final String KILL_APP_REASON_GIDS_CHANGED =
367            "permission grant or revoke changed gids";
368
369    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
370            "permissions revoked";
371
372    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
373
374    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
375
376    /** Permission grant: not grant the permission. */
377    private static final int GRANT_DENIED = 1;
378
379    /** Permission grant: grant the permission as an install permission. */
380    private static final int GRANT_INSTALL = 2;
381
382    /** Permission grant: grant the permission as an install permission for a legacy app. */
383    private static final int GRANT_INSTALL_LEGACY = 3;
384
385    /** Permission grant: grant the permission as a runtime one. */
386    private static final int GRANT_RUNTIME = 4;
387
388    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
389    private static final int GRANT_UPGRADE = 5;
390
391    final ServiceThread mHandlerThread;
392
393    final PackageHandler mHandler;
394
395    /**
396     * Messages for {@link #mHandler} that need to wait for system ready before
397     * being dispatched.
398     */
399    private ArrayList<Message> mPostSystemReadyMessages;
400
401    final int mSdkVersion = Build.VERSION.SDK_INT;
402
403    final Context mContext;
404    final boolean mFactoryTest;
405    final boolean mOnlyCore;
406    final boolean mLazyDexOpt;
407    final long mDexOptLRUThresholdInMills;
408    final DisplayMetrics mMetrics;
409    final int mDefParseFlags;
410    final String[] mSeparateProcesses;
411    final boolean mIsUpgrade;
412
413    // This is where all application persistent data goes.
414    final File mAppDataDir;
415
416    // This is where all application persistent data goes for secondary users.
417    final File mUserAppDataDir;
418
419    /** The location for ASEC container files on internal storage. */
420    final String mAsecInternalPath;
421
422    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
423    // LOCK HELD.  Can be called with mInstallLock held.
424    final Installer mInstaller;
425
426    /** Directory where installed third-party apps stored */
427    final File mAppInstallDir;
428
429    /**
430     * Directory to which applications installed internally have their
431     * 32 bit native libraries copied.
432     */
433    private File mAppLib32InstallDir;
434
435    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
436    // apps.
437    final File mDrmAppPrivateInstallDir;
438
439    // ----------------------------------------------------------------
440
441    // Lock for state used when installing and doing other long running
442    // operations.  Methods that must be called with this lock held have
443    // the suffix "LI".
444    final Object mInstallLock = new Object();
445
446    // ----------------------------------------------------------------
447
448    // Keys are String (package name), values are Package.  This also serves
449    // as the lock for the global state.  Methods that must be called with
450    // this lock held have the prefix "LP".
451    final ArrayMap<String, PackageParser.Package> mPackages =
452            new ArrayMap<String, PackageParser.Package>();
453
454    // Tracks available target package names -> overlay package paths.
455    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
456        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
457
458    final Settings mSettings;
459    boolean mRestoredSettings;
460
461    // System configuration read by SystemConfig.
462    final int[] mGlobalGids;
463    final SparseArray<ArraySet<String>> mSystemPermissions;
464    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
465
466    // If mac_permissions.xml was found for seinfo labeling.
467    boolean mFoundPolicyFile;
468
469    // If a recursive restorecon of /data/data/<pkg> is needed.
470    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
471
472    public static final class SharedLibraryEntry {
473        public final String path;
474        public final String apk;
475
476        SharedLibraryEntry(String _path, String _apk) {
477            path = _path;
478            apk = _apk;
479        }
480    }
481
482    // Currently known shared libraries.
483    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
484            new ArrayMap<String, SharedLibraryEntry>();
485
486    // All available activities, for your resolving pleasure.
487    final ActivityIntentResolver mActivities =
488            new ActivityIntentResolver();
489
490    // All available receivers, for your resolving pleasure.
491    final ActivityIntentResolver mReceivers =
492            new ActivityIntentResolver();
493
494    // All available services, for your resolving pleasure.
495    final ServiceIntentResolver mServices = new ServiceIntentResolver();
496
497    // All available providers, for your resolving pleasure.
498    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
499
500    // Mapping from provider base names (first directory in content URI codePath)
501    // to the provider information.
502    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
503            new ArrayMap<String, PackageParser.Provider>();
504
505    // Mapping from instrumentation class names to info about them.
506    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
507            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
508
509    // Mapping from permission names to info about them.
510    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
511            new ArrayMap<String, PackageParser.PermissionGroup>();
512
513    // Packages whose data we have transfered into another package, thus
514    // should no longer exist.
515    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
516
517    // Broadcast actions that are only available to the system.
518    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
519
520    /** List of packages waiting for verification. */
521    final SparseArray<PackageVerificationState> mPendingVerification
522            = new SparseArray<PackageVerificationState>();
523
524    /** Set of packages associated with each app op permission. */
525    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
526
527    final PackageInstallerService mInstallerService;
528
529    private final PackageDexOptimizer mPackageDexOptimizer;
530
531    private AtomicInteger mNextMoveId = new AtomicInteger();
532    private final MoveCallbacks mMoveCallbacks;
533
534    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
535
536    // Cache of users who need badging.
537    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
538
539    /** Token for keys in mPendingVerification. */
540    private int mPendingVerificationToken = 0;
541
542    volatile boolean mSystemReady;
543    volatile boolean mSafeMode;
544    volatile boolean mHasSystemUidErrors;
545
546    ApplicationInfo mAndroidApplication;
547    final ActivityInfo mResolveActivity = new ActivityInfo();
548    final ResolveInfo mResolveInfo = new ResolveInfo();
549    ComponentName mResolveComponentName;
550    PackageParser.Package mPlatformPackage;
551    ComponentName mCustomResolverComponentName;
552
553    boolean mResolverReplaced = false;
554
555    private final ComponentName mIntentFilterVerifierComponent;
556    private int mIntentFilterVerificationToken = 0;
557
558    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
559            = new SparseArray<IntentFilterVerificationState>();
560
561    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
562            new DefaultPermissionGrantPolicy(this);
563
564    private static class IFVerificationParams {
565        PackageParser.Package pkg;
566        boolean replacing;
567        int userId;
568        int verifierUid;
569
570        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
571                int _userId, int _verifierUid) {
572            pkg = _pkg;
573            replacing = _replacing;
574            userId = _userId;
575            replacing = _replacing;
576            verifierUid = _verifierUid;
577        }
578    }
579
580    private interface IntentFilterVerifier<T extends IntentFilter> {
581        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
582                                               T filter, String packageName);
583        void startVerifications(int userId);
584        void receiveVerificationResponse(int verificationId);
585    }
586
587    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
588        private Context mContext;
589        private ComponentName mIntentFilterVerifierComponent;
590        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
591
592        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
593            mContext = context;
594            mIntentFilterVerifierComponent = verifierComponent;
595        }
596
597        private String getDefaultScheme() {
598            return IntentFilter.SCHEME_HTTPS;
599        }
600
601        @Override
602        public void startVerifications(int userId) {
603            // Launch verifications requests
604            int count = mCurrentIntentFilterVerifications.size();
605            for (int n=0; n<count; n++) {
606                int verificationId = mCurrentIntentFilterVerifications.get(n);
607                final IntentFilterVerificationState ivs =
608                        mIntentFilterVerificationStates.get(verificationId);
609
610                String packageName = ivs.getPackageName();
611
612                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
613                final int filterCount = filters.size();
614                ArraySet<String> domainsSet = new ArraySet<>();
615                for (int m=0; m<filterCount; m++) {
616                    PackageParser.ActivityIntentInfo filter = filters.get(m);
617                    domainsSet.addAll(filter.getHostsList());
618                }
619                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
620                synchronized (mPackages) {
621                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
622                            packageName, domainsList) != null) {
623                        scheduleWriteSettingsLocked();
624                    }
625                }
626                sendVerificationRequest(userId, verificationId, ivs);
627            }
628            mCurrentIntentFilterVerifications.clear();
629        }
630
631        private void sendVerificationRequest(int userId, int verificationId,
632                IntentFilterVerificationState ivs) {
633
634            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
635            verificationIntent.putExtra(
636                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
637                    verificationId);
638            verificationIntent.putExtra(
639                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
640                    getDefaultScheme());
641            verificationIntent.putExtra(
642                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
643                    ivs.getHostsString());
644            verificationIntent.putExtra(
645                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
646                    ivs.getPackageName());
647            verificationIntent.setComponent(mIntentFilterVerifierComponent);
648            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
649
650            UserHandle user = new UserHandle(userId);
651            mContext.sendBroadcastAsUser(verificationIntent, user);
652            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
653                    "Sending IntentFilter verification broadcast");
654        }
655
656        public void receiveVerificationResponse(int verificationId) {
657            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
658
659            final boolean verified = ivs.isVerified();
660
661            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
662            final int count = filters.size();
663            if (DEBUG_DOMAIN_VERIFICATION) {
664                Slog.i(TAG, "Received verification response " + verificationId
665                        + " for " + count + " filters, verified=" + verified);
666            }
667            for (int n=0; n<count; n++) {
668                PackageParser.ActivityIntentInfo filter = filters.get(n);
669                filter.setVerified(verified);
670
671                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
672                        + " verified with result:" + verified + " and hosts:"
673                        + ivs.getHostsString());
674            }
675
676            mIntentFilterVerificationStates.remove(verificationId);
677
678            final String packageName = ivs.getPackageName();
679            IntentFilterVerificationInfo ivi = null;
680
681            synchronized (mPackages) {
682                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
683            }
684            if (ivi == null) {
685                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
686                        + verificationId + " packageName:" + packageName);
687                return;
688            }
689            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
690                    "Updating IntentFilterVerificationInfo for verificationId:" + verificationId);
691
692            synchronized (mPackages) {
693                if (verified) {
694                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
695                } else {
696                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
697                }
698                scheduleWriteSettingsLocked();
699
700                final int userId = ivs.getUserId();
701                if (userId != UserHandle.USER_ALL) {
702                    final int userStatus =
703                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
704
705                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
706                    boolean needUpdate = false;
707
708                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
709                    // already been set by the User thru the Disambiguation dialog
710                    switch (userStatus) {
711                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
712                            if (verified) {
713                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
714                            } else {
715                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
716                            }
717                            needUpdate = true;
718                            break;
719
720                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
721                            if (verified) {
722                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
723                                needUpdate = true;
724                            }
725                            break;
726
727                        default:
728                            // Nothing to do
729                    }
730
731                    if (needUpdate) {
732                        mSettings.updateIntentFilterVerificationStatusLPw(
733                                packageName, updatedStatus, userId);
734                        scheduleWritePackageRestrictionsLocked(userId);
735                    }
736                }
737            }
738        }
739
740        @Override
741        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
742                    ActivityIntentInfo filter, String packageName) {
743            if (!hasValidDomains(filter)) {
744                return false;
745            }
746            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
747            if (ivs == null) {
748                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
749                        packageName);
750            }
751            if (DEBUG_DOMAIN_VERIFICATION) {
752                Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter);
753            }
754            ivs.addFilter(filter);
755            return true;
756        }
757
758        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
759                int userId, int verificationId, String packageName) {
760            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
761                    verifierUid, userId, packageName);
762            ivs.setPendingState();
763            synchronized (mPackages) {
764                mIntentFilterVerificationStates.append(verificationId, ivs);
765                mCurrentIntentFilterVerifications.add(verificationId);
766            }
767            return ivs;
768        }
769    }
770
771    private static boolean hasValidDomains(ActivityIntentInfo filter) {
772        boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
773                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS);
774        if (!hasHTTPorHTTPS) {
775            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
776                    "IntentFilter does not contain any HTTP or HTTPS data scheme");
777            return false;
778        }
779        return true;
780    }
781
782    private IntentFilterVerifier mIntentFilterVerifier;
783
784    // Set of pending broadcasts for aggregating enable/disable of components.
785    static class PendingPackageBroadcasts {
786        // for each user id, a map of <package name -> components within that package>
787        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
788
789        public PendingPackageBroadcasts() {
790            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
791        }
792
793        public ArrayList<String> get(int userId, String packageName) {
794            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
795            return packages.get(packageName);
796        }
797
798        public void put(int userId, String packageName, ArrayList<String> components) {
799            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
800            packages.put(packageName, components);
801        }
802
803        public void remove(int userId, String packageName) {
804            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
805            if (packages != null) {
806                packages.remove(packageName);
807            }
808        }
809
810        public void remove(int userId) {
811            mUidMap.remove(userId);
812        }
813
814        public int userIdCount() {
815            return mUidMap.size();
816        }
817
818        public int userIdAt(int n) {
819            return mUidMap.keyAt(n);
820        }
821
822        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
823            return mUidMap.get(userId);
824        }
825
826        public int size() {
827            // total number of pending broadcast entries across all userIds
828            int num = 0;
829            for (int i = 0; i< mUidMap.size(); i++) {
830                num += mUidMap.valueAt(i).size();
831            }
832            return num;
833        }
834
835        public void clear() {
836            mUidMap.clear();
837        }
838
839        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
840            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
841            if (map == null) {
842                map = new ArrayMap<String, ArrayList<String>>();
843                mUidMap.put(userId, map);
844            }
845            return map;
846        }
847    }
848    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
849
850    // Service Connection to remote media container service to copy
851    // package uri's from external media onto secure containers
852    // or internal storage.
853    private IMediaContainerService mContainerService = null;
854
855    static final int SEND_PENDING_BROADCAST = 1;
856    static final int MCS_BOUND = 3;
857    static final int END_COPY = 4;
858    static final int INIT_COPY = 5;
859    static final int MCS_UNBIND = 6;
860    static final int START_CLEANING_PACKAGE = 7;
861    static final int FIND_INSTALL_LOC = 8;
862    static final int POST_INSTALL = 9;
863    static final int MCS_RECONNECT = 10;
864    static final int MCS_GIVE_UP = 11;
865    static final int UPDATED_MEDIA_STATUS = 12;
866    static final int WRITE_SETTINGS = 13;
867    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
868    static final int PACKAGE_VERIFIED = 15;
869    static final int CHECK_PENDING_VERIFICATION = 16;
870    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
871    static final int INTENT_FILTER_VERIFIED = 18;
872
873    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
874
875    // Delay time in millisecs
876    static final int BROADCAST_DELAY = 10 * 1000;
877
878    static UserManagerService sUserManager;
879
880    // Stores a list of users whose package restrictions file needs to be updated
881    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
882
883    final private DefaultContainerConnection mDefContainerConn =
884            new DefaultContainerConnection();
885    class DefaultContainerConnection implements ServiceConnection {
886        public void onServiceConnected(ComponentName name, IBinder service) {
887            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
888            IMediaContainerService imcs =
889                IMediaContainerService.Stub.asInterface(service);
890            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
891        }
892
893        public void onServiceDisconnected(ComponentName name) {
894            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
895        }
896    }
897
898    // Recordkeeping of restore-after-install operations that are currently in flight
899    // between the Package Manager and the Backup Manager
900    class PostInstallData {
901        public InstallArgs args;
902        public PackageInstalledInfo res;
903
904        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
905            args = _a;
906            res = _r;
907        }
908    }
909
910    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
911    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
912
913    // XML tags for backup/restore of various bits of state
914    private static final String TAG_PREFERRED_BACKUP = "pa";
915    private static final String TAG_DEFAULT_APPS = "da";
916    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
917
918    private final String mRequiredVerifierPackage;
919
920    private final PackageUsage mPackageUsage = new PackageUsage();
921
922    private class PackageUsage {
923        private static final int WRITE_INTERVAL
924            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
925
926        private final Object mFileLock = new Object();
927        private final AtomicLong mLastWritten = new AtomicLong(0);
928        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
929
930        private boolean mIsHistoricalPackageUsageAvailable = true;
931
932        boolean isHistoricalPackageUsageAvailable() {
933            return mIsHistoricalPackageUsageAvailable;
934        }
935
936        void write(boolean force) {
937            if (force) {
938                writeInternal();
939                return;
940            }
941            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
942                && !DEBUG_DEXOPT) {
943                return;
944            }
945            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
946                new Thread("PackageUsage_DiskWriter") {
947                    @Override
948                    public void run() {
949                        try {
950                            writeInternal();
951                        } finally {
952                            mBackgroundWriteRunning.set(false);
953                        }
954                    }
955                }.start();
956            }
957        }
958
959        private void writeInternal() {
960            synchronized (mPackages) {
961                synchronized (mFileLock) {
962                    AtomicFile file = getFile();
963                    FileOutputStream f = null;
964                    try {
965                        f = file.startWrite();
966                        BufferedOutputStream out = new BufferedOutputStream(f);
967                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
968                        StringBuilder sb = new StringBuilder();
969                        for (PackageParser.Package pkg : mPackages.values()) {
970                            if (pkg.mLastPackageUsageTimeInMills == 0) {
971                                continue;
972                            }
973                            sb.setLength(0);
974                            sb.append(pkg.packageName);
975                            sb.append(' ');
976                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
977                            sb.append('\n');
978                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
979                        }
980                        out.flush();
981                        file.finishWrite(f);
982                    } catch (IOException e) {
983                        if (f != null) {
984                            file.failWrite(f);
985                        }
986                        Log.e(TAG, "Failed to write package usage times", e);
987                    }
988                }
989            }
990            mLastWritten.set(SystemClock.elapsedRealtime());
991        }
992
993        void readLP() {
994            synchronized (mFileLock) {
995                AtomicFile file = getFile();
996                BufferedInputStream in = null;
997                try {
998                    in = new BufferedInputStream(file.openRead());
999                    StringBuffer sb = new StringBuffer();
1000                    while (true) {
1001                        String packageName = readToken(in, sb, ' ');
1002                        if (packageName == null) {
1003                            break;
1004                        }
1005                        String timeInMillisString = readToken(in, sb, '\n');
1006                        if (timeInMillisString == null) {
1007                            throw new IOException("Failed to find last usage time for package "
1008                                                  + packageName);
1009                        }
1010                        PackageParser.Package pkg = mPackages.get(packageName);
1011                        if (pkg == null) {
1012                            continue;
1013                        }
1014                        long timeInMillis;
1015                        try {
1016                            timeInMillis = Long.parseLong(timeInMillisString.toString());
1017                        } catch (NumberFormatException e) {
1018                            throw new IOException("Failed to parse " + timeInMillisString
1019                                                  + " as a long.", e);
1020                        }
1021                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1022                    }
1023                } catch (FileNotFoundException expected) {
1024                    mIsHistoricalPackageUsageAvailable = false;
1025                } catch (IOException e) {
1026                    Log.w(TAG, "Failed to read package usage times", e);
1027                } finally {
1028                    IoUtils.closeQuietly(in);
1029                }
1030            }
1031            mLastWritten.set(SystemClock.elapsedRealtime());
1032        }
1033
1034        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1035                throws IOException {
1036            sb.setLength(0);
1037            while (true) {
1038                int ch = in.read();
1039                if (ch == -1) {
1040                    if (sb.length() == 0) {
1041                        return null;
1042                    }
1043                    throw new IOException("Unexpected EOF");
1044                }
1045                if (ch == endOfToken) {
1046                    return sb.toString();
1047                }
1048                sb.append((char)ch);
1049            }
1050        }
1051
1052        private AtomicFile getFile() {
1053            File dataDir = Environment.getDataDirectory();
1054            File systemDir = new File(dataDir, "system");
1055            File fname = new File(systemDir, "package-usage.list");
1056            return new AtomicFile(fname);
1057        }
1058    }
1059
1060    class PackageHandler extends Handler {
1061        private boolean mBound = false;
1062        final ArrayList<HandlerParams> mPendingInstalls =
1063            new ArrayList<HandlerParams>();
1064
1065        private boolean connectToService() {
1066            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1067                    " DefaultContainerService");
1068            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1069            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1070            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1071                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
1072                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1073                mBound = true;
1074                return true;
1075            }
1076            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1077            return false;
1078        }
1079
1080        private void disconnectService() {
1081            mContainerService = null;
1082            mBound = false;
1083            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1084            mContext.unbindService(mDefContainerConn);
1085            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1086        }
1087
1088        PackageHandler(Looper looper) {
1089            super(looper);
1090        }
1091
1092        public void handleMessage(Message msg) {
1093            try {
1094                doHandleMessage(msg);
1095            } finally {
1096                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1097            }
1098        }
1099
1100        void doHandleMessage(Message msg) {
1101            switch (msg.what) {
1102                case INIT_COPY: {
1103                    HandlerParams params = (HandlerParams) msg.obj;
1104                    int idx = mPendingInstalls.size();
1105                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1106                    // If a bind was already initiated we dont really
1107                    // need to do anything. The pending install
1108                    // will be processed later on.
1109                    if (!mBound) {
1110                        // If this is the only one pending we might
1111                        // have to bind to the service again.
1112                        if (!connectToService()) {
1113                            Slog.e(TAG, "Failed to bind to media container service");
1114                            params.serviceError();
1115                            return;
1116                        } else {
1117                            // Once we bind to the service, the first
1118                            // pending request will be processed.
1119                            mPendingInstalls.add(idx, params);
1120                        }
1121                    } else {
1122                        mPendingInstalls.add(idx, params);
1123                        // Already bound to the service. Just make
1124                        // sure we trigger off processing the first request.
1125                        if (idx == 0) {
1126                            mHandler.sendEmptyMessage(MCS_BOUND);
1127                        }
1128                    }
1129                    break;
1130                }
1131                case MCS_BOUND: {
1132                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1133                    if (msg.obj != null) {
1134                        mContainerService = (IMediaContainerService) msg.obj;
1135                    }
1136                    if (mContainerService == null) {
1137                        if (!mBound) {
1138                            // Something seriously wrong since we are not bound and we are not
1139                            // waiting for connection. Bail out.
1140                            Slog.e(TAG, "Cannot bind to media container service");
1141                            for (HandlerParams params : mPendingInstalls) {
1142                                // Indicate service bind error
1143                                params.serviceError();
1144                            }
1145                            mPendingInstalls.clear();
1146                        } else {
1147                            Slog.w(TAG, "Waiting to connect to media container service");
1148                        }
1149                    } else if (mPendingInstalls.size() > 0) {
1150                        HandlerParams params = mPendingInstalls.get(0);
1151                        if (params != null) {
1152                            if (params.startCopy()) {
1153                                // We are done...  look for more work or to
1154                                // go idle.
1155                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1156                                        "Checking for more work or unbind...");
1157                                // Delete pending install
1158                                if (mPendingInstalls.size() > 0) {
1159                                    mPendingInstalls.remove(0);
1160                                }
1161                                if (mPendingInstalls.size() == 0) {
1162                                    if (mBound) {
1163                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1164                                                "Posting delayed MCS_UNBIND");
1165                                        removeMessages(MCS_UNBIND);
1166                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1167                                        // Unbind after a little delay, to avoid
1168                                        // continual thrashing.
1169                                        sendMessageDelayed(ubmsg, 10000);
1170                                    }
1171                                } else {
1172                                    // There are more pending requests in queue.
1173                                    // Just post MCS_BOUND message to trigger processing
1174                                    // of next pending install.
1175                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1176                                            "Posting MCS_BOUND for next work");
1177                                    mHandler.sendEmptyMessage(MCS_BOUND);
1178                                }
1179                            }
1180                        }
1181                    } else {
1182                        // Should never happen ideally.
1183                        Slog.w(TAG, "Empty queue");
1184                    }
1185                    break;
1186                }
1187                case MCS_RECONNECT: {
1188                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1189                    if (mPendingInstalls.size() > 0) {
1190                        if (mBound) {
1191                            disconnectService();
1192                        }
1193                        if (!connectToService()) {
1194                            Slog.e(TAG, "Failed to bind to media container service");
1195                            for (HandlerParams params : mPendingInstalls) {
1196                                // Indicate service bind error
1197                                params.serviceError();
1198                            }
1199                            mPendingInstalls.clear();
1200                        }
1201                    }
1202                    break;
1203                }
1204                case MCS_UNBIND: {
1205                    // If there is no actual work left, then time to unbind.
1206                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1207
1208                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1209                        if (mBound) {
1210                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1211
1212                            disconnectService();
1213                        }
1214                    } else if (mPendingInstalls.size() > 0) {
1215                        // There are more pending requests in queue.
1216                        // Just post MCS_BOUND message to trigger processing
1217                        // of next pending install.
1218                        mHandler.sendEmptyMessage(MCS_BOUND);
1219                    }
1220
1221                    break;
1222                }
1223                case MCS_GIVE_UP: {
1224                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1225                    mPendingInstalls.remove(0);
1226                    break;
1227                }
1228                case SEND_PENDING_BROADCAST: {
1229                    String packages[];
1230                    ArrayList<String> components[];
1231                    int size = 0;
1232                    int uids[];
1233                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1234                    synchronized (mPackages) {
1235                        if (mPendingBroadcasts == null) {
1236                            return;
1237                        }
1238                        size = mPendingBroadcasts.size();
1239                        if (size <= 0) {
1240                            // Nothing to be done. Just return
1241                            return;
1242                        }
1243                        packages = new String[size];
1244                        components = new ArrayList[size];
1245                        uids = new int[size];
1246                        int i = 0;  // filling out the above arrays
1247
1248                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1249                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1250                            Iterator<Map.Entry<String, ArrayList<String>>> it
1251                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1252                                            .entrySet().iterator();
1253                            while (it.hasNext() && i < size) {
1254                                Map.Entry<String, ArrayList<String>> ent = it.next();
1255                                packages[i] = ent.getKey();
1256                                components[i] = ent.getValue();
1257                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1258                                uids[i] = (ps != null)
1259                                        ? UserHandle.getUid(packageUserId, ps.appId)
1260                                        : -1;
1261                                i++;
1262                            }
1263                        }
1264                        size = i;
1265                        mPendingBroadcasts.clear();
1266                    }
1267                    // Send broadcasts
1268                    for (int i = 0; i < size; i++) {
1269                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1270                    }
1271                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1272                    break;
1273                }
1274                case START_CLEANING_PACKAGE: {
1275                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1276                    final String packageName = (String)msg.obj;
1277                    final int userId = msg.arg1;
1278                    final boolean andCode = msg.arg2 != 0;
1279                    synchronized (mPackages) {
1280                        if (userId == UserHandle.USER_ALL) {
1281                            int[] users = sUserManager.getUserIds();
1282                            for (int user : users) {
1283                                mSettings.addPackageToCleanLPw(
1284                                        new PackageCleanItem(user, packageName, andCode));
1285                            }
1286                        } else {
1287                            mSettings.addPackageToCleanLPw(
1288                                    new PackageCleanItem(userId, packageName, andCode));
1289                        }
1290                    }
1291                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1292                    startCleaningPackages();
1293                } break;
1294                case POST_INSTALL: {
1295                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1296                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1297                    mRunningInstalls.delete(msg.arg1);
1298                    boolean deleteOld = false;
1299
1300                    if (data != null) {
1301                        InstallArgs args = data.args;
1302                        PackageInstalledInfo res = data.res;
1303
1304                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1305                            res.removedInfo.sendBroadcast(false, true, false);
1306                            Bundle extras = new Bundle(1);
1307                            extras.putInt(Intent.EXTRA_UID, res.uid);
1308
1309                            // Now that we successfully installed the package, grant runtime
1310                            // permissions if requested before broadcasting the install.
1311                            if ((args.installFlags
1312                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) {
1313                                grantRequestedRuntimePermissions(res.pkg,
1314                                        args.user.getIdentifier());
1315                            }
1316
1317                            // Determine the set of users who are adding this
1318                            // package for the first time vs. those who are seeing
1319                            // an update.
1320                            int[] firstUsers;
1321                            int[] updateUsers = new int[0];
1322                            if (res.origUsers == null || res.origUsers.length == 0) {
1323                                firstUsers = res.newUsers;
1324                            } else {
1325                                firstUsers = new int[0];
1326                                for (int i=0; i<res.newUsers.length; i++) {
1327                                    int user = res.newUsers[i];
1328                                    boolean isNew = true;
1329                                    for (int j=0; j<res.origUsers.length; j++) {
1330                                        if (res.origUsers[j] == user) {
1331                                            isNew = false;
1332                                            break;
1333                                        }
1334                                    }
1335                                    if (isNew) {
1336                                        int[] newFirst = new int[firstUsers.length+1];
1337                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1338                                                firstUsers.length);
1339                                        newFirst[firstUsers.length] = user;
1340                                        firstUsers = newFirst;
1341                                    } else {
1342                                        int[] newUpdate = new int[updateUsers.length+1];
1343                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1344                                                updateUsers.length);
1345                                        newUpdate[updateUsers.length] = user;
1346                                        updateUsers = newUpdate;
1347                                    }
1348                                }
1349                            }
1350                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1351                                    res.pkg.applicationInfo.packageName,
1352                                    extras, null, null, firstUsers);
1353                            final boolean update = res.removedInfo.removedPackage != null;
1354                            if (update) {
1355                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1356                            }
1357                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1358                                    res.pkg.applicationInfo.packageName,
1359                                    extras, null, null, updateUsers);
1360                            if (update) {
1361                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1362                                        res.pkg.applicationInfo.packageName,
1363                                        extras, null, null, updateUsers);
1364                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1365                                        null, null,
1366                                        res.pkg.applicationInfo.packageName, null, updateUsers);
1367
1368                                // treat asec-hosted packages like removable media on upgrade
1369                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1370                                    if (DEBUG_INSTALL) {
1371                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1372                                                + " is ASEC-hosted -> AVAILABLE");
1373                                    }
1374                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1375                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1376                                    pkgList.add(res.pkg.applicationInfo.packageName);
1377                                    sendResourcesChangedBroadcast(true, true,
1378                                            pkgList,uidArray, null);
1379                                }
1380                            }
1381                            if (res.removedInfo.args != null) {
1382                                // Remove the replaced package's older resources safely now
1383                                deleteOld = true;
1384                            }
1385
1386                            // Log current value of "unknown sources" setting
1387                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1388                                getUnknownSourcesSettings());
1389                        }
1390                        // Force a gc to clear up things
1391                        Runtime.getRuntime().gc();
1392                        // We delete after a gc for applications  on sdcard.
1393                        if (deleteOld) {
1394                            synchronized (mInstallLock) {
1395                                res.removedInfo.args.doPostDeleteLI(true);
1396                            }
1397                        }
1398                        if (args.observer != null) {
1399                            try {
1400                                Bundle extras = extrasForInstallResult(res);
1401                                args.observer.onPackageInstalled(res.name, res.returnCode,
1402                                        res.returnMsg, extras);
1403                            } catch (RemoteException e) {
1404                                Slog.i(TAG, "Observer no longer exists.");
1405                            }
1406                        }
1407                    } else {
1408                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1409                    }
1410                } break;
1411                case UPDATED_MEDIA_STATUS: {
1412                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1413                    boolean reportStatus = msg.arg1 == 1;
1414                    boolean doGc = msg.arg2 == 1;
1415                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1416                    if (doGc) {
1417                        // Force a gc to clear up stale containers.
1418                        Runtime.getRuntime().gc();
1419                    }
1420                    if (msg.obj != null) {
1421                        @SuppressWarnings("unchecked")
1422                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1423                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1424                        // Unload containers
1425                        unloadAllContainers(args);
1426                    }
1427                    if (reportStatus) {
1428                        try {
1429                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1430                            PackageHelper.getMountService().finishMediaUpdate();
1431                        } catch (RemoteException e) {
1432                            Log.e(TAG, "MountService not running?");
1433                        }
1434                    }
1435                } break;
1436                case WRITE_SETTINGS: {
1437                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1438                    synchronized (mPackages) {
1439                        removeMessages(WRITE_SETTINGS);
1440                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1441                        mSettings.writeLPr();
1442                        mDirtyUsers.clear();
1443                    }
1444                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1445                } break;
1446                case WRITE_PACKAGE_RESTRICTIONS: {
1447                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1448                    synchronized (mPackages) {
1449                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1450                        for (int userId : mDirtyUsers) {
1451                            mSettings.writePackageRestrictionsLPr(userId);
1452                        }
1453                        mDirtyUsers.clear();
1454                    }
1455                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1456                } break;
1457                case CHECK_PENDING_VERIFICATION: {
1458                    final int verificationId = msg.arg1;
1459                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1460
1461                    if ((state != null) && !state.timeoutExtended()) {
1462                        final InstallArgs args = state.getInstallArgs();
1463                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1464
1465                        Slog.i(TAG, "Verification timed out for " + originUri);
1466                        mPendingVerification.remove(verificationId);
1467
1468                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1469
1470                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1471                            Slog.i(TAG, "Continuing with installation of " + originUri);
1472                            state.setVerifierResponse(Binder.getCallingUid(),
1473                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1474                            broadcastPackageVerified(verificationId, originUri,
1475                                    PackageManager.VERIFICATION_ALLOW,
1476                                    state.getInstallArgs().getUser());
1477                            try {
1478                                ret = args.copyApk(mContainerService, true);
1479                            } catch (RemoteException e) {
1480                                Slog.e(TAG, "Could not contact the ContainerService");
1481                            }
1482                        } else {
1483                            broadcastPackageVerified(verificationId, originUri,
1484                                    PackageManager.VERIFICATION_REJECT,
1485                                    state.getInstallArgs().getUser());
1486                        }
1487
1488                        processPendingInstall(args, ret);
1489                        mHandler.sendEmptyMessage(MCS_UNBIND);
1490                    }
1491                    break;
1492                }
1493                case PACKAGE_VERIFIED: {
1494                    final int verificationId = msg.arg1;
1495
1496                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1497                    if (state == null) {
1498                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1499                        break;
1500                    }
1501
1502                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1503
1504                    state.setVerifierResponse(response.callerUid, response.code);
1505
1506                    if (state.isVerificationComplete()) {
1507                        mPendingVerification.remove(verificationId);
1508
1509                        final InstallArgs args = state.getInstallArgs();
1510                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1511
1512                        int ret;
1513                        if (state.isInstallAllowed()) {
1514                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1515                            broadcastPackageVerified(verificationId, originUri,
1516                                    response.code, state.getInstallArgs().getUser());
1517                            try {
1518                                ret = args.copyApk(mContainerService, true);
1519                            } catch (RemoteException e) {
1520                                Slog.e(TAG, "Could not contact the ContainerService");
1521                            }
1522                        } else {
1523                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1524                        }
1525
1526                        processPendingInstall(args, ret);
1527
1528                        mHandler.sendEmptyMessage(MCS_UNBIND);
1529                    }
1530
1531                    break;
1532                }
1533                case START_INTENT_FILTER_VERIFICATIONS: {
1534                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1535                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1536                            params.replacing, params.pkg);
1537                    break;
1538                }
1539                case INTENT_FILTER_VERIFIED: {
1540                    final int verificationId = msg.arg1;
1541
1542                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1543                            verificationId);
1544                    if (state == null) {
1545                        Slog.w(TAG, "Invalid IntentFilter verification token "
1546                                + verificationId + " received");
1547                        break;
1548                    }
1549
1550                    final int userId = state.getUserId();
1551
1552                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1553                            "Processing IntentFilter verification with token:"
1554                            + verificationId + " and userId:" + userId);
1555
1556                    final IntentFilterVerificationResponse response =
1557                            (IntentFilterVerificationResponse) msg.obj;
1558
1559                    state.setVerifierResponse(response.callerUid, response.code);
1560
1561                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1562                            "IntentFilter verification with token:" + verificationId
1563                            + " and userId:" + userId
1564                            + " is settings verifier response with response code:"
1565                            + response.code);
1566
1567                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1568                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1569                                + response.getFailedDomainsString());
1570                    }
1571
1572                    if (state.isVerificationComplete()) {
1573                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1574                    } else {
1575                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1576                                "IntentFilter verification with token:" + verificationId
1577                                + " was not said to be complete");
1578                    }
1579
1580                    break;
1581                }
1582            }
1583        }
1584    }
1585
1586    private StorageEventListener mStorageListener = new StorageEventListener() {
1587        @Override
1588        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1589            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1590                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1591                    // TODO: ensure that private directories exist for all active users
1592                    // TODO: remove user data whose serial number doesn't match
1593                    loadPrivatePackages(vol);
1594                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1595                    unloadPrivatePackages(vol);
1596                }
1597            }
1598
1599            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1600                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1601                    updateExternalMediaStatus(true, false);
1602                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1603                    updateExternalMediaStatus(false, false);
1604                }
1605            }
1606        }
1607
1608        @Override
1609        public void onVolumeForgotten(String fsUuid) {
1610            // TODO: remove all packages hosted on this uuid
1611        }
1612    };
1613
1614    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) {
1615        if (userId >= UserHandle.USER_OWNER) {
1616            grantRequestedRuntimePermissionsForUser(pkg, userId);
1617        } else if (userId == UserHandle.USER_ALL) {
1618            for (int someUserId : UserManagerService.getInstance().getUserIds()) {
1619                grantRequestedRuntimePermissionsForUser(pkg, someUserId);
1620            }
1621        }
1622
1623        // We could have touched GID membership, so flush out packages.list
1624        synchronized (mPackages) {
1625            mSettings.writePackageListLPr();
1626        }
1627    }
1628
1629    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) {
1630        SettingBase sb = (SettingBase) pkg.mExtras;
1631        if (sb == null) {
1632            return;
1633        }
1634
1635        PermissionsState permissionsState = sb.getPermissionsState();
1636
1637        for (String permission : pkg.requestedPermissions) {
1638            BasePermission bp = mSettings.mPermissions.get(permission);
1639            if (bp != null && bp.isRuntime()) {
1640                permissionsState.grantRuntimePermission(bp, userId);
1641            }
1642        }
1643    }
1644
1645    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1646        Bundle extras = null;
1647        switch (res.returnCode) {
1648            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1649                extras = new Bundle();
1650                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1651                        res.origPermission);
1652                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1653                        res.origPackage);
1654                break;
1655            }
1656            case PackageManager.INSTALL_SUCCEEDED: {
1657                extras = new Bundle();
1658                extras.putBoolean(Intent.EXTRA_REPLACING,
1659                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1660                break;
1661            }
1662        }
1663        return extras;
1664    }
1665
1666    void scheduleWriteSettingsLocked() {
1667        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1668            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1669        }
1670    }
1671
1672    void scheduleWritePackageRestrictionsLocked(int userId) {
1673        if (!sUserManager.exists(userId)) return;
1674        mDirtyUsers.add(userId);
1675        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1676            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1677        }
1678    }
1679
1680    public static PackageManagerService main(Context context, Installer installer,
1681            boolean factoryTest, boolean onlyCore) {
1682        PackageManagerService m = new PackageManagerService(context, installer,
1683                factoryTest, onlyCore);
1684        ServiceManager.addService("package", m);
1685        return m;
1686    }
1687
1688    static String[] splitString(String str, char sep) {
1689        int count = 1;
1690        int i = 0;
1691        while ((i=str.indexOf(sep, i)) >= 0) {
1692            count++;
1693            i++;
1694        }
1695
1696        String[] res = new String[count];
1697        i=0;
1698        count = 0;
1699        int lastI=0;
1700        while ((i=str.indexOf(sep, i)) >= 0) {
1701            res[count] = str.substring(lastI, i);
1702            count++;
1703            i++;
1704            lastI = i;
1705        }
1706        res[count] = str.substring(lastI, str.length());
1707        return res;
1708    }
1709
1710    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1711        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1712                Context.DISPLAY_SERVICE);
1713        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1714    }
1715
1716    public PackageManagerService(Context context, Installer installer,
1717            boolean factoryTest, boolean onlyCore) {
1718        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1719                SystemClock.uptimeMillis());
1720
1721        if (mSdkVersion <= 0) {
1722            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1723        }
1724
1725        mContext = context;
1726        mFactoryTest = factoryTest;
1727        mOnlyCore = onlyCore;
1728        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1729        mMetrics = new DisplayMetrics();
1730        mSettings = new Settings(mPackages);
1731        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1732                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1733        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1734                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1735        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1736                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1737        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1738                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1739        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1740                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1741        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1742                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1743
1744        // TODO: add a property to control this?
1745        long dexOptLRUThresholdInMinutes;
1746        if (mLazyDexOpt) {
1747            dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1748        } else {
1749            dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1750        }
1751        mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1752
1753        String separateProcesses = SystemProperties.get("debug.separate_processes");
1754        if (separateProcesses != null && separateProcesses.length() > 0) {
1755            if ("*".equals(separateProcesses)) {
1756                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1757                mSeparateProcesses = null;
1758                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1759            } else {
1760                mDefParseFlags = 0;
1761                mSeparateProcesses = separateProcesses.split(",");
1762                Slog.w(TAG, "Running with debug.separate_processes: "
1763                        + separateProcesses);
1764            }
1765        } else {
1766            mDefParseFlags = 0;
1767            mSeparateProcesses = null;
1768        }
1769
1770        mInstaller = installer;
1771        mPackageDexOptimizer = new PackageDexOptimizer(this);
1772        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1773
1774        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1775                FgThread.get().getLooper());
1776
1777        getDefaultDisplayMetrics(context, mMetrics);
1778
1779        SystemConfig systemConfig = SystemConfig.getInstance();
1780        mGlobalGids = systemConfig.getGlobalGids();
1781        mSystemPermissions = systemConfig.getSystemPermissions();
1782        mAvailableFeatures = systemConfig.getAvailableFeatures();
1783
1784        synchronized (mInstallLock) {
1785        // writer
1786        synchronized (mPackages) {
1787            mHandlerThread = new ServiceThread(TAG,
1788                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1789            mHandlerThread.start();
1790            mHandler = new PackageHandler(mHandlerThread.getLooper());
1791            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1792
1793            File dataDir = Environment.getDataDirectory();
1794            mAppDataDir = new File(dataDir, "data");
1795            mAppInstallDir = new File(dataDir, "app");
1796            mAppLib32InstallDir = new File(dataDir, "app-lib");
1797            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1798            mUserAppDataDir = new File(dataDir, "user");
1799            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1800
1801            sUserManager = new UserManagerService(context, this,
1802                    mInstallLock, mPackages);
1803
1804            // Propagate permission configuration in to package manager.
1805            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1806                    = systemConfig.getPermissions();
1807            for (int i=0; i<permConfig.size(); i++) {
1808                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1809                BasePermission bp = mSettings.mPermissions.get(perm.name);
1810                if (bp == null) {
1811                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1812                    mSettings.mPermissions.put(perm.name, bp);
1813                }
1814                if (perm.gids != null) {
1815                    bp.setGids(perm.gids, perm.perUser);
1816                }
1817            }
1818
1819            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1820            for (int i=0; i<libConfig.size(); i++) {
1821                mSharedLibraries.put(libConfig.keyAt(i),
1822                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1823            }
1824
1825            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1826
1827            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1828                    mSdkVersion, mOnlyCore);
1829
1830            String customResolverActivity = Resources.getSystem().getString(
1831                    R.string.config_customResolverActivity);
1832            if (TextUtils.isEmpty(customResolverActivity)) {
1833                customResolverActivity = null;
1834            } else {
1835                mCustomResolverComponentName = ComponentName.unflattenFromString(
1836                        customResolverActivity);
1837            }
1838
1839            long startTime = SystemClock.uptimeMillis();
1840
1841            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1842                    startTime);
1843
1844            // Set flag to monitor and not change apk file paths when
1845            // scanning install directories.
1846            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
1847
1848            final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1849
1850            /**
1851             * Add everything in the in the boot class path to the
1852             * list of process files because dexopt will have been run
1853             * if necessary during zygote startup.
1854             */
1855            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1856            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1857
1858            if (bootClassPath != null) {
1859                String[] bootClassPathElements = splitString(bootClassPath, ':');
1860                for (String element : bootClassPathElements) {
1861                    alreadyDexOpted.add(element);
1862                }
1863            } else {
1864                Slog.w(TAG, "No BOOTCLASSPATH found!");
1865            }
1866
1867            if (systemServerClassPath != null) {
1868                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1869                for (String element : systemServerClassPathElements) {
1870                    alreadyDexOpted.add(element);
1871                }
1872            } else {
1873                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1874            }
1875
1876            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
1877            final String[] dexCodeInstructionSets =
1878                    getDexCodeInstructionSets(
1879                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
1880
1881            /**
1882             * Ensure all external libraries have had dexopt run on them.
1883             */
1884            if (mSharedLibraries.size() > 0) {
1885                // NOTE: For now, we're compiling these system "shared libraries"
1886                // (and framework jars) into all available architectures. It's possible
1887                // to compile them only when we come across an app that uses them (there's
1888                // already logic for that in scanPackageLI) but that adds some complexity.
1889                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1890                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1891                        final String lib = libEntry.path;
1892                        if (lib == null) {
1893                            continue;
1894                        }
1895
1896                        try {
1897                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
1898                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1899                                alreadyDexOpted.add(lib);
1900                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1901                            }
1902                        } catch (FileNotFoundException e) {
1903                            Slog.w(TAG, "Library not found: " + lib);
1904                        } catch (IOException e) {
1905                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1906                                    + e.getMessage());
1907                        }
1908                    }
1909                }
1910            }
1911
1912            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1913
1914            // Gross hack for now: we know this file doesn't contain any
1915            // code, so don't dexopt it to avoid the resulting log spew.
1916            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1917
1918            // Gross hack for now: we know this file is only part of
1919            // the boot class path for art, so don't dexopt it to
1920            // avoid the resulting log spew.
1921            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1922
1923            /**
1924             * There are a number of commands implemented in Java, which
1925             * we currently need to do the dexopt on so that they can be
1926             * run from a non-root shell.
1927             */
1928            String[] frameworkFiles = frameworkDir.list();
1929            if (frameworkFiles != null) {
1930                // TODO: We could compile these only for the most preferred ABI. We should
1931                // first double check that the dex files for these commands are not referenced
1932                // by other system apps.
1933                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1934                    for (int i=0; i<frameworkFiles.length; i++) {
1935                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1936                        String path = libPath.getPath();
1937                        // Skip the file if we already did it.
1938                        if (alreadyDexOpted.contains(path)) {
1939                            continue;
1940                        }
1941                        // Skip the file if it is not a type we want to dexopt.
1942                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1943                            continue;
1944                        }
1945                        try {
1946                            int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false);
1947                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1948                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1949                            }
1950                        } catch (FileNotFoundException e) {
1951                            Slog.w(TAG, "Jar not found: " + path);
1952                        } catch (IOException e) {
1953                            Slog.w(TAG, "Exception reading jar: " + path, e);
1954                        }
1955                    }
1956                }
1957            }
1958
1959            // Collect vendor overlay packages.
1960            // (Do this before scanning any apps.)
1961            // For security and version matching reason, only consider
1962            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1963            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1964            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1965                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
1966
1967            // Find base frameworks (resource packages without code).
1968            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1969                    | PackageParser.PARSE_IS_SYSTEM_DIR
1970                    | PackageParser.PARSE_IS_PRIVILEGED,
1971                    scanFlags | SCAN_NO_DEX, 0);
1972
1973            // Collected privileged system packages.
1974            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1975            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1976                    | PackageParser.PARSE_IS_SYSTEM_DIR
1977                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
1978
1979            // Collect ordinary system packages.
1980            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
1981            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1982                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1983
1984            // Collect all vendor packages.
1985            File vendorAppDir = new File("/vendor/app");
1986            try {
1987                vendorAppDir = vendorAppDir.getCanonicalFile();
1988            } catch (IOException e) {
1989                // failed to look up canonical path, continue with original one
1990            }
1991            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1992                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1993
1994            // Collect all OEM packages.
1995            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
1996            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
1997                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1998
1999            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
2000            mInstaller.moveFiles();
2001
2002            // Prune any system packages that no longer exist.
2003            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2004            final ArrayMap<String, File> expectingBetter = new ArrayMap<>();
2005            if (!mOnlyCore) {
2006                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2007                while (psit.hasNext()) {
2008                    PackageSetting ps = psit.next();
2009
2010                    /*
2011                     * If this is not a system app, it can't be a
2012                     * disable system app.
2013                     */
2014                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2015                        continue;
2016                    }
2017
2018                    /*
2019                     * If the package is scanned, it's not erased.
2020                     */
2021                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2022                    if (scannedPkg != null) {
2023                        /*
2024                         * If the system app is both scanned and in the
2025                         * disabled packages list, then it must have been
2026                         * added via OTA. Remove it from the currently
2027                         * scanned package so the previously user-installed
2028                         * application can be scanned.
2029                         */
2030                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2031                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2032                                    + ps.name + "; removing system app.  Last known codePath="
2033                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2034                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2035                                    + scannedPkg.mVersionCode);
2036                            removePackageLI(ps, true);
2037                            expectingBetter.put(ps.name, ps.codePath);
2038                        }
2039
2040                        continue;
2041                    }
2042
2043                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2044                        psit.remove();
2045                        logCriticalInfo(Log.WARN, "System package " + ps.name
2046                                + " no longer exists; wiping its data");
2047                        removeDataDirsLI(null, ps.name);
2048                    } else {
2049                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2050                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2051                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2052                        }
2053                    }
2054                }
2055            }
2056
2057            //look for any incomplete package installations
2058            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2059            //clean up list
2060            for(int i = 0; i < deletePkgsList.size(); i++) {
2061                //clean up here
2062                cleanupInstallFailedPackage(deletePkgsList.get(i));
2063            }
2064            //delete tmp files
2065            deleteTempPackageFiles();
2066
2067            // Remove any shared userIDs that have no associated packages
2068            mSettings.pruneSharedUsersLPw();
2069
2070            if (!mOnlyCore) {
2071                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2072                        SystemClock.uptimeMillis());
2073                scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2074
2075                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2076                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2077
2078                /**
2079                 * Remove disable package settings for any updated system
2080                 * apps that were removed via an OTA. If they're not a
2081                 * previously-updated app, remove them completely.
2082                 * Otherwise, just revoke their system-level permissions.
2083                 */
2084                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2085                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2086                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2087
2088                    String msg;
2089                    if (deletedPkg == null) {
2090                        msg = "Updated system package " + deletedAppName
2091                                + " no longer exists; wiping its data";
2092                        removeDataDirsLI(null, deletedAppName);
2093                    } else {
2094                        msg = "Updated system app + " + deletedAppName
2095                                + " no longer present; removing system privileges for "
2096                                + deletedAppName;
2097
2098                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2099
2100                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2101                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2102                    }
2103                    logCriticalInfo(Log.WARN, msg);
2104                }
2105
2106                /**
2107                 * Make sure all system apps that we expected to appear on
2108                 * the userdata partition actually showed up. If they never
2109                 * appeared, crawl back and revive the system version.
2110                 */
2111                for (int i = 0; i < expectingBetter.size(); i++) {
2112                    final String packageName = expectingBetter.keyAt(i);
2113                    if (!mPackages.containsKey(packageName)) {
2114                        final File scanFile = expectingBetter.valueAt(i);
2115
2116                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2117                                + " but never showed up; reverting to system");
2118
2119                        final int reparseFlags;
2120                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2121                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2122                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2123                                    | PackageParser.PARSE_IS_PRIVILEGED;
2124                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2125                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2126                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2127                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2128                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2129                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2130                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2131                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2132                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2133                        } else {
2134                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2135                            continue;
2136                        }
2137
2138                        mSettings.enableSystemPackageLPw(packageName);
2139
2140                        try {
2141                            scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
2142                        } catch (PackageManagerException e) {
2143                            Slog.e(TAG, "Failed to parse original system package: "
2144                                    + e.getMessage());
2145                        }
2146                    }
2147                }
2148            }
2149
2150            // Now that we know all of the shared libraries, update all clients to have
2151            // the correct library paths.
2152            updateAllSharedLibrariesLPw();
2153
2154            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2155                // NOTE: We ignore potential failures here during a system scan (like
2156                // the rest of the commands above) because there's precious little we
2157                // can do about it. A settings error is reported, though.
2158                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2159                        false /* force dexopt */, false /* defer dexopt */);
2160            }
2161
2162            // Now that we know all the packages we are keeping,
2163            // read and update their last usage times.
2164            mPackageUsage.readLP();
2165
2166            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2167                    SystemClock.uptimeMillis());
2168            Slog.i(TAG, "Time to scan packages: "
2169                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2170                    + " seconds");
2171
2172            // If the platform SDK has changed since the last time we booted,
2173            // we need to re-grant app permission to catch any new ones that
2174            // appear.  This is really a hack, and means that apps can in some
2175            // cases get permissions that the user didn't initially explicitly
2176            // allow...  it would be nice to have some better way to handle
2177            // this situation.
2178            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
2179                    != mSdkVersion;
2180            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
2181                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
2182                    + "; regranting permissions for internal storage");
2183            mSettings.mInternalSdkPlatform = mSdkVersion;
2184
2185            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
2186                    | (regrantPermissions
2187                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
2188                            : 0));
2189
2190            // If this is the first boot, and it is a normal boot, then
2191            // we need to initialize the default preferred apps.
2192            if (!mRestoredSettings && !onlyCore) {
2193                mSettings.applyDefaultPreferredAppsLPw(this, UserHandle.USER_OWNER);
2194                applyFactoryDefaultBrowserLPw(UserHandle.USER_OWNER);
2195            }
2196
2197            // If this is first boot after an OTA, and a normal boot, then
2198            // we need to clear code cache directories.
2199            mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint);
2200            if (mIsUpgrade && !onlyCore) {
2201                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2202                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2203                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2204                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2205                }
2206                mSettings.mFingerprint = Build.FINGERPRINT;
2207            }
2208
2209            primeDomainVerificationsLPw();
2210            checkDefaultBrowser();
2211
2212            // All the changes are done during package scanning.
2213            mSettings.updateInternalDatabaseVersion();
2214
2215            // can downgrade to reader
2216            mSettings.writeLPr();
2217
2218            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2219                    SystemClock.uptimeMillis());
2220
2221            mRequiredVerifierPackage = getRequiredVerifierLPr();
2222
2223            mInstallerService = new PackageInstallerService(context, this);
2224
2225            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2226            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2227                    mIntentFilterVerifierComponent);
2228
2229        } // synchronized (mPackages)
2230        } // synchronized (mInstallLock)
2231
2232        // Now after opening every single application zip, make sure they
2233        // are all flushed.  Not really needed, but keeps things nice and
2234        // tidy.
2235        Runtime.getRuntime().gc();
2236
2237        // Expose private service for system components to use.
2238        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2239    }
2240
2241    @Override
2242    public boolean isFirstBoot() {
2243        return !mRestoredSettings;
2244    }
2245
2246    @Override
2247    public boolean isOnlyCoreApps() {
2248        return mOnlyCore;
2249    }
2250
2251    @Override
2252    public boolean isUpgrade() {
2253        return mIsUpgrade;
2254    }
2255
2256    private String getRequiredVerifierLPr() {
2257        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2258        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2259                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
2260
2261        String requiredVerifier = null;
2262
2263        final int N = receivers.size();
2264        for (int i = 0; i < N; i++) {
2265            final ResolveInfo info = receivers.get(i);
2266
2267            if (info.activityInfo == null) {
2268                continue;
2269            }
2270
2271            final String packageName = info.activityInfo.packageName;
2272
2273            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2274                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2275                continue;
2276            }
2277
2278            if (requiredVerifier != null) {
2279                throw new RuntimeException("There can be only one required verifier");
2280            }
2281
2282            requiredVerifier = packageName;
2283        }
2284
2285        return requiredVerifier;
2286    }
2287
2288    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2289        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2290        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2291                PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */);
2292
2293        ComponentName verifierComponentName = null;
2294
2295        int priority = -1000;
2296        final int N = receivers.size();
2297        for (int i = 0; i < N; i++) {
2298            final ResolveInfo info = receivers.get(i);
2299
2300            if (info.activityInfo == null) {
2301                continue;
2302            }
2303
2304            final String packageName = info.activityInfo.packageName;
2305
2306            final PackageSetting ps = mSettings.mPackages.get(packageName);
2307            if (ps == null) {
2308                continue;
2309            }
2310
2311            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2312                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2313                continue;
2314            }
2315
2316            // Select the IntentFilterVerifier with the highest priority
2317            if (priority < info.priority) {
2318                priority = info.priority;
2319                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2320                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2321                        + verifierComponentName + " with priority: " + info.priority);
2322            }
2323        }
2324
2325        return verifierComponentName;
2326    }
2327
2328    private void primeDomainVerificationsLPw() {
2329        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Start priming domain verifications");
2330        boolean updated = false;
2331        ArraySet<String> allHostsSet = new ArraySet<>();
2332        for (PackageParser.Package pkg : mPackages.values()) {
2333            final String packageName = pkg.packageName;
2334            if (!hasDomainURLs(pkg)) {
2335                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "No priming domain verifications for " +
2336                            "package with no domain URLs: " + packageName);
2337                continue;
2338            }
2339            if (!pkg.isSystemApp()) {
2340                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2341                        "No priming domain verifications for a non system package : " +
2342                                packageName);
2343                continue;
2344            }
2345            for (PackageParser.Activity a : pkg.activities) {
2346                for (ActivityIntentInfo filter : a.intents) {
2347                    if (hasValidDomains(filter)) {
2348                        allHostsSet.addAll(filter.getHostsList());
2349                    }
2350                }
2351            }
2352            if (allHostsSet.size() == 0) {
2353                allHostsSet.add("*");
2354            }
2355            ArrayList<String> allHostsList = new ArrayList<>(allHostsSet);
2356            IntentFilterVerificationInfo ivi =
2357                    mSettings.createIntentFilterVerificationIfNeededLPw(packageName, allHostsList);
2358            if (ivi != null) {
2359                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2360                        "Priming domain verifications for package: " + packageName +
2361                        " with hosts:" + ivi.getDomainsString());
2362                ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
2363                updated = true;
2364            }
2365            else {
2366                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2367                        "No priming domain verifications for package: " + packageName);
2368            }
2369            allHostsSet.clear();
2370        }
2371        if (updated) {
2372            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2373                    "Will need to write primed domain verifications");
2374        }
2375        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "End priming domain verifications");
2376    }
2377
2378    private void applyFactoryDefaultBrowserLPw(int userId) {
2379        // The default browser app's package name is stored in a string resource,
2380        // with a product-specific overlay used for vendor customization.
2381        String browserPkg = mContext.getResources().getString(
2382                com.android.internal.R.string.default_browser);
2383        if (browserPkg != null) {
2384            // non-empty string => required to be a known package
2385            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2386            if (ps == null) {
2387                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2388                browserPkg = null;
2389            } else {
2390                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2391            }
2392        }
2393
2394        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2395        // default.  If there's more than one, just leave everything alone.
2396        if (browserPkg == null) {
2397            calculateDefaultBrowserLPw(userId);
2398        }
2399    }
2400
2401    private void calculateDefaultBrowserLPw(int userId) {
2402        List<String> allBrowsers = resolveAllBrowserApps(userId);
2403        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2404        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2405    }
2406
2407    private List<String> resolveAllBrowserApps(int userId) {
2408        // Match all generic http: browser apps
2409        Intent intent = new Intent();
2410        intent.setAction(Intent.ACTION_VIEW);
2411        intent.addCategory(Intent.CATEGORY_BROWSABLE);
2412        intent.setData(Uri.parse("http:"));
2413
2414        // Resolve that intent and check that the handleAllWebDataURI boolean is set
2415        List<ResolveInfo> list = queryIntentActivities(intent, null, 0, userId);
2416
2417        final int count = list.size();
2418        List<String> result = new ArrayList<String>(count);
2419        for (int i=0; i<count; i++) {
2420            ResolveInfo info = list.get(i);
2421            if (info.activityInfo == null
2422                    || !info.handleAllWebDataURI
2423                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2424                    || result.contains(info.activityInfo.packageName)) {
2425                continue;
2426            }
2427            result.add(info.activityInfo.packageName);
2428        }
2429
2430        return result;
2431    }
2432
2433    private void checkDefaultBrowser() {
2434        final int myUserId = UserHandle.myUserId();
2435        final String packageName = getDefaultBrowserPackageName(myUserId);
2436        if (packageName != null) {
2437            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2438            if (info == null) {
2439                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2440                synchronized (mPackages) {
2441                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2442                }
2443            }
2444        }
2445    }
2446
2447    @Override
2448    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2449            throws RemoteException {
2450        try {
2451            return super.onTransact(code, data, reply, flags);
2452        } catch (RuntimeException e) {
2453            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2454                Slog.wtf(TAG, "Package Manager Crash", e);
2455            }
2456            throw e;
2457        }
2458    }
2459
2460    void cleanupInstallFailedPackage(PackageSetting ps) {
2461        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2462
2463        removeDataDirsLI(ps.volumeUuid, ps.name);
2464        if (ps.codePath != null) {
2465            if (ps.codePath.isDirectory()) {
2466                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2467            } else {
2468                ps.codePath.delete();
2469            }
2470        }
2471        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2472            if (ps.resourcePath.isDirectory()) {
2473                FileUtils.deleteContents(ps.resourcePath);
2474            }
2475            ps.resourcePath.delete();
2476        }
2477        mSettings.removePackageLPw(ps.name);
2478    }
2479
2480    static int[] appendInts(int[] cur, int[] add) {
2481        if (add == null) return cur;
2482        if (cur == null) return add;
2483        final int N = add.length;
2484        for (int i=0; i<N; i++) {
2485            cur = appendInt(cur, add[i]);
2486        }
2487        return cur;
2488    }
2489
2490    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2491        if (!sUserManager.exists(userId)) return null;
2492        final PackageSetting ps = (PackageSetting) p.mExtras;
2493        if (ps == null) {
2494            return null;
2495        }
2496
2497        final PermissionsState permissionsState = ps.getPermissionsState();
2498
2499        final int[] gids = permissionsState.computeGids(userId);
2500        final Set<String> permissions = permissionsState.getPermissions(userId);
2501        final PackageUserState state = ps.readUserState(userId);
2502
2503        return PackageParser.generatePackageInfo(p, gids, flags,
2504                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2505    }
2506
2507    @Override
2508    public boolean isPackageFrozen(String packageName) {
2509        synchronized (mPackages) {
2510            final PackageSetting ps = mSettings.mPackages.get(packageName);
2511            if (ps != null) {
2512                return ps.frozen;
2513            }
2514        }
2515        Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen");
2516        return true;
2517    }
2518
2519    @Override
2520    public boolean isPackageAvailable(String packageName, int userId) {
2521        if (!sUserManager.exists(userId)) return false;
2522        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2523        synchronized (mPackages) {
2524            PackageParser.Package p = mPackages.get(packageName);
2525            if (p != null) {
2526                final PackageSetting ps = (PackageSetting) p.mExtras;
2527                if (ps != null) {
2528                    final PackageUserState state = ps.readUserState(userId);
2529                    if (state != null) {
2530                        return PackageParser.isAvailable(state);
2531                    }
2532                }
2533            }
2534        }
2535        return false;
2536    }
2537
2538    @Override
2539    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2540        if (!sUserManager.exists(userId)) return null;
2541        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2542        // reader
2543        synchronized (mPackages) {
2544            PackageParser.Package p = mPackages.get(packageName);
2545            if (DEBUG_PACKAGE_INFO)
2546                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2547            if (p != null) {
2548                return generatePackageInfo(p, flags, userId);
2549            }
2550            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2551                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2552            }
2553        }
2554        return null;
2555    }
2556
2557    @Override
2558    public String[] currentToCanonicalPackageNames(String[] names) {
2559        String[] out = new String[names.length];
2560        // reader
2561        synchronized (mPackages) {
2562            for (int i=names.length-1; i>=0; i--) {
2563                PackageSetting ps = mSettings.mPackages.get(names[i]);
2564                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2565            }
2566        }
2567        return out;
2568    }
2569
2570    @Override
2571    public String[] canonicalToCurrentPackageNames(String[] names) {
2572        String[] out = new String[names.length];
2573        // reader
2574        synchronized (mPackages) {
2575            for (int i=names.length-1; i>=0; i--) {
2576                String cur = mSettings.mRenamedPackages.get(names[i]);
2577                out[i] = cur != null ? cur : names[i];
2578            }
2579        }
2580        return out;
2581    }
2582
2583    @Override
2584    public int getPackageUid(String packageName, int userId) {
2585        if (!sUserManager.exists(userId)) return -1;
2586        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2587
2588        // reader
2589        synchronized (mPackages) {
2590            PackageParser.Package p = mPackages.get(packageName);
2591            if(p != null) {
2592                return UserHandle.getUid(userId, p.applicationInfo.uid);
2593            }
2594            PackageSetting ps = mSettings.mPackages.get(packageName);
2595            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2596                return -1;
2597            }
2598            p = ps.pkg;
2599            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2600        }
2601    }
2602
2603    @Override
2604    public int[] getPackageGids(String packageName, int userId) throws RemoteException {
2605        if (!sUserManager.exists(userId)) {
2606            return null;
2607        }
2608
2609        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2610                "getPackageGids");
2611
2612        // reader
2613        synchronized (mPackages) {
2614            PackageParser.Package p = mPackages.get(packageName);
2615            if (DEBUG_PACKAGE_INFO) {
2616                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2617            }
2618            if (p != null) {
2619                PackageSetting ps = (PackageSetting) p.mExtras;
2620                return ps.getPermissionsState().computeGids(userId);
2621            }
2622        }
2623
2624        return null;
2625    }
2626
2627    @Override
2628    public int getMountExternalMode(int uid) {
2629        if (Process.isIsolated(uid)) {
2630            return Zygote.MOUNT_EXTERNAL_NONE;
2631        } else {
2632            if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_GRANTED) {
2633                return Zygote.MOUNT_EXTERNAL_WRITE;
2634            } else if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_GRANTED) {
2635                return Zygote.MOUNT_EXTERNAL_READ;
2636            } else {
2637                return Zygote.MOUNT_EXTERNAL_DEFAULT;
2638            }
2639        }
2640    }
2641
2642    static PermissionInfo generatePermissionInfo(
2643            BasePermission bp, int flags) {
2644        if (bp.perm != null) {
2645            return PackageParser.generatePermissionInfo(bp.perm, flags);
2646        }
2647        PermissionInfo pi = new PermissionInfo();
2648        pi.name = bp.name;
2649        pi.packageName = bp.sourcePackage;
2650        pi.nonLocalizedLabel = bp.name;
2651        pi.protectionLevel = bp.protectionLevel;
2652        return pi;
2653    }
2654
2655    @Override
2656    public PermissionInfo getPermissionInfo(String name, int flags) {
2657        // reader
2658        synchronized (mPackages) {
2659            final BasePermission p = mSettings.mPermissions.get(name);
2660            if (p != null) {
2661                return generatePermissionInfo(p, flags);
2662            }
2663            return null;
2664        }
2665    }
2666
2667    @Override
2668    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2669        // reader
2670        synchronized (mPackages) {
2671            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2672            for (BasePermission p : mSettings.mPermissions.values()) {
2673                if (group == null) {
2674                    if (p.perm == null || p.perm.info.group == null) {
2675                        out.add(generatePermissionInfo(p, flags));
2676                    }
2677                } else {
2678                    if (p.perm != null && group.equals(p.perm.info.group)) {
2679                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2680                    }
2681                }
2682            }
2683
2684            if (out.size() > 0) {
2685                return out;
2686            }
2687            return mPermissionGroups.containsKey(group) ? out : null;
2688        }
2689    }
2690
2691    @Override
2692    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2693        // reader
2694        synchronized (mPackages) {
2695            return PackageParser.generatePermissionGroupInfo(
2696                    mPermissionGroups.get(name), flags);
2697        }
2698    }
2699
2700    @Override
2701    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2702        // reader
2703        synchronized (mPackages) {
2704            final int N = mPermissionGroups.size();
2705            ArrayList<PermissionGroupInfo> out
2706                    = new ArrayList<PermissionGroupInfo>(N);
2707            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2708                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2709            }
2710            return out;
2711        }
2712    }
2713
2714    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2715            int userId) {
2716        if (!sUserManager.exists(userId)) return null;
2717        PackageSetting ps = mSettings.mPackages.get(packageName);
2718        if (ps != null) {
2719            if (ps.pkg == null) {
2720                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2721                        flags, userId);
2722                if (pInfo != null) {
2723                    return pInfo.applicationInfo;
2724                }
2725                return null;
2726            }
2727            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2728                    ps.readUserState(userId), userId);
2729        }
2730        return null;
2731    }
2732
2733    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2734            int userId) {
2735        if (!sUserManager.exists(userId)) return null;
2736        PackageSetting ps = mSettings.mPackages.get(packageName);
2737        if (ps != null) {
2738            PackageParser.Package pkg = ps.pkg;
2739            if (pkg == null) {
2740                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2741                    return null;
2742                }
2743                // Only data remains, so we aren't worried about code paths
2744                pkg = new PackageParser.Package(packageName);
2745                pkg.applicationInfo.packageName = packageName;
2746                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2747                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2748                pkg.applicationInfo.dataDir = PackageManager.getDataDirForUser(ps.volumeUuid,
2749                        packageName, userId).getAbsolutePath();
2750                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2751                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2752            }
2753            return generatePackageInfo(pkg, flags, userId);
2754        }
2755        return null;
2756    }
2757
2758    @Override
2759    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2760        if (!sUserManager.exists(userId)) return null;
2761        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2762        // writer
2763        synchronized (mPackages) {
2764            PackageParser.Package p = mPackages.get(packageName);
2765            if (DEBUG_PACKAGE_INFO) Log.v(
2766                    TAG, "getApplicationInfo " + packageName
2767                    + ": " + p);
2768            if (p != null) {
2769                PackageSetting ps = mSettings.mPackages.get(packageName);
2770                if (ps == null) return null;
2771                // Note: isEnabledLP() does not apply here - always return info
2772                return PackageParser.generateApplicationInfo(
2773                        p, flags, ps.readUserState(userId), userId);
2774            }
2775            if ("android".equals(packageName)||"system".equals(packageName)) {
2776                return mAndroidApplication;
2777            }
2778            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2779                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2780            }
2781        }
2782        return null;
2783    }
2784
2785    @Override
2786    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
2787            final IPackageDataObserver observer) {
2788        mContext.enforceCallingOrSelfPermission(
2789                android.Manifest.permission.CLEAR_APP_CACHE, null);
2790        // Queue up an async operation since clearing cache may take a little while.
2791        mHandler.post(new Runnable() {
2792            public void run() {
2793                mHandler.removeCallbacks(this);
2794                int retCode = -1;
2795                synchronized (mInstallLock) {
2796                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2797                    if (retCode < 0) {
2798                        Slog.w(TAG, "Couldn't clear application caches");
2799                    }
2800                }
2801                if (observer != null) {
2802                    try {
2803                        observer.onRemoveCompleted(null, (retCode >= 0));
2804                    } catch (RemoteException e) {
2805                        Slog.w(TAG, "RemoveException when invoking call back");
2806                    }
2807                }
2808            }
2809        });
2810    }
2811
2812    @Override
2813    public void freeStorage(final String volumeUuid, final long freeStorageSize,
2814            final IntentSender pi) {
2815        mContext.enforceCallingOrSelfPermission(
2816                android.Manifest.permission.CLEAR_APP_CACHE, null);
2817        // Queue up an async operation since clearing cache may take a little while.
2818        mHandler.post(new Runnable() {
2819            public void run() {
2820                mHandler.removeCallbacks(this);
2821                int retCode = -1;
2822                synchronized (mInstallLock) {
2823                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2824                    if (retCode < 0) {
2825                        Slog.w(TAG, "Couldn't clear application caches");
2826                    }
2827                }
2828                if(pi != null) {
2829                    try {
2830                        // Callback via pending intent
2831                        int code = (retCode >= 0) ? 1 : 0;
2832                        pi.sendIntent(null, code, null,
2833                                null, null);
2834                    } catch (SendIntentException e1) {
2835                        Slog.i(TAG, "Failed to send pending intent");
2836                    }
2837                }
2838            }
2839        });
2840    }
2841
2842    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
2843        synchronized (mInstallLock) {
2844            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
2845                throw new IOException("Failed to free enough space");
2846            }
2847        }
2848    }
2849
2850    @Override
2851    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2852        if (!sUserManager.exists(userId)) return null;
2853        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2854        synchronized (mPackages) {
2855            PackageParser.Activity a = mActivities.mActivities.get(component);
2856
2857            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2858            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2859                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2860                if (ps == null) return null;
2861                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2862                        userId);
2863            }
2864            if (mResolveComponentName.equals(component)) {
2865                return PackageParser.generateActivityInfo(mResolveActivity, flags,
2866                        new PackageUserState(), userId);
2867            }
2868        }
2869        return null;
2870    }
2871
2872    @Override
2873    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2874            String resolvedType) {
2875        synchronized (mPackages) {
2876            PackageParser.Activity a = mActivities.mActivities.get(component);
2877            if (a == null) {
2878                return false;
2879            }
2880            for (int i=0; i<a.intents.size(); i++) {
2881                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2882                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2883                    return true;
2884                }
2885            }
2886            return false;
2887        }
2888    }
2889
2890    @Override
2891    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2892        if (!sUserManager.exists(userId)) return null;
2893        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
2894        synchronized (mPackages) {
2895            PackageParser.Activity a = mReceivers.mActivities.get(component);
2896            if (DEBUG_PACKAGE_INFO) Log.v(
2897                TAG, "getReceiverInfo " + component + ": " + a);
2898            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2899                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2900                if (ps == null) return null;
2901                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2902                        userId);
2903            }
2904        }
2905        return null;
2906    }
2907
2908    @Override
2909    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2910        if (!sUserManager.exists(userId)) return null;
2911        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
2912        synchronized (mPackages) {
2913            PackageParser.Service s = mServices.mServices.get(component);
2914            if (DEBUG_PACKAGE_INFO) Log.v(
2915                TAG, "getServiceInfo " + component + ": " + s);
2916            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2917                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2918                if (ps == null) return null;
2919                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2920                        userId);
2921            }
2922        }
2923        return null;
2924    }
2925
2926    @Override
2927    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2928        if (!sUserManager.exists(userId)) return null;
2929        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
2930        synchronized (mPackages) {
2931            PackageParser.Provider p = mProviders.mProviders.get(component);
2932            if (DEBUG_PACKAGE_INFO) Log.v(
2933                TAG, "getProviderInfo " + component + ": " + p);
2934            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2935                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2936                if (ps == null) return null;
2937                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2938                        userId);
2939            }
2940        }
2941        return null;
2942    }
2943
2944    @Override
2945    public String[] getSystemSharedLibraryNames() {
2946        Set<String> libSet;
2947        synchronized (mPackages) {
2948            libSet = mSharedLibraries.keySet();
2949            int size = libSet.size();
2950            if (size > 0) {
2951                String[] libs = new String[size];
2952                libSet.toArray(libs);
2953                return libs;
2954            }
2955        }
2956        return null;
2957    }
2958
2959    /**
2960     * @hide
2961     */
2962    PackageParser.Package findSharedNonSystemLibrary(String libName) {
2963        synchronized (mPackages) {
2964            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
2965            if (lib != null && lib.apk != null) {
2966                return mPackages.get(lib.apk);
2967            }
2968        }
2969        return null;
2970    }
2971
2972    @Override
2973    public FeatureInfo[] getSystemAvailableFeatures() {
2974        Collection<FeatureInfo> featSet;
2975        synchronized (mPackages) {
2976            featSet = mAvailableFeatures.values();
2977            int size = featSet.size();
2978            if (size > 0) {
2979                FeatureInfo[] features = new FeatureInfo[size+1];
2980                featSet.toArray(features);
2981                FeatureInfo fi = new FeatureInfo();
2982                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2983                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2984                features[size] = fi;
2985                return features;
2986            }
2987        }
2988        return null;
2989    }
2990
2991    @Override
2992    public boolean hasSystemFeature(String name) {
2993        synchronized (mPackages) {
2994            return mAvailableFeatures.containsKey(name);
2995        }
2996    }
2997
2998    private void checkValidCaller(int uid, int userId) {
2999        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
3000            return;
3001
3002        throw new SecurityException("Caller uid=" + uid
3003                + " is not privileged to communicate with user=" + userId);
3004    }
3005
3006    @Override
3007    public int checkPermission(String permName, String pkgName, int userId) {
3008        if (!sUserManager.exists(userId)) {
3009            return PackageManager.PERMISSION_DENIED;
3010        }
3011
3012        synchronized (mPackages) {
3013            final PackageParser.Package p = mPackages.get(pkgName);
3014            if (p != null && p.mExtras != null) {
3015                final PackageSetting ps = (PackageSetting) p.mExtras;
3016                if (ps.getPermissionsState().hasPermission(permName, userId)) {
3017                    return PackageManager.PERMISSION_GRANTED;
3018                }
3019            }
3020        }
3021
3022        return PackageManager.PERMISSION_DENIED;
3023    }
3024
3025    @Override
3026    public int checkUidPermission(String permName, int uid) {
3027        final int userId = UserHandle.getUserId(uid);
3028
3029        if (!sUserManager.exists(userId)) {
3030            return PackageManager.PERMISSION_DENIED;
3031        }
3032
3033        synchronized (mPackages) {
3034            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3035            if (obj != null) {
3036                final SettingBase ps = (SettingBase) obj;
3037                if (ps.getPermissionsState().hasPermission(permName, userId)) {
3038                    return PackageManager.PERMISSION_GRANTED;
3039                }
3040            } else {
3041                ArraySet<String> perms = mSystemPermissions.get(uid);
3042                if (perms != null && perms.contains(permName)) {
3043                    return PackageManager.PERMISSION_GRANTED;
3044                }
3045            }
3046        }
3047
3048        return PackageManager.PERMISSION_DENIED;
3049    }
3050
3051    /**
3052     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3053     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3054     * @param checkShell TODO(yamasani):
3055     * @param message the message to log on security exception
3056     */
3057    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3058            boolean checkShell, String message) {
3059        if (userId < 0) {
3060            throw new IllegalArgumentException("Invalid userId " + userId);
3061        }
3062        if (checkShell) {
3063            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3064        }
3065        if (userId == UserHandle.getUserId(callingUid)) return;
3066        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3067            if (requireFullPermission) {
3068                mContext.enforceCallingOrSelfPermission(
3069                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3070            } else {
3071                try {
3072                    mContext.enforceCallingOrSelfPermission(
3073                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3074                } catch (SecurityException se) {
3075                    mContext.enforceCallingOrSelfPermission(
3076                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3077                }
3078            }
3079        }
3080    }
3081
3082    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3083        if (callingUid == Process.SHELL_UID) {
3084            if (userHandle >= 0
3085                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3086                throw new SecurityException("Shell does not have permission to access user "
3087                        + userHandle);
3088            } else if (userHandle < 0) {
3089                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3090                        + Debug.getCallers(3));
3091            }
3092        }
3093    }
3094
3095    private BasePermission findPermissionTreeLP(String permName) {
3096        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3097            if (permName.startsWith(bp.name) &&
3098                    permName.length() > bp.name.length() &&
3099                    permName.charAt(bp.name.length()) == '.') {
3100                return bp;
3101            }
3102        }
3103        return null;
3104    }
3105
3106    private BasePermission checkPermissionTreeLP(String permName) {
3107        if (permName != null) {
3108            BasePermission bp = findPermissionTreeLP(permName);
3109            if (bp != null) {
3110                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3111                    return bp;
3112                }
3113                throw new SecurityException("Calling uid "
3114                        + Binder.getCallingUid()
3115                        + " is not allowed to add to permission tree "
3116                        + bp.name + " owned by uid " + bp.uid);
3117            }
3118        }
3119        throw new SecurityException("No permission tree found for " + permName);
3120    }
3121
3122    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3123        if (s1 == null) {
3124            return s2 == null;
3125        }
3126        if (s2 == null) {
3127            return false;
3128        }
3129        if (s1.getClass() != s2.getClass()) {
3130            return false;
3131        }
3132        return s1.equals(s2);
3133    }
3134
3135    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3136        if (pi1.icon != pi2.icon) return false;
3137        if (pi1.logo != pi2.logo) return false;
3138        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3139        if (!compareStrings(pi1.name, pi2.name)) return false;
3140        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3141        // We'll take care of setting this one.
3142        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3143        // These are not currently stored in settings.
3144        //if (!compareStrings(pi1.group, pi2.group)) return false;
3145        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3146        //if (pi1.labelRes != pi2.labelRes) return false;
3147        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3148        return true;
3149    }
3150
3151    int permissionInfoFootprint(PermissionInfo info) {
3152        int size = info.name.length();
3153        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3154        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3155        return size;
3156    }
3157
3158    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3159        int size = 0;
3160        for (BasePermission perm : mSettings.mPermissions.values()) {
3161            if (perm.uid == tree.uid) {
3162                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3163            }
3164        }
3165        return size;
3166    }
3167
3168    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3169        // We calculate the max size of permissions defined by this uid and throw
3170        // if that plus the size of 'info' would exceed our stated maximum.
3171        if (tree.uid != Process.SYSTEM_UID) {
3172            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3173            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3174                throw new SecurityException("Permission tree size cap exceeded");
3175            }
3176        }
3177    }
3178
3179    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3180        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3181            throw new SecurityException("Label must be specified in permission");
3182        }
3183        BasePermission tree = checkPermissionTreeLP(info.name);
3184        BasePermission bp = mSettings.mPermissions.get(info.name);
3185        boolean added = bp == null;
3186        boolean changed = true;
3187        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3188        if (added) {
3189            enforcePermissionCapLocked(info, tree);
3190            bp = new BasePermission(info.name, tree.sourcePackage,
3191                    BasePermission.TYPE_DYNAMIC);
3192        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3193            throw new SecurityException(
3194                    "Not allowed to modify non-dynamic permission "
3195                    + info.name);
3196        } else {
3197            if (bp.protectionLevel == fixedLevel
3198                    && bp.perm.owner.equals(tree.perm.owner)
3199                    && bp.uid == tree.uid
3200                    && comparePermissionInfos(bp.perm.info, info)) {
3201                changed = false;
3202            }
3203        }
3204        bp.protectionLevel = fixedLevel;
3205        info = new PermissionInfo(info);
3206        info.protectionLevel = fixedLevel;
3207        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3208        bp.perm.info.packageName = tree.perm.info.packageName;
3209        bp.uid = tree.uid;
3210        if (added) {
3211            mSettings.mPermissions.put(info.name, bp);
3212        }
3213        if (changed) {
3214            if (!async) {
3215                mSettings.writeLPr();
3216            } else {
3217                scheduleWriteSettingsLocked();
3218            }
3219        }
3220        return added;
3221    }
3222
3223    @Override
3224    public boolean addPermission(PermissionInfo info) {
3225        synchronized (mPackages) {
3226            return addPermissionLocked(info, false);
3227        }
3228    }
3229
3230    @Override
3231    public boolean addPermissionAsync(PermissionInfo info) {
3232        synchronized (mPackages) {
3233            return addPermissionLocked(info, true);
3234        }
3235    }
3236
3237    @Override
3238    public void removePermission(String name) {
3239        synchronized (mPackages) {
3240            checkPermissionTreeLP(name);
3241            BasePermission bp = mSettings.mPermissions.get(name);
3242            if (bp != null) {
3243                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3244                    throw new SecurityException(
3245                            "Not allowed to modify non-dynamic permission "
3246                            + name);
3247                }
3248                mSettings.mPermissions.remove(name);
3249                mSettings.writeLPr();
3250            }
3251        }
3252    }
3253
3254    private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg,
3255            BasePermission bp) {
3256        int index = pkg.requestedPermissions.indexOf(bp.name);
3257        if (index == -1) {
3258            throw new SecurityException("Package " + pkg.packageName
3259                    + " has not requested permission " + bp.name);
3260        }
3261        if (!bp.isRuntime()) {
3262            throw new SecurityException("Permission " + bp.name
3263                    + " is not a changeable permission type");
3264        }
3265    }
3266
3267    @Override
3268    public void grantRuntimePermission(String packageName, String name, final int userId) {
3269        if (!sUserManager.exists(userId)) {
3270            Log.e(TAG, "No such user:" + userId);
3271            return;
3272        }
3273
3274        mContext.enforceCallingOrSelfPermission(
3275                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3276                "grantRuntimePermission");
3277
3278        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3279                "grantRuntimePermission");
3280
3281        final int uid;
3282        final SettingBase sb;
3283
3284        synchronized (mPackages) {
3285            final PackageParser.Package pkg = mPackages.get(packageName);
3286            if (pkg == null) {
3287                throw new IllegalArgumentException("Unknown package: " + packageName);
3288            }
3289
3290            final BasePermission bp = mSettings.mPermissions.get(name);
3291            if (bp == null) {
3292                throw new IllegalArgumentException("Unknown permission: " + name);
3293            }
3294
3295            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3296
3297            uid = pkg.applicationInfo.uid;
3298            sb = (SettingBase) pkg.mExtras;
3299            if (sb == null) {
3300                throw new IllegalArgumentException("Unknown package: " + packageName);
3301            }
3302
3303            final PermissionsState permissionsState = sb.getPermissionsState();
3304
3305            final int flags = permissionsState.getPermissionFlags(name, userId);
3306            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3307                throw new SecurityException("Cannot grant system fixed permission: "
3308                        + name + " for package: " + packageName);
3309            }
3310
3311            final int result = permissionsState.grantRuntimePermission(bp, userId);
3312            switch (result) {
3313                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3314                    return;
3315                }
3316
3317                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3318                    mHandler.post(new Runnable() {
3319                        @Override
3320                        public void run() {
3321                            killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED);
3322                        }
3323                    });
3324                } break;
3325            }
3326
3327            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3328
3329            // Not critical if that is lost - app has to request again.
3330            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3331        }
3332
3333        if (READ_EXTERNAL_STORAGE.equals(name)
3334                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3335            final long token = Binder.clearCallingIdentity();
3336            try {
3337                final StorageManager storage = mContext.getSystemService(StorageManager.class);
3338                storage.remountUid(uid);
3339            } finally {
3340                Binder.restoreCallingIdentity(token);
3341            }
3342        }
3343    }
3344
3345    @Override
3346    public void revokeRuntimePermission(String packageName, String name, int userId) {
3347        if (!sUserManager.exists(userId)) {
3348            Log.e(TAG, "No such user:" + userId);
3349            return;
3350        }
3351
3352        mContext.enforceCallingOrSelfPermission(
3353                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3354                "revokeRuntimePermission");
3355
3356        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3357                "revokeRuntimePermission");
3358
3359        final SettingBase sb;
3360
3361        synchronized (mPackages) {
3362            final PackageParser.Package pkg = mPackages.get(packageName);
3363            if (pkg == null) {
3364                throw new IllegalArgumentException("Unknown package: " + packageName);
3365            }
3366
3367            final BasePermission bp = mSettings.mPermissions.get(name);
3368            if (bp == null) {
3369                throw new IllegalArgumentException("Unknown permission: " + name);
3370            }
3371
3372            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3373
3374            sb = (SettingBase) pkg.mExtras;
3375            if (sb == null) {
3376                throw new IllegalArgumentException("Unknown package: " + packageName);
3377            }
3378
3379            final PermissionsState permissionsState = sb.getPermissionsState();
3380
3381            final int flags = permissionsState.getPermissionFlags(name, userId);
3382            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3383                throw new SecurityException("Cannot revoke system fixed permission: "
3384                        + name + " for package: " + packageName);
3385            }
3386
3387            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3388                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3389                return;
3390            }
3391
3392            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3393
3394            // Critical, after this call app should never have the permission.
3395            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3396        }
3397
3398        killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3399    }
3400
3401    @Override
3402    public void resetRuntimePermissions() {
3403        mContext.enforceCallingOrSelfPermission(
3404                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3405                "revokeRuntimePermission");
3406
3407        int callingUid = Binder.getCallingUid();
3408        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3409            mContext.enforceCallingOrSelfPermission(
3410                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3411                    "resetRuntimePermissions");
3412        }
3413
3414        final int[] userIds;
3415
3416        synchronized (mPackages) {
3417            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3418            final int userCount = UserManagerService.getInstance().getUserIds().length;
3419            userIds = Arrays.copyOf(UserManagerService.getInstance().getUserIds(), userCount);
3420        }
3421
3422        for (int userId : userIds) {
3423            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
3424        }
3425    }
3426
3427    @Override
3428    public int getPermissionFlags(String name, String packageName, int userId) {
3429        if (!sUserManager.exists(userId)) {
3430            return 0;
3431        }
3432
3433        mContext.enforceCallingOrSelfPermission(
3434                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3435                "getPermissionFlags");
3436
3437        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3438                "getPermissionFlags");
3439
3440        synchronized (mPackages) {
3441            final PackageParser.Package pkg = mPackages.get(packageName);
3442            if (pkg == null) {
3443                throw new IllegalArgumentException("Unknown package: " + packageName);
3444            }
3445
3446            final BasePermission bp = mSettings.mPermissions.get(name);
3447            if (bp == null) {
3448                throw new IllegalArgumentException("Unknown permission: " + name);
3449            }
3450
3451            SettingBase sb = (SettingBase) pkg.mExtras;
3452            if (sb == null) {
3453                throw new IllegalArgumentException("Unknown package: " + packageName);
3454            }
3455
3456            PermissionsState permissionsState = sb.getPermissionsState();
3457            return permissionsState.getPermissionFlags(name, userId);
3458        }
3459    }
3460
3461    @Override
3462    public void updatePermissionFlags(String name, String packageName, int flagMask,
3463            int flagValues, int userId) {
3464        if (!sUserManager.exists(userId)) {
3465            return;
3466        }
3467
3468        mContext.enforceCallingOrSelfPermission(
3469                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3470                "updatePermissionFlags");
3471
3472        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3473                "updatePermissionFlags");
3474
3475        // Only the system can change system fixed flags.
3476        if (getCallingUid() != Process.SYSTEM_UID) {
3477            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3478            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3479        }
3480
3481        synchronized (mPackages) {
3482            final PackageParser.Package pkg = mPackages.get(packageName);
3483            if (pkg == null) {
3484                throw new IllegalArgumentException("Unknown package: " + packageName);
3485            }
3486
3487            final BasePermission bp = mSettings.mPermissions.get(name);
3488            if (bp == null) {
3489                throw new IllegalArgumentException("Unknown permission: " + name);
3490            }
3491
3492            SettingBase sb = (SettingBase) pkg.mExtras;
3493            if (sb == null) {
3494                throw new IllegalArgumentException("Unknown package: " + packageName);
3495            }
3496
3497            PermissionsState permissionsState = sb.getPermissionsState();
3498
3499            // Only the package manager can change flags for system component permissions.
3500            final int flags = permissionsState.getPermissionFlags(bp.name, userId);
3501            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3502                return;
3503            }
3504
3505            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3506
3507            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3508                // Install and runtime permissions are stored in different places,
3509                // so figure out what permission changed and persist the change.
3510                if (permissionsState.getInstallPermissionState(name) != null) {
3511                    scheduleWriteSettingsLocked();
3512                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3513                        || hadState) {
3514                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3515                }
3516            }
3517        }
3518    }
3519
3520    /**
3521     * Update the permission flags for all packages and runtime permissions of a user in order
3522     * to allow device or profile owner to remove POLICY_FIXED.
3523     */
3524    @Override
3525    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3526        if (!sUserManager.exists(userId)) {
3527            return;
3528        }
3529
3530        mContext.enforceCallingOrSelfPermission(
3531                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3532                "updatePermissionFlagsForAllApps");
3533
3534        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3535                "updatePermissionFlagsForAllApps");
3536
3537        // Only the system can change system fixed flags.
3538        if (getCallingUid() != Process.SYSTEM_UID) {
3539            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3540            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3541        }
3542
3543        synchronized (mPackages) {
3544            boolean changed = false;
3545            final int packageCount = mPackages.size();
3546            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
3547                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
3548                SettingBase sb = (SettingBase) pkg.mExtras;
3549                if (sb == null) {
3550                    continue;
3551                }
3552                PermissionsState permissionsState = sb.getPermissionsState();
3553                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
3554                        userId, flagMask, flagValues);
3555            }
3556            if (changed) {
3557                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3558            }
3559        }
3560    }
3561
3562    @Override
3563    public boolean shouldShowRequestPermissionRationale(String permissionName,
3564            String packageName, int userId) {
3565        if (UserHandle.getCallingUserId() != userId) {
3566            mContext.enforceCallingPermission(
3567                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3568                    "canShowRequestPermissionRationale for user " + userId);
3569        }
3570
3571        final int uid = getPackageUid(packageName, userId);
3572        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
3573            return false;
3574        }
3575
3576        if (checkPermission(permissionName, packageName, userId)
3577                == PackageManager.PERMISSION_GRANTED) {
3578            return false;
3579        }
3580
3581        final int flags;
3582
3583        final long identity = Binder.clearCallingIdentity();
3584        try {
3585            flags = getPermissionFlags(permissionName,
3586                    packageName, userId);
3587        } finally {
3588            Binder.restoreCallingIdentity(identity);
3589        }
3590
3591        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
3592                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
3593                | PackageManager.FLAG_PERMISSION_USER_FIXED;
3594
3595        if ((flags & fixedFlags) != 0) {
3596            return false;
3597        }
3598
3599        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
3600    }
3601
3602    void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) {
3603        BasePermission bp = mSettings.mPermissions.get(permission);
3604        if (bp == null) {
3605            throw new SecurityException("Missing " + permission + " permission");
3606        }
3607
3608        SettingBase sb = (SettingBase) pkg.mExtras;
3609        PermissionsState permissionsState = sb.getPermissionsState();
3610
3611        if (permissionsState.grantInstallPermission(bp) !=
3612                PermissionsState.PERMISSION_OPERATION_FAILURE) {
3613            scheduleWriteSettingsLocked();
3614        }
3615    }
3616
3617    @Override
3618    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3619        mContext.enforceCallingOrSelfPermission(
3620                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
3621                "addOnPermissionsChangeListener");
3622
3623        synchronized (mPackages) {
3624            mOnPermissionChangeListeners.addListenerLocked(listener);
3625        }
3626    }
3627
3628    @Override
3629    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3630        synchronized (mPackages) {
3631            mOnPermissionChangeListeners.removeListenerLocked(listener);
3632        }
3633    }
3634
3635    @Override
3636    public boolean isProtectedBroadcast(String actionName) {
3637        synchronized (mPackages) {
3638            return mProtectedBroadcasts.contains(actionName);
3639        }
3640    }
3641
3642    @Override
3643    public int checkSignatures(String pkg1, String pkg2) {
3644        synchronized (mPackages) {
3645            final PackageParser.Package p1 = mPackages.get(pkg1);
3646            final PackageParser.Package p2 = mPackages.get(pkg2);
3647            if (p1 == null || p1.mExtras == null
3648                    || p2 == null || p2.mExtras == null) {
3649                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3650            }
3651            return compareSignatures(p1.mSignatures, p2.mSignatures);
3652        }
3653    }
3654
3655    @Override
3656    public int checkUidSignatures(int uid1, int uid2) {
3657        // Map to base uids.
3658        uid1 = UserHandle.getAppId(uid1);
3659        uid2 = UserHandle.getAppId(uid2);
3660        // reader
3661        synchronized (mPackages) {
3662            Signature[] s1;
3663            Signature[] s2;
3664            Object obj = mSettings.getUserIdLPr(uid1);
3665            if (obj != null) {
3666                if (obj instanceof SharedUserSetting) {
3667                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3668                } else if (obj instanceof PackageSetting) {
3669                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3670                } else {
3671                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3672                }
3673            } else {
3674                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3675            }
3676            obj = mSettings.getUserIdLPr(uid2);
3677            if (obj != null) {
3678                if (obj instanceof SharedUserSetting) {
3679                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3680                } else if (obj instanceof PackageSetting) {
3681                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3682                } else {
3683                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3684                }
3685            } else {
3686                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3687            }
3688            return compareSignatures(s1, s2);
3689        }
3690    }
3691
3692    private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) {
3693        final long identity = Binder.clearCallingIdentity();
3694        try {
3695            if (sb instanceof SharedUserSetting) {
3696                SharedUserSetting sus = (SharedUserSetting) sb;
3697                final int packageCount = sus.packages.size();
3698                for (int i = 0; i < packageCount; i++) {
3699                    PackageSetting susPs = sus.packages.valueAt(i);
3700                    if (userId == UserHandle.USER_ALL) {
3701                        killApplication(susPs.pkg.packageName, susPs.appId, reason);
3702                    } else {
3703                        final int uid = UserHandle.getUid(userId, susPs.appId);
3704                        killUid(uid, reason);
3705                    }
3706                }
3707            } else if (sb instanceof PackageSetting) {
3708                PackageSetting ps = (PackageSetting) sb;
3709                if (userId == UserHandle.USER_ALL) {
3710                    killApplication(ps.pkg.packageName, ps.appId, reason);
3711                } else {
3712                    final int uid = UserHandle.getUid(userId, ps.appId);
3713                    killUid(uid, reason);
3714                }
3715            }
3716        } finally {
3717            Binder.restoreCallingIdentity(identity);
3718        }
3719    }
3720
3721    private static void killUid(int uid, String reason) {
3722        IActivityManager am = ActivityManagerNative.getDefault();
3723        if (am != null) {
3724            try {
3725                am.killUid(uid, reason);
3726            } catch (RemoteException e) {
3727                /* ignore - same process */
3728            }
3729        }
3730    }
3731
3732    /**
3733     * Compares two sets of signatures. Returns:
3734     * <br />
3735     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3736     * <br />
3737     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3738     * <br />
3739     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3740     * <br />
3741     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3742     * <br />
3743     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3744     */
3745    static int compareSignatures(Signature[] s1, Signature[] s2) {
3746        if (s1 == null) {
3747            return s2 == null
3748                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3749                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3750        }
3751
3752        if (s2 == null) {
3753            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3754        }
3755
3756        if (s1.length != s2.length) {
3757            return PackageManager.SIGNATURE_NO_MATCH;
3758        }
3759
3760        // Since both signature sets are of size 1, we can compare without HashSets.
3761        if (s1.length == 1) {
3762            return s1[0].equals(s2[0]) ?
3763                    PackageManager.SIGNATURE_MATCH :
3764                    PackageManager.SIGNATURE_NO_MATCH;
3765        }
3766
3767        ArraySet<Signature> set1 = new ArraySet<Signature>();
3768        for (Signature sig : s1) {
3769            set1.add(sig);
3770        }
3771        ArraySet<Signature> set2 = new ArraySet<Signature>();
3772        for (Signature sig : s2) {
3773            set2.add(sig);
3774        }
3775        // Make sure s2 contains all signatures in s1.
3776        if (set1.equals(set2)) {
3777            return PackageManager.SIGNATURE_MATCH;
3778        }
3779        return PackageManager.SIGNATURE_NO_MATCH;
3780    }
3781
3782    /**
3783     * If the database version for this type of package (internal storage or
3784     * external storage) is less than the version where package signatures
3785     * were updated, return true.
3786     */
3787    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3788        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
3789                DatabaseVersion.SIGNATURE_END_ENTITY))
3790                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
3791                        DatabaseVersion.SIGNATURE_END_ENTITY));
3792    }
3793
3794    /**
3795     * Used for backward compatibility to make sure any packages with
3796     * certificate chains get upgraded to the new style. {@code existingSigs}
3797     * will be in the old format (since they were stored on disk from before the
3798     * system upgrade) and {@code scannedSigs} will be in the newer format.
3799     */
3800    private int compareSignaturesCompat(PackageSignatures existingSigs,
3801            PackageParser.Package scannedPkg) {
3802        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
3803            return PackageManager.SIGNATURE_NO_MATCH;
3804        }
3805
3806        ArraySet<Signature> existingSet = new ArraySet<Signature>();
3807        for (Signature sig : existingSigs.mSignatures) {
3808            existingSet.add(sig);
3809        }
3810        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
3811        for (Signature sig : scannedPkg.mSignatures) {
3812            try {
3813                Signature[] chainSignatures = sig.getChainSignatures();
3814                for (Signature chainSig : chainSignatures) {
3815                    scannedCompatSet.add(chainSig);
3816                }
3817            } catch (CertificateEncodingException e) {
3818                scannedCompatSet.add(sig);
3819            }
3820        }
3821        /*
3822         * Make sure the expanded scanned set contains all signatures in the
3823         * existing one.
3824         */
3825        if (scannedCompatSet.equals(existingSet)) {
3826            // Migrate the old signatures to the new scheme.
3827            existingSigs.assignSignatures(scannedPkg.mSignatures);
3828            // The new KeySets will be re-added later in the scanning process.
3829            synchronized (mPackages) {
3830                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
3831            }
3832            return PackageManager.SIGNATURE_MATCH;
3833        }
3834        return PackageManager.SIGNATURE_NO_MATCH;
3835    }
3836
3837    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3838        if (isExternal(scannedPkg)) {
3839            return mSettings.isExternalDatabaseVersionOlderThan(
3840                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3841        } else {
3842            return mSettings.isInternalDatabaseVersionOlderThan(
3843                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3844        }
3845    }
3846
3847    private int compareSignaturesRecover(PackageSignatures existingSigs,
3848            PackageParser.Package scannedPkg) {
3849        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
3850            return PackageManager.SIGNATURE_NO_MATCH;
3851        }
3852
3853        String msg = null;
3854        try {
3855            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
3856                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
3857                        + scannedPkg.packageName);
3858                return PackageManager.SIGNATURE_MATCH;
3859            }
3860        } catch (CertificateException e) {
3861            msg = e.getMessage();
3862        }
3863
3864        logCriticalInfo(Log.INFO,
3865                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
3866        return PackageManager.SIGNATURE_NO_MATCH;
3867    }
3868
3869    @Override
3870    public String[] getPackagesForUid(int uid) {
3871        uid = UserHandle.getAppId(uid);
3872        // reader
3873        synchronized (mPackages) {
3874            Object obj = mSettings.getUserIdLPr(uid);
3875            if (obj instanceof SharedUserSetting) {
3876                final SharedUserSetting sus = (SharedUserSetting) obj;
3877                final int N = sus.packages.size();
3878                final String[] res = new String[N];
3879                final Iterator<PackageSetting> it = sus.packages.iterator();
3880                int i = 0;
3881                while (it.hasNext()) {
3882                    res[i++] = it.next().name;
3883                }
3884                return res;
3885            } else if (obj instanceof PackageSetting) {
3886                final PackageSetting ps = (PackageSetting) obj;
3887                return new String[] { ps.name };
3888            }
3889        }
3890        return null;
3891    }
3892
3893    @Override
3894    public String getNameForUid(int uid) {
3895        // reader
3896        synchronized (mPackages) {
3897            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3898            if (obj instanceof SharedUserSetting) {
3899                final SharedUserSetting sus = (SharedUserSetting) obj;
3900                return sus.name + ":" + sus.userId;
3901            } else if (obj instanceof PackageSetting) {
3902                final PackageSetting ps = (PackageSetting) obj;
3903                return ps.name;
3904            }
3905        }
3906        return null;
3907    }
3908
3909    @Override
3910    public int getUidForSharedUser(String sharedUserName) {
3911        if(sharedUserName == null) {
3912            return -1;
3913        }
3914        // reader
3915        synchronized (mPackages) {
3916            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
3917            if (suid == null) {
3918                return -1;
3919            }
3920            return suid.userId;
3921        }
3922    }
3923
3924    @Override
3925    public int getFlagsForUid(int uid) {
3926        synchronized (mPackages) {
3927            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3928            if (obj instanceof SharedUserSetting) {
3929                final SharedUserSetting sus = (SharedUserSetting) obj;
3930                return sus.pkgFlags;
3931            } else if (obj instanceof PackageSetting) {
3932                final PackageSetting ps = (PackageSetting) obj;
3933                return ps.pkgFlags;
3934            }
3935        }
3936        return 0;
3937    }
3938
3939    @Override
3940    public int getPrivateFlagsForUid(int uid) {
3941        synchronized (mPackages) {
3942            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3943            if (obj instanceof SharedUserSetting) {
3944                final SharedUserSetting sus = (SharedUserSetting) obj;
3945                return sus.pkgPrivateFlags;
3946            } else if (obj instanceof PackageSetting) {
3947                final PackageSetting ps = (PackageSetting) obj;
3948                return ps.pkgPrivateFlags;
3949            }
3950        }
3951        return 0;
3952    }
3953
3954    @Override
3955    public boolean isUidPrivileged(int uid) {
3956        uid = UserHandle.getAppId(uid);
3957        // reader
3958        synchronized (mPackages) {
3959            Object obj = mSettings.getUserIdLPr(uid);
3960            if (obj instanceof SharedUserSetting) {
3961                final SharedUserSetting sus = (SharedUserSetting) obj;
3962                final Iterator<PackageSetting> it = sus.packages.iterator();
3963                while (it.hasNext()) {
3964                    if (it.next().isPrivileged()) {
3965                        return true;
3966                    }
3967                }
3968            } else if (obj instanceof PackageSetting) {
3969                final PackageSetting ps = (PackageSetting) obj;
3970                return ps.isPrivileged();
3971            }
3972        }
3973        return false;
3974    }
3975
3976    @Override
3977    public String[] getAppOpPermissionPackages(String permissionName) {
3978        synchronized (mPackages) {
3979            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
3980            if (pkgs == null) {
3981                return null;
3982            }
3983            return pkgs.toArray(new String[pkgs.size()]);
3984        }
3985    }
3986
3987    @Override
3988    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
3989            int flags, int userId) {
3990        if (!sUserManager.exists(userId)) return null;
3991        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
3992        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3993        return chooseBestActivity(intent, resolvedType, flags, query, userId);
3994    }
3995
3996    @Override
3997    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
3998            IntentFilter filter, int match, ComponentName activity) {
3999        final int userId = UserHandle.getCallingUserId();
4000        if (DEBUG_PREFERRED) {
4001            Log.v(TAG, "setLastChosenActivity intent=" + intent
4002                + " resolvedType=" + resolvedType
4003                + " flags=" + flags
4004                + " filter=" + filter
4005                + " match=" + match
4006                + " activity=" + activity);
4007            filter.dump(new PrintStreamPrinter(System.out), "    ");
4008        }
4009        intent.setComponent(null);
4010        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4011        // Find any earlier preferred or last chosen entries and nuke them
4012        findPreferredActivity(intent, resolvedType,
4013                flags, query, 0, false, true, false, userId);
4014        // Add the new activity as the last chosen for this filter
4015        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4016                "Setting last chosen");
4017    }
4018
4019    @Override
4020    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4021        final int userId = UserHandle.getCallingUserId();
4022        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4023        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4024        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4025                false, false, false, userId);
4026    }
4027
4028    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4029            int flags, List<ResolveInfo> query, int userId) {
4030        if (query != null) {
4031            final int N = query.size();
4032            if (N == 1) {
4033                return query.get(0);
4034            } else if (N > 1) {
4035                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4036                // If there is more than one activity with the same priority,
4037                // then let the user decide between them.
4038                ResolveInfo r0 = query.get(0);
4039                ResolveInfo r1 = query.get(1);
4040                if (DEBUG_INTENT_MATCHING || debug) {
4041                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4042                            + r1.activityInfo.name + "=" + r1.priority);
4043                }
4044                // If the first activity has a higher priority, or a different
4045                // default, then it is always desireable to pick it.
4046                if (r0.priority != r1.priority
4047                        || r0.preferredOrder != r1.preferredOrder
4048                        || r0.isDefault != r1.isDefault) {
4049                    return query.get(0);
4050                }
4051                // If we have saved a preference for a preferred activity for
4052                // this Intent, use that.
4053                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4054                        flags, query, r0.priority, true, false, debug, userId);
4055                if (ri != null) {
4056                    return ri;
4057                }
4058                if (userId != 0) {
4059                    ri = new ResolveInfo(mResolveInfo);
4060                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
4061                    ri.activityInfo.applicationInfo = new ApplicationInfo(
4062                            ri.activityInfo.applicationInfo);
4063                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4064                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4065                    return ri;
4066                }
4067                return mResolveInfo;
4068            }
4069        }
4070        return null;
4071    }
4072
4073    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4074            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4075        final int N = query.size();
4076        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4077                .get(userId);
4078        // Get the list of persistent preferred activities that handle the intent
4079        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4080        List<PersistentPreferredActivity> pprefs = ppir != null
4081                ? ppir.queryIntent(intent, resolvedType,
4082                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4083                : null;
4084        if (pprefs != null && pprefs.size() > 0) {
4085            final int M = pprefs.size();
4086            for (int i=0; i<M; i++) {
4087                final PersistentPreferredActivity ppa = pprefs.get(i);
4088                if (DEBUG_PREFERRED || debug) {
4089                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4090                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4091                            + "\n  component=" + ppa.mComponent);
4092                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4093                }
4094                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4095                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4096                if (DEBUG_PREFERRED || debug) {
4097                    Slog.v(TAG, "Found persistent preferred activity:");
4098                    if (ai != null) {
4099                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4100                    } else {
4101                        Slog.v(TAG, "  null");
4102                    }
4103                }
4104                if (ai == null) {
4105                    // This previously registered persistent preferred activity
4106                    // component is no longer known. Ignore it and do NOT remove it.
4107                    continue;
4108                }
4109                for (int j=0; j<N; j++) {
4110                    final ResolveInfo ri = query.get(j);
4111                    if (!ri.activityInfo.applicationInfo.packageName
4112                            .equals(ai.applicationInfo.packageName)) {
4113                        continue;
4114                    }
4115                    if (!ri.activityInfo.name.equals(ai.name)) {
4116                        continue;
4117                    }
4118                    //  Found a persistent preference that can handle the intent.
4119                    if (DEBUG_PREFERRED || debug) {
4120                        Slog.v(TAG, "Returning persistent preferred activity: " +
4121                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4122                    }
4123                    return ri;
4124                }
4125            }
4126        }
4127        return null;
4128    }
4129
4130    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4131            List<ResolveInfo> query, int priority, boolean always,
4132            boolean removeMatches, boolean debug, int userId) {
4133        if (!sUserManager.exists(userId)) return null;
4134        // writer
4135        synchronized (mPackages) {
4136            if (intent.getSelector() != null) {
4137                intent = intent.getSelector();
4138            }
4139            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4140
4141            // Try to find a matching persistent preferred activity.
4142            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4143                    debug, userId);
4144
4145            // If a persistent preferred activity matched, use it.
4146            if (pri != null) {
4147                return pri;
4148            }
4149
4150            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4151            // Get the list of preferred activities that handle the intent
4152            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4153            List<PreferredActivity> prefs = pir != null
4154                    ? pir.queryIntent(intent, resolvedType,
4155                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4156                    : null;
4157            if (prefs != null && prefs.size() > 0) {
4158                boolean changed = false;
4159                try {
4160                    // First figure out how good the original match set is.
4161                    // We will only allow preferred activities that came
4162                    // from the same match quality.
4163                    int match = 0;
4164
4165                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4166
4167                    final int N = query.size();
4168                    for (int j=0; j<N; j++) {
4169                        final ResolveInfo ri = query.get(j);
4170                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4171                                + ": 0x" + Integer.toHexString(match));
4172                        if (ri.match > match) {
4173                            match = ri.match;
4174                        }
4175                    }
4176
4177                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4178                            + Integer.toHexString(match));
4179
4180                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4181                    final int M = prefs.size();
4182                    for (int i=0; i<M; i++) {
4183                        final PreferredActivity pa = prefs.get(i);
4184                        if (DEBUG_PREFERRED || debug) {
4185                            Slog.v(TAG, "Checking PreferredActivity ds="
4186                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4187                                    + "\n  component=" + pa.mPref.mComponent);
4188                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4189                        }
4190                        if (pa.mPref.mMatch != match) {
4191                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4192                                    + Integer.toHexString(pa.mPref.mMatch));
4193                            continue;
4194                        }
4195                        // If it's not an "always" type preferred activity and that's what we're
4196                        // looking for, skip it.
4197                        if (always && !pa.mPref.mAlways) {
4198                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4199                            continue;
4200                        }
4201                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4202                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4203                        if (DEBUG_PREFERRED || debug) {
4204                            Slog.v(TAG, "Found preferred activity:");
4205                            if (ai != null) {
4206                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4207                            } else {
4208                                Slog.v(TAG, "  null");
4209                            }
4210                        }
4211                        if (ai == null) {
4212                            // This previously registered preferred activity
4213                            // component is no longer known.  Most likely an update
4214                            // to the app was installed and in the new version this
4215                            // component no longer exists.  Clean it up by removing
4216                            // it from the preferred activities list, and skip it.
4217                            Slog.w(TAG, "Removing dangling preferred activity: "
4218                                    + pa.mPref.mComponent);
4219                            pir.removeFilter(pa);
4220                            changed = true;
4221                            continue;
4222                        }
4223                        for (int j=0; j<N; j++) {
4224                            final ResolveInfo ri = query.get(j);
4225                            if (!ri.activityInfo.applicationInfo.packageName
4226                                    .equals(ai.applicationInfo.packageName)) {
4227                                continue;
4228                            }
4229                            if (!ri.activityInfo.name.equals(ai.name)) {
4230                                continue;
4231                            }
4232
4233                            if (removeMatches) {
4234                                pir.removeFilter(pa);
4235                                changed = true;
4236                                if (DEBUG_PREFERRED) {
4237                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4238                                }
4239                                break;
4240                            }
4241
4242                            // Okay we found a previously set preferred or last chosen app.
4243                            // If the result set is different from when this
4244                            // was created, we need to clear it and re-ask the
4245                            // user their preference, if we're looking for an "always" type entry.
4246                            if (always && !pa.mPref.sameSet(query)) {
4247                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4248                                        + intent + " type " + resolvedType);
4249                                if (DEBUG_PREFERRED) {
4250                                    Slog.v(TAG, "Removing preferred activity since set changed "
4251                                            + pa.mPref.mComponent);
4252                                }
4253                                pir.removeFilter(pa);
4254                                // Re-add the filter as a "last chosen" entry (!always)
4255                                PreferredActivity lastChosen = new PreferredActivity(
4256                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4257                                pir.addFilter(lastChosen);
4258                                changed = true;
4259                                return null;
4260                            }
4261
4262                            // Yay! Either the set matched or we're looking for the last chosen
4263                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4264                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4265                            return ri;
4266                        }
4267                    }
4268                } finally {
4269                    if (changed) {
4270                        if (DEBUG_PREFERRED) {
4271                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4272                        }
4273                        scheduleWritePackageRestrictionsLocked(userId);
4274                    }
4275                }
4276            }
4277        }
4278        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4279        return null;
4280    }
4281
4282    /*
4283     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4284     */
4285    @Override
4286    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4287            int targetUserId) {
4288        mContext.enforceCallingOrSelfPermission(
4289                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4290        List<CrossProfileIntentFilter> matches =
4291                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4292        if (matches != null) {
4293            int size = matches.size();
4294            for (int i = 0; i < size; i++) {
4295                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4296            }
4297        }
4298        if (hasWebURI(intent)) {
4299            // cross-profile app linking works only towards the parent.
4300            final UserInfo parent = getProfileParent(sourceUserId);
4301            synchronized(mPackages) {
4302                return getCrossProfileDomainPreferredLpr(intent, resolvedType, 0, sourceUserId,
4303                        parent.id) != null;
4304            }
4305        }
4306        return false;
4307    }
4308
4309    private UserInfo getProfileParent(int userId) {
4310        final long identity = Binder.clearCallingIdentity();
4311        try {
4312            return sUserManager.getProfileParent(userId);
4313        } finally {
4314            Binder.restoreCallingIdentity(identity);
4315        }
4316    }
4317
4318    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4319            String resolvedType, int userId) {
4320        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4321        if (resolver != null) {
4322            return resolver.queryIntent(intent, resolvedType, false, userId);
4323        }
4324        return null;
4325    }
4326
4327    @Override
4328    public List<ResolveInfo> queryIntentActivities(Intent intent,
4329            String resolvedType, int flags, int userId) {
4330        if (!sUserManager.exists(userId)) return Collections.emptyList();
4331        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4332        ComponentName comp = intent.getComponent();
4333        if (comp == null) {
4334            if (intent.getSelector() != null) {
4335                intent = intent.getSelector();
4336                comp = intent.getComponent();
4337            }
4338        }
4339
4340        if (comp != null) {
4341            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4342            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4343            if (ai != null) {
4344                final ResolveInfo ri = new ResolveInfo();
4345                ri.activityInfo = ai;
4346                list.add(ri);
4347            }
4348            return list;
4349        }
4350
4351        // reader
4352        synchronized (mPackages) {
4353            final String pkgName = intent.getPackage();
4354            if (pkgName == null) {
4355                List<CrossProfileIntentFilter> matchingFilters =
4356                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4357                // Check for results that need to skip the current profile.
4358                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4359                        resolvedType, flags, userId);
4360                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4361                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4362                    result.add(xpResolveInfo);
4363                    return filterIfNotPrimaryUser(result, userId);
4364                }
4365
4366                // Check for results in the current profile.
4367                List<ResolveInfo> result = mActivities.queryIntent(
4368                        intent, resolvedType, flags, userId);
4369
4370                // Check for cross profile results.
4371                xpResolveInfo = queryCrossProfileIntents(
4372                        matchingFilters, intent, resolvedType, flags, userId);
4373                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4374                    result.add(xpResolveInfo);
4375                    Collections.sort(result, mResolvePrioritySorter);
4376                }
4377                result = filterIfNotPrimaryUser(result, userId);
4378                if (hasWebURI(intent)) {
4379                    CrossProfileDomainInfo xpDomainInfo = null;
4380                    final UserInfo parent = getProfileParent(userId);
4381                    if (parent != null) {
4382                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4383                                flags, userId, parent.id);
4384                    }
4385                    if (xpDomainInfo != null) {
4386                        if (xpResolveInfo != null) {
4387                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4388                            // in the result.
4389                            result.remove(xpResolveInfo);
4390                        }
4391                        if (result.size() == 0) {
4392                            result.add(xpDomainInfo.resolveInfo);
4393                            return result;
4394                        }
4395                    } else if (result.size() <= 1) {
4396                        return result;
4397                    }
4398                    result = filterCandidatesWithDomainPreferredActivitiesLPr(flags, result,
4399                            xpDomainInfo);
4400                    Collections.sort(result, mResolvePrioritySorter);
4401                }
4402                return result;
4403            }
4404            final PackageParser.Package pkg = mPackages.get(pkgName);
4405            if (pkg != null) {
4406                return filterIfNotPrimaryUser(
4407                        mActivities.queryIntentForPackage(
4408                                intent, resolvedType, flags, pkg.activities, userId),
4409                        userId);
4410            }
4411            return new ArrayList<ResolveInfo>();
4412        }
4413    }
4414
4415    private static class CrossProfileDomainInfo {
4416        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4417        ResolveInfo resolveInfo;
4418        /* Best domain verification status of the activities found in the other profile */
4419        int bestDomainVerificationStatus;
4420    }
4421
4422    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4423            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4424        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
4425                sourceUserId)) {
4426            return null;
4427        }
4428        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4429                resolvedType, flags, parentUserId);
4430
4431        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4432            return null;
4433        }
4434        CrossProfileDomainInfo result = null;
4435        int size = resultTargetUser.size();
4436        for (int i = 0; i < size; i++) {
4437            ResolveInfo riTargetUser = resultTargetUser.get(i);
4438            // Intent filter verification is only for filters that specify a host. So don't return
4439            // those that handle all web uris.
4440            if (riTargetUser.handleAllWebDataURI) {
4441                continue;
4442            }
4443            String packageName = riTargetUser.activityInfo.packageName;
4444            PackageSetting ps = mSettings.mPackages.get(packageName);
4445            if (ps == null) {
4446                continue;
4447            }
4448            int status = getDomainVerificationStatusLPr(ps, parentUserId);
4449            if (result == null) {
4450                result = new CrossProfileDomainInfo();
4451                result.resolveInfo =
4452                        createForwardingResolveInfo(null, sourceUserId, parentUserId);
4453                result.bestDomainVerificationStatus = status;
4454            } else {
4455                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
4456                        result.bestDomainVerificationStatus);
4457            }
4458        }
4459        return result;
4460    }
4461
4462    /**
4463     * Verification statuses are ordered from the worse to the best, except for
4464     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
4465     */
4466    private int bestDomainVerificationStatus(int status1, int status2) {
4467        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4468            return status2;
4469        }
4470        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4471            return status1;
4472        }
4473        return (int) MathUtils.max(status1, status2);
4474    }
4475
4476    private boolean isUserEnabled(int userId) {
4477        long callingId = Binder.clearCallingIdentity();
4478        try {
4479            UserInfo userInfo = sUserManager.getUserInfo(userId);
4480            return userInfo != null && userInfo.isEnabled();
4481        } finally {
4482            Binder.restoreCallingIdentity(callingId);
4483        }
4484    }
4485
4486    /**
4487     * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
4488     *
4489     * @return filtered list
4490     */
4491    private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
4492        if (userId == UserHandle.USER_OWNER) {
4493            return resolveInfos;
4494        }
4495        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4496            ResolveInfo info = resolveInfos.get(i);
4497            if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
4498                resolveInfos.remove(i);
4499            }
4500        }
4501        return resolveInfos;
4502    }
4503
4504    private static boolean hasWebURI(Intent intent) {
4505        if (intent.getData() == null) {
4506            return false;
4507        }
4508        final String scheme = intent.getScheme();
4509        if (TextUtils.isEmpty(scheme)) {
4510            return false;
4511        }
4512        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4513    }
4514
4515    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(
4516            int flags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo) {
4517        if (DEBUG_PREFERRED) {
4518            Slog.v("TAG", "Filtering results with prefered activities. Candidates count: " +
4519                    candidates.size());
4520        }
4521
4522        final int userId = UserHandle.getCallingUserId();
4523        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4524        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
4525        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4526        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4527        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4528
4529        synchronized (mPackages) {
4530            final int count = candidates.size();
4531            // First, try to use the domain preferred app. Partition the candidates into four lists:
4532            // one for the final results, one for the "do not use ever", one for "undefined status"
4533            // and finally one for "Browser App type".
4534            for (int n=0; n<count; n++) {
4535                ResolveInfo info = candidates.get(n);
4536                String packageName = info.activityInfo.packageName;
4537                PackageSetting ps = mSettings.mPackages.get(packageName);
4538                if (ps != null) {
4539                    // Add to the special match all list (Browser use case)
4540                    if (info.handleAllWebDataURI) {
4541                        matchAllList.add(info);
4542                        continue;
4543                    }
4544                    // Try to get the status from User settings first
4545                    int status = getDomainVerificationStatusLPr(ps, userId);
4546                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4547                        alwaysList.add(info);
4548                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4549                        neverList.add(info);
4550                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
4551                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
4552                        undefinedList.add(info);
4553                    }
4554                }
4555            }
4556            // First try to add the "always" resolution for the current user if there is any
4557            if (alwaysList.size() > 0) {
4558                result.addAll(alwaysList);
4559            // if there is an "always" for the parent user, add it.
4560            } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus
4561                    == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4562                result.add(xpDomainInfo.resolveInfo);
4563            } else {
4564                // Add all undefined Apps as we want them to appear in the Disambiguation dialog.
4565                result.addAll(undefinedList);
4566                if (xpDomainInfo != null && (
4567                        xpDomainInfo.bestDomainVerificationStatus
4568                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
4569                        || xpDomainInfo.bestDomainVerificationStatus
4570                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) {
4571                    result.add(xpDomainInfo.resolveInfo);
4572                }
4573                // Also add Browsers (all of them or only the default one)
4574                if ((flags & MATCH_ALL) != 0) {
4575                    result.addAll(matchAllList);
4576                } else {
4577                    // Try to add the Default Browser if we can
4578                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(
4579                            UserHandle.myUserId());
4580                    if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
4581                        boolean defaultBrowserFound = false;
4582                        final int browserCount = matchAllList.size();
4583                        for (int n=0; n<browserCount; n++) {
4584                            ResolveInfo browser = matchAllList.get(n);
4585                            if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) {
4586                                result.add(browser);
4587                                defaultBrowserFound = true;
4588                                break;
4589                            }
4590                        }
4591                        if (!defaultBrowserFound) {
4592                            result.addAll(matchAllList);
4593                        }
4594                    } else {
4595                        result.addAll(matchAllList);
4596                    }
4597                }
4598
4599                // If there is nothing selected, add all candidates and remove the ones that the User
4600                // has explicitely put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
4601                if (result.size() == 0) {
4602                    result.addAll(candidates);
4603                    result.removeAll(neverList);
4604                }
4605            }
4606        }
4607        if (DEBUG_PREFERRED) {
4608            Slog.v("TAG", "Filtered results with prefered activities. New candidates count: " +
4609                    result.size());
4610        }
4611        return result;
4612    }
4613
4614    private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4615        int status = ps.getDomainVerificationStatusForUser(userId);
4616        // if none available, get the master status
4617        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4618            if (ps.getIntentFilterVerificationInfo() != null) {
4619                status = ps.getIntentFilterVerificationInfo().getStatus();
4620            }
4621        }
4622        return status;
4623    }
4624
4625    private ResolveInfo querySkipCurrentProfileIntents(
4626            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4627            int flags, int sourceUserId) {
4628        if (matchingFilters != null) {
4629            int size = matchingFilters.size();
4630            for (int i = 0; i < size; i ++) {
4631                CrossProfileIntentFilter filter = matchingFilters.get(i);
4632                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4633                    // Checking if there are activities in the target user that can handle the
4634                    // intent.
4635                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4636                            flags, sourceUserId);
4637                    if (resolveInfo != null) {
4638                        return resolveInfo;
4639                    }
4640                }
4641            }
4642        }
4643        return null;
4644    }
4645
4646    // Return matching ResolveInfo if any for skip current profile intent filters.
4647    private ResolveInfo queryCrossProfileIntents(
4648            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4649            int flags, int sourceUserId) {
4650        if (matchingFilters != null) {
4651            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4652            // match the same intent. For performance reasons, it is better not to
4653            // run queryIntent twice for the same userId
4654            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4655            int size = matchingFilters.size();
4656            for (int i = 0; i < size; i++) {
4657                CrossProfileIntentFilter filter = matchingFilters.get(i);
4658                int targetUserId = filter.getTargetUserId();
4659                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4660                        && !alreadyTriedUserIds.get(targetUserId)) {
4661                    // Checking if there are activities in the target user that can handle the
4662                    // intent.
4663                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4664                            flags, sourceUserId);
4665                    if (resolveInfo != null) return resolveInfo;
4666                    alreadyTriedUserIds.put(targetUserId, true);
4667                }
4668            }
4669        }
4670        return null;
4671    }
4672
4673    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
4674            String resolvedType, int flags, int sourceUserId) {
4675        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4676                resolvedType, flags, filter.getTargetUserId());
4677        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
4678            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
4679        }
4680        return null;
4681    }
4682
4683    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
4684            int sourceUserId, int targetUserId) {
4685        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4686        String className;
4687        if (targetUserId == UserHandle.USER_OWNER) {
4688            className = FORWARD_INTENT_TO_USER_OWNER;
4689        } else {
4690            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4691        }
4692        ComponentName forwardingActivityComponentName = new ComponentName(
4693                mAndroidApplication.packageName, className);
4694        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
4695                sourceUserId);
4696        if (targetUserId == UserHandle.USER_OWNER) {
4697            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
4698            forwardingResolveInfo.noResourceId = true;
4699        }
4700        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
4701        forwardingResolveInfo.priority = 0;
4702        forwardingResolveInfo.preferredOrder = 0;
4703        forwardingResolveInfo.match = 0;
4704        forwardingResolveInfo.isDefault = true;
4705        forwardingResolveInfo.filter = filter;
4706        forwardingResolveInfo.targetUserId = targetUserId;
4707        return forwardingResolveInfo;
4708    }
4709
4710    @Override
4711    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
4712            Intent[] specifics, String[] specificTypes, Intent intent,
4713            String resolvedType, int flags, int userId) {
4714        if (!sUserManager.exists(userId)) return Collections.emptyList();
4715        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
4716                false, "query intent activity options");
4717        final String resultsAction = intent.getAction();
4718
4719        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
4720                | PackageManager.GET_RESOLVED_FILTER, userId);
4721
4722        if (DEBUG_INTENT_MATCHING) {
4723            Log.v(TAG, "Query " + intent + ": " + results);
4724        }
4725
4726        int specificsPos = 0;
4727        int N;
4728
4729        // todo: note that the algorithm used here is O(N^2).  This
4730        // isn't a problem in our current environment, but if we start running
4731        // into situations where we have more than 5 or 10 matches then this
4732        // should probably be changed to something smarter...
4733
4734        // First we go through and resolve each of the specific items
4735        // that were supplied, taking care of removing any corresponding
4736        // duplicate items in the generic resolve list.
4737        if (specifics != null) {
4738            for (int i=0; i<specifics.length; i++) {
4739                final Intent sintent = specifics[i];
4740                if (sintent == null) {
4741                    continue;
4742                }
4743
4744                if (DEBUG_INTENT_MATCHING) {
4745                    Log.v(TAG, "Specific #" + i + ": " + sintent);
4746                }
4747
4748                String action = sintent.getAction();
4749                if (resultsAction != null && resultsAction.equals(action)) {
4750                    // If this action was explicitly requested, then don't
4751                    // remove things that have it.
4752                    action = null;
4753                }
4754
4755                ResolveInfo ri = null;
4756                ActivityInfo ai = null;
4757
4758                ComponentName comp = sintent.getComponent();
4759                if (comp == null) {
4760                    ri = resolveIntent(
4761                        sintent,
4762                        specificTypes != null ? specificTypes[i] : null,
4763                            flags, userId);
4764                    if (ri == null) {
4765                        continue;
4766                    }
4767                    if (ri == mResolveInfo) {
4768                        // ACK!  Must do something better with this.
4769                    }
4770                    ai = ri.activityInfo;
4771                    comp = new ComponentName(ai.applicationInfo.packageName,
4772                            ai.name);
4773                } else {
4774                    ai = getActivityInfo(comp, flags, userId);
4775                    if (ai == null) {
4776                        continue;
4777                    }
4778                }
4779
4780                // Look for any generic query activities that are duplicates
4781                // of this specific one, and remove them from the results.
4782                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
4783                N = results.size();
4784                int j;
4785                for (j=specificsPos; j<N; j++) {
4786                    ResolveInfo sri = results.get(j);
4787                    if ((sri.activityInfo.name.equals(comp.getClassName())
4788                            && sri.activityInfo.applicationInfo.packageName.equals(
4789                                    comp.getPackageName()))
4790                        || (action != null && sri.filter.matchAction(action))) {
4791                        results.remove(j);
4792                        if (DEBUG_INTENT_MATCHING) Log.v(
4793                            TAG, "Removing duplicate item from " + j
4794                            + " due to specific " + specificsPos);
4795                        if (ri == null) {
4796                            ri = sri;
4797                        }
4798                        j--;
4799                        N--;
4800                    }
4801                }
4802
4803                // Add this specific item to its proper place.
4804                if (ri == null) {
4805                    ri = new ResolveInfo();
4806                    ri.activityInfo = ai;
4807                }
4808                results.add(specificsPos, ri);
4809                ri.specificIndex = i;
4810                specificsPos++;
4811            }
4812        }
4813
4814        // Now we go through the remaining generic results and remove any
4815        // duplicate actions that are found here.
4816        N = results.size();
4817        for (int i=specificsPos; i<N-1; i++) {
4818            final ResolveInfo rii = results.get(i);
4819            if (rii.filter == null) {
4820                continue;
4821            }
4822
4823            // Iterate over all of the actions of this result's intent
4824            // filter...  typically this should be just one.
4825            final Iterator<String> it = rii.filter.actionsIterator();
4826            if (it == null) {
4827                continue;
4828            }
4829            while (it.hasNext()) {
4830                final String action = it.next();
4831                if (resultsAction != null && resultsAction.equals(action)) {
4832                    // If this action was explicitly requested, then don't
4833                    // remove things that have it.
4834                    continue;
4835                }
4836                for (int j=i+1; j<N; j++) {
4837                    final ResolveInfo rij = results.get(j);
4838                    if (rij.filter != null && rij.filter.hasAction(action)) {
4839                        results.remove(j);
4840                        if (DEBUG_INTENT_MATCHING) Log.v(
4841                            TAG, "Removing duplicate item from " + j
4842                            + " due to action " + action + " at " + i);
4843                        j--;
4844                        N--;
4845                    }
4846                }
4847            }
4848
4849            // If the caller didn't request filter information, drop it now
4850            // so we don't have to marshall/unmarshall it.
4851            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4852                rii.filter = null;
4853            }
4854        }
4855
4856        // Filter out the caller activity if so requested.
4857        if (caller != null) {
4858            N = results.size();
4859            for (int i=0; i<N; i++) {
4860                ActivityInfo ainfo = results.get(i).activityInfo;
4861                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
4862                        && caller.getClassName().equals(ainfo.name)) {
4863                    results.remove(i);
4864                    break;
4865                }
4866            }
4867        }
4868
4869        // If the caller didn't request filter information,
4870        // drop them now so we don't have to
4871        // marshall/unmarshall it.
4872        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4873            N = results.size();
4874            for (int i=0; i<N; i++) {
4875                results.get(i).filter = null;
4876            }
4877        }
4878
4879        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
4880        return results;
4881    }
4882
4883    @Override
4884    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
4885            int userId) {
4886        if (!sUserManager.exists(userId)) return Collections.emptyList();
4887        ComponentName comp = intent.getComponent();
4888        if (comp == null) {
4889            if (intent.getSelector() != null) {
4890                intent = intent.getSelector();
4891                comp = intent.getComponent();
4892            }
4893        }
4894        if (comp != null) {
4895            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4896            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
4897            if (ai != null) {
4898                ResolveInfo ri = new ResolveInfo();
4899                ri.activityInfo = ai;
4900                list.add(ri);
4901            }
4902            return list;
4903        }
4904
4905        // reader
4906        synchronized (mPackages) {
4907            String pkgName = intent.getPackage();
4908            if (pkgName == null) {
4909                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
4910            }
4911            final PackageParser.Package pkg = mPackages.get(pkgName);
4912            if (pkg != null) {
4913                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
4914                        userId);
4915            }
4916            return null;
4917        }
4918    }
4919
4920    @Override
4921    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
4922        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
4923        if (!sUserManager.exists(userId)) return null;
4924        if (query != null) {
4925            if (query.size() >= 1) {
4926                // If there is more than one service with the same priority,
4927                // just arbitrarily pick the first one.
4928                return query.get(0);
4929            }
4930        }
4931        return null;
4932    }
4933
4934    @Override
4935    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
4936            int userId) {
4937        if (!sUserManager.exists(userId)) return Collections.emptyList();
4938        ComponentName comp = intent.getComponent();
4939        if (comp == null) {
4940            if (intent.getSelector() != null) {
4941                intent = intent.getSelector();
4942                comp = intent.getComponent();
4943            }
4944        }
4945        if (comp != null) {
4946            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4947            final ServiceInfo si = getServiceInfo(comp, flags, userId);
4948            if (si != null) {
4949                final ResolveInfo ri = new ResolveInfo();
4950                ri.serviceInfo = si;
4951                list.add(ri);
4952            }
4953            return list;
4954        }
4955
4956        // reader
4957        synchronized (mPackages) {
4958            String pkgName = intent.getPackage();
4959            if (pkgName == null) {
4960                return mServices.queryIntent(intent, resolvedType, flags, userId);
4961            }
4962            final PackageParser.Package pkg = mPackages.get(pkgName);
4963            if (pkg != null) {
4964                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
4965                        userId);
4966            }
4967            return null;
4968        }
4969    }
4970
4971    @Override
4972    public List<ResolveInfo> queryIntentContentProviders(
4973            Intent intent, String resolvedType, int flags, int userId) {
4974        if (!sUserManager.exists(userId)) return Collections.emptyList();
4975        ComponentName comp = intent.getComponent();
4976        if (comp == null) {
4977            if (intent.getSelector() != null) {
4978                intent = intent.getSelector();
4979                comp = intent.getComponent();
4980            }
4981        }
4982        if (comp != null) {
4983            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4984            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
4985            if (pi != null) {
4986                final ResolveInfo ri = new ResolveInfo();
4987                ri.providerInfo = pi;
4988                list.add(ri);
4989            }
4990            return list;
4991        }
4992
4993        // reader
4994        synchronized (mPackages) {
4995            String pkgName = intent.getPackage();
4996            if (pkgName == null) {
4997                return mProviders.queryIntent(intent, resolvedType, flags, userId);
4998            }
4999            final PackageParser.Package pkg = mPackages.get(pkgName);
5000            if (pkg != null) {
5001                return mProviders.queryIntentForPackage(
5002                        intent, resolvedType, flags, pkg.providers, userId);
5003            }
5004            return null;
5005        }
5006    }
5007
5008    @Override
5009    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5010        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5011
5012        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5013
5014        // writer
5015        synchronized (mPackages) {
5016            ArrayList<PackageInfo> list;
5017            if (listUninstalled) {
5018                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5019                for (PackageSetting ps : mSettings.mPackages.values()) {
5020                    PackageInfo pi;
5021                    if (ps.pkg != null) {
5022                        pi = generatePackageInfo(ps.pkg, flags, userId);
5023                    } else {
5024                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5025                    }
5026                    if (pi != null) {
5027                        list.add(pi);
5028                    }
5029                }
5030            } else {
5031                list = new ArrayList<PackageInfo>(mPackages.size());
5032                for (PackageParser.Package p : mPackages.values()) {
5033                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5034                    if (pi != null) {
5035                        list.add(pi);
5036                    }
5037                }
5038            }
5039
5040            return new ParceledListSlice<PackageInfo>(list);
5041        }
5042    }
5043
5044    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5045            String[] permissions, boolean[] tmp, int flags, int userId) {
5046        int numMatch = 0;
5047        final PermissionsState permissionsState = ps.getPermissionsState();
5048        for (int i=0; i<permissions.length; i++) {
5049            final String permission = permissions[i];
5050            if (permissionsState.hasPermission(permission, userId)) {
5051                tmp[i] = true;
5052                numMatch++;
5053            } else {
5054                tmp[i] = false;
5055            }
5056        }
5057        if (numMatch == 0) {
5058            return;
5059        }
5060        PackageInfo pi;
5061        if (ps.pkg != null) {
5062            pi = generatePackageInfo(ps.pkg, flags, userId);
5063        } else {
5064            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5065        }
5066        // The above might return null in cases of uninstalled apps or install-state
5067        // skew across users/profiles.
5068        if (pi != null) {
5069            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5070                if (numMatch == permissions.length) {
5071                    pi.requestedPermissions = permissions;
5072                } else {
5073                    pi.requestedPermissions = new String[numMatch];
5074                    numMatch = 0;
5075                    for (int i=0; i<permissions.length; i++) {
5076                        if (tmp[i]) {
5077                            pi.requestedPermissions[numMatch] = permissions[i];
5078                            numMatch++;
5079                        }
5080                    }
5081                }
5082            }
5083            list.add(pi);
5084        }
5085    }
5086
5087    @Override
5088    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5089            String[] permissions, int flags, int userId) {
5090        if (!sUserManager.exists(userId)) return null;
5091        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5092
5093        // writer
5094        synchronized (mPackages) {
5095            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5096            boolean[] tmpBools = new boolean[permissions.length];
5097            if (listUninstalled) {
5098                for (PackageSetting ps : mSettings.mPackages.values()) {
5099                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5100                }
5101            } else {
5102                for (PackageParser.Package pkg : mPackages.values()) {
5103                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5104                    if (ps != null) {
5105                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5106                                userId);
5107                    }
5108                }
5109            }
5110
5111            return new ParceledListSlice<PackageInfo>(list);
5112        }
5113    }
5114
5115    @Override
5116    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5117        if (!sUserManager.exists(userId)) return null;
5118        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5119
5120        // writer
5121        synchronized (mPackages) {
5122            ArrayList<ApplicationInfo> list;
5123            if (listUninstalled) {
5124                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5125                for (PackageSetting ps : mSettings.mPackages.values()) {
5126                    ApplicationInfo ai;
5127                    if (ps.pkg != null) {
5128                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5129                                ps.readUserState(userId), userId);
5130                    } else {
5131                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5132                    }
5133                    if (ai != null) {
5134                        list.add(ai);
5135                    }
5136                }
5137            } else {
5138                list = new ArrayList<ApplicationInfo>(mPackages.size());
5139                for (PackageParser.Package p : mPackages.values()) {
5140                    if (p.mExtras != null) {
5141                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5142                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5143                        if (ai != null) {
5144                            list.add(ai);
5145                        }
5146                    }
5147                }
5148            }
5149
5150            return new ParceledListSlice<ApplicationInfo>(list);
5151        }
5152    }
5153
5154    public List<ApplicationInfo> getPersistentApplications(int flags) {
5155        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5156
5157        // reader
5158        synchronized (mPackages) {
5159            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5160            final int userId = UserHandle.getCallingUserId();
5161            while (i.hasNext()) {
5162                final PackageParser.Package p = i.next();
5163                if (p.applicationInfo != null
5164                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5165                        && (!mSafeMode || isSystemApp(p))) {
5166                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5167                    if (ps != null) {
5168                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5169                                ps.readUserState(userId), userId);
5170                        if (ai != null) {
5171                            finalList.add(ai);
5172                        }
5173                    }
5174                }
5175            }
5176        }
5177
5178        return finalList;
5179    }
5180
5181    @Override
5182    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5183        if (!sUserManager.exists(userId)) return null;
5184        // reader
5185        synchronized (mPackages) {
5186            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5187            PackageSetting ps = provider != null
5188                    ? mSettings.mPackages.get(provider.owner.packageName)
5189                    : null;
5190            return ps != null
5191                    && mSettings.isEnabledLPr(provider.info, flags, userId)
5192                    && (!mSafeMode || (provider.info.applicationInfo.flags
5193                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5194                    ? PackageParser.generateProviderInfo(provider, flags,
5195                            ps.readUserState(userId), userId)
5196                    : null;
5197        }
5198    }
5199
5200    /**
5201     * @deprecated
5202     */
5203    @Deprecated
5204    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5205        // reader
5206        synchronized (mPackages) {
5207            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5208                    .entrySet().iterator();
5209            final int userId = UserHandle.getCallingUserId();
5210            while (i.hasNext()) {
5211                Map.Entry<String, PackageParser.Provider> entry = i.next();
5212                PackageParser.Provider p = entry.getValue();
5213                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5214
5215                if (ps != null && p.syncable
5216                        && (!mSafeMode || (p.info.applicationInfo.flags
5217                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5218                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5219                            ps.readUserState(userId), userId);
5220                    if (info != null) {
5221                        outNames.add(entry.getKey());
5222                        outInfo.add(info);
5223                    }
5224                }
5225            }
5226        }
5227    }
5228
5229    @Override
5230    public List<ProviderInfo> queryContentProviders(String processName,
5231            int uid, int flags) {
5232        ArrayList<ProviderInfo> finalList = null;
5233        // reader
5234        synchronized (mPackages) {
5235            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5236            final int userId = processName != null ?
5237                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
5238            while (i.hasNext()) {
5239                final PackageParser.Provider p = i.next();
5240                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5241                if (ps != null && p.info.authority != null
5242                        && (processName == null
5243                                || (p.info.processName.equals(processName)
5244                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5245                        && mSettings.isEnabledLPr(p.info, flags, userId)
5246                        && (!mSafeMode
5247                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5248                    if (finalList == null) {
5249                        finalList = new ArrayList<ProviderInfo>(3);
5250                    }
5251                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5252                            ps.readUserState(userId), userId);
5253                    if (info != null) {
5254                        finalList.add(info);
5255                    }
5256                }
5257            }
5258        }
5259
5260        if (finalList != null) {
5261            Collections.sort(finalList, mProviderInitOrderSorter);
5262        }
5263
5264        return finalList;
5265    }
5266
5267    @Override
5268    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
5269            int flags) {
5270        // reader
5271        synchronized (mPackages) {
5272            final PackageParser.Instrumentation i = mInstrumentation.get(name);
5273            return PackageParser.generateInstrumentationInfo(i, flags);
5274        }
5275    }
5276
5277    @Override
5278    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
5279            int flags) {
5280        ArrayList<InstrumentationInfo> finalList =
5281            new ArrayList<InstrumentationInfo>();
5282
5283        // reader
5284        synchronized (mPackages) {
5285            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
5286            while (i.hasNext()) {
5287                final PackageParser.Instrumentation p = i.next();
5288                if (targetPackage == null
5289                        || targetPackage.equals(p.info.targetPackage)) {
5290                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
5291                            flags);
5292                    if (ii != null) {
5293                        finalList.add(ii);
5294                    }
5295                }
5296            }
5297        }
5298
5299        return finalList;
5300    }
5301
5302    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
5303        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
5304        if (overlays == null) {
5305            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
5306            return;
5307        }
5308        for (PackageParser.Package opkg : overlays.values()) {
5309            // Not much to do if idmap fails: we already logged the error
5310            // and we certainly don't want to abort installation of pkg simply
5311            // because an overlay didn't fit properly. For these reasons,
5312            // ignore the return value of createIdmapForPackagePairLI.
5313            createIdmapForPackagePairLI(pkg, opkg);
5314        }
5315    }
5316
5317    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
5318            PackageParser.Package opkg) {
5319        if (!opkg.mTrustedOverlay) {
5320            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
5321                    opkg.baseCodePath + ": overlay not trusted");
5322            return false;
5323        }
5324        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
5325        if (overlaySet == null) {
5326            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
5327                    opkg.baseCodePath + " but target package has no known overlays");
5328            return false;
5329        }
5330        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
5331        // TODO: generate idmap for split APKs
5332        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
5333            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
5334                    + opkg.baseCodePath);
5335            return false;
5336        }
5337        PackageParser.Package[] overlayArray =
5338            overlaySet.values().toArray(new PackageParser.Package[0]);
5339        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
5340            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
5341                return p1.mOverlayPriority - p2.mOverlayPriority;
5342            }
5343        };
5344        Arrays.sort(overlayArray, cmp);
5345
5346        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5347        int i = 0;
5348        for (PackageParser.Package p : overlayArray) {
5349            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5350        }
5351        return true;
5352    }
5353
5354    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5355        final File[] files = dir.listFiles();
5356        if (ArrayUtils.isEmpty(files)) {
5357            Log.d(TAG, "No files in app dir " + dir);
5358            return;
5359        }
5360
5361        if (DEBUG_PACKAGE_SCANNING) {
5362            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
5363                    + " flags=0x" + Integer.toHexString(parseFlags));
5364        }
5365
5366        for (File file : files) {
5367            final boolean isPackage = (isApkFile(file) || file.isDirectory())
5368                    && !PackageInstallerService.isStageName(file.getName());
5369            if (!isPackage) {
5370                // Ignore entries which are not packages
5371                continue;
5372            }
5373            try {
5374                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
5375                        scanFlags, currentTime, null);
5376            } catch (PackageManagerException e) {
5377                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
5378
5379                // Delete invalid userdata apps
5380                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
5381                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
5382                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
5383                    if (file.isDirectory()) {
5384                        mInstaller.rmPackageDir(file.getAbsolutePath());
5385                    } else {
5386                        file.delete();
5387                    }
5388                }
5389            }
5390        }
5391    }
5392
5393    private static File getSettingsProblemFile() {
5394        File dataDir = Environment.getDataDirectory();
5395        File systemDir = new File(dataDir, "system");
5396        File fname = new File(systemDir, "uiderrors.txt");
5397        return fname;
5398    }
5399
5400    static void reportSettingsProblem(int priority, String msg) {
5401        logCriticalInfo(priority, msg);
5402    }
5403
5404    static void logCriticalInfo(int priority, String msg) {
5405        Slog.println(priority, TAG, msg);
5406        EventLogTags.writePmCriticalInfo(msg);
5407        try {
5408            File fname = getSettingsProblemFile();
5409            FileOutputStream out = new FileOutputStream(fname, true);
5410            PrintWriter pw = new FastPrintWriter(out);
5411            SimpleDateFormat formatter = new SimpleDateFormat();
5412            String dateString = formatter.format(new Date(System.currentTimeMillis()));
5413            pw.println(dateString + ": " + msg);
5414            pw.close();
5415            FileUtils.setPermissions(
5416                    fname.toString(),
5417                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5418                    -1, -1);
5419        } catch (java.io.IOException e) {
5420        }
5421    }
5422
5423    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5424            PackageParser.Package pkg, File srcFile, int parseFlags)
5425            throws PackageManagerException {
5426        if (ps != null
5427                && ps.codePath.equals(srcFile)
5428                && ps.timeStamp == srcFile.lastModified()
5429                && !isCompatSignatureUpdateNeeded(pkg)
5430                && !isRecoverSignatureUpdateNeeded(pkg)) {
5431            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5432            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5433            ArraySet<PublicKey> signingKs;
5434            synchronized (mPackages) {
5435                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
5436            }
5437            if (ps.signatures.mSignatures != null
5438                    && ps.signatures.mSignatures.length != 0
5439                    && signingKs != null) {
5440                // Optimization: reuse the existing cached certificates
5441                // if the package appears to be unchanged.
5442                pkg.mSignatures = ps.signatures.mSignatures;
5443                pkg.mSigningKeys = signingKs;
5444                return;
5445            }
5446
5447            Slog.w(TAG, "PackageSetting for " + ps.name
5448                    + " is missing signatures.  Collecting certs again to recover them.");
5449        } else {
5450            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
5451        }
5452
5453        try {
5454            pp.collectCertificates(pkg, parseFlags);
5455            pp.collectManifestDigest(pkg);
5456        } catch (PackageParserException e) {
5457            throw PackageManagerException.from(e);
5458        }
5459    }
5460
5461    /*
5462     *  Scan a package and return the newly parsed package.
5463     *  Returns null in case of errors and the error code is stored in mLastScanError
5464     */
5465    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
5466            long currentTime, UserHandle user) throws PackageManagerException {
5467        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
5468        parseFlags |= mDefParseFlags;
5469        PackageParser pp = new PackageParser();
5470        pp.setSeparateProcesses(mSeparateProcesses);
5471        pp.setOnlyCoreApps(mOnlyCore);
5472        pp.setDisplayMetrics(mMetrics);
5473
5474        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
5475            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
5476        }
5477
5478        final PackageParser.Package pkg;
5479        try {
5480            pkg = pp.parsePackage(scanFile, parseFlags);
5481        } catch (PackageParserException e) {
5482            throw PackageManagerException.from(e);
5483        }
5484
5485        PackageSetting ps = null;
5486        PackageSetting updatedPkg;
5487        // reader
5488        synchronized (mPackages) {
5489            // Look to see if we already know about this package.
5490            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
5491            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
5492                // This package has been renamed to its original name.  Let's
5493                // use that.
5494                ps = mSettings.peekPackageLPr(oldName);
5495            }
5496            // If there was no original package, see one for the real package name.
5497            if (ps == null) {
5498                ps = mSettings.peekPackageLPr(pkg.packageName);
5499            }
5500            // Check to see if this package could be hiding/updating a system
5501            // package.  Must look for it either under the original or real
5502            // package name depending on our state.
5503            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
5504            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
5505        }
5506        boolean updatedPkgBetter = false;
5507        // First check if this is a system package that may involve an update
5508        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5509            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
5510            // it needs to drop FLAG_PRIVILEGED.
5511            if (locationIsPrivileged(scanFile)) {
5512                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5513            } else {
5514                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5515            }
5516
5517            if (ps != null && !ps.codePath.equals(scanFile)) {
5518                // The path has changed from what was last scanned...  check the
5519                // version of the new path against what we have stored to determine
5520                // what to do.
5521                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
5522                if (pkg.mVersionCode <= ps.versionCode) {
5523                    // The system package has been updated and the code path does not match
5524                    // Ignore entry. Skip it.
5525                    Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5526                            + " ignored: updated version " + ps.versionCode
5527                            + " better than this " + pkg.mVersionCode);
5528                    if (!updatedPkg.codePath.equals(scanFile)) {
5529                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5530                                + ps.name + " changing from " + updatedPkg.codePathString
5531                                + " to " + scanFile);
5532                        updatedPkg.codePath = scanFile;
5533                        updatedPkg.codePathString = scanFile.toString();
5534                        updatedPkg.resourcePath = scanFile;
5535                        updatedPkg.resourcePathString = scanFile.toString();
5536                    }
5537                    updatedPkg.pkg = pkg;
5538                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null);
5539                } else {
5540                    // The current app on the system partition is better than
5541                    // what we have updated to on the data partition; switch
5542                    // back to the system partition version.
5543                    // At this point, its safely assumed that package installation for
5544                    // apps in system partition will go through. If not there won't be a working
5545                    // version of the app
5546                    // writer
5547                    synchronized (mPackages) {
5548                        // Just remove the loaded entries from package lists.
5549                        mPackages.remove(ps.name);
5550                    }
5551
5552                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5553                            + " reverting from " + ps.codePathString
5554                            + ": new version " + pkg.mVersionCode
5555                            + " better than installed " + ps.versionCode);
5556
5557                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5558                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5559                    synchronized (mInstallLock) {
5560                        args.cleanUpResourcesLI();
5561                    }
5562                    synchronized (mPackages) {
5563                        mSettings.enableSystemPackageLPw(ps.name);
5564                    }
5565                    updatedPkgBetter = true;
5566                }
5567            }
5568        }
5569
5570        if (updatedPkg != null) {
5571            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5572            // initially
5573            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5574
5575            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5576            // flag set initially
5577            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5578                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5579            }
5580        }
5581
5582        // Verify certificates against what was last scanned
5583        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5584
5585        /*
5586         * A new system app appeared, but we already had a non-system one of the
5587         * same name installed earlier.
5588         */
5589        boolean shouldHideSystemApp = false;
5590        if (updatedPkg == null && ps != null
5591                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5592            /*
5593             * Check to make sure the signatures match first. If they don't,
5594             * wipe the installed application and its data.
5595             */
5596            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5597                    != PackageManager.SIGNATURE_MATCH) {
5598                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5599                        + " signatures don't match existing userdata copy; removing");
5600                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5601                ps = null;
5602            } else {
5603                /*
5604                 * If the newly-added system app is an older version than the
5605                 * already installed version, hide it. It will be scanned later
5606                 * and re-added like an update.
5607                 */
5608                if (pkg.mVersionCode <= ps.versionCode) {
5609                    shouldHideSystemApp = true;
5610                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5611                            + " but new version " + pkg.mVersionCode + " better than installed "
5612                            + ps.versionCode + "; hiding system");
5613                } else {
5614                    /*
5615                     * The newly found system app is a newer version that the
5616                     * one previously installed. Simply remove the
5617                     * already-installed application and replace it with our own
5618                     * while keeping the application data.
5619                     */
5620                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5621                            + " reverting from " + ps.codePathString + ": new version "
5622                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5623                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5624                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5625                    synchronized (mInstallLock) {
5626                        args.cleanUpResourcesLI();
5627                    }
5628                }
5629            }
5630        }
5631
5632        // The apk is forward locked (not public) if its code and resources
5633        // are kept in different files. (except for app in either system or
5634        // vendor path).
5635        // TODO grab this value from PackageSettings
5636        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5637            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5638                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5639            }
5640        }
5641
5642        // TODO: extend to support forward-locked splits
5643        String resourcePath = null;
5644        String baseResourcePath = null;
5645        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5646            if (ps != null && ps.resourcePathString != null) {
5647                resourcePath = ps.resourcePathString;
5648                baseResourcePath = ps.resourcePathString;
5649            } else {
5650                // Should not happen at all. Just log an error.
5651                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5652            }
5653        } else {
5654            resourcePath = pkg.codePath;
5655            baseResourcePath = pkg.baseCodePath;
5656        }
5657
5658        // Set application objects path explicitly.
5659        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
5660        pkg.applicationInfo.setCodePath(pkg.codePath);
5661        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5662        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5663        pkg.applicationInfo.setResourcePath(resourcePath);
5664        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5665        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5666
5667        // Note that we invoke the following method only if we are about to unpack an application
5668        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5669                | SCAN_UPDATE_SIGNATURE, currentTime, user);
5670
5671        /*
5672         * If the system app should be overridden by a previously installed
5673         * data, hide the system app now and let the /data/app scan pick it up
5674         * again.
5675         */
5676        if (shouldHideSystemApp) {
5677            synchronized (mPackages) {
5678                /*
5679                 * We have to grant systems permissions before we hide, because
5680                 * grantPermissions will assume the package update is trying to
5681                 * expand its permissions.
5682                 */
5683                grantPermissionsLPw(pkg, true, pkg.packageName);
5684                mSettings.disableSystemPackageLPw(pkg.packageName);
5685            }
5686        }
5687
5688        return scannedPkg;
5689    }
5690
5691    private static String fixProcessName(String defProcessName,
5692            String processName, int uid) {
5693        if (processName == null) {
5694            return defProcessName;
5695        }
5696        return processName;
5697    }
5698
5699    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
5700            throws PackageManagerException {
5701        if (pkgSetting.signatures.mSignatures != null) {
5702            // Already existing package. Make sure signatures match
5703            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
5704                    == PackageManager.SIGNATURE_MATCH;
5705            if (!match) {
5706                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
5707                        == PackageManager.SIGNATURE_MATCH;
5708            }
5709            if (!match) {
5710                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
5711                        == PackageManager.SIGNATURE_MATCH;
5712            }
5713            if (!match) {
5714                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5715                        + pkg.packageName + " signatures do not match the "
5716                        + "previously installed version; ignoring!");
5717            }
5718        }
5719
5720        // Check for shared user signatures
5721        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
5722            // Already existing package. Make sure signatures match
5723            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5724                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
5725            if (!match) {
5726                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
5727                        == PackageManager.SIGNATURE_MATCH;
5728            }
5729            if (!match) {
5730                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
5731                        == PackageManager.SIGNATURE_MATCH;
5732            }
5733            if (!match) {
5734                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
5735                        "Package " + pkg.packageName
5736                        + " has no signatures that match those in shared user "
5737                        + pkgSetting.sharedUser.name + "; ignoring!");
5738            }
5739        }
5740    }
5741
5742    /**
5743     * Enforces that only the system UID or root's UID can call a method exposed
5744     * via Binder.
5745     *
5746     * @param message used as message if SecurityException is thrown
5747     * @throws SecurityException if the caller is not system or root
5748     */
5749    private static final void enforceSystemOrRoot(String message) {
5750        final int uid = Binder.getCallingUid();
5751        if (uid != Process.SYSTEM_UID && uid != 0) {
5752            throw new SecurityException(message);
5753        }
5754    }
5755
5756    @Override
5757    public void performBootDexOpt() {
5758        enforceSystemOrRoot("Only the system can request dexopt be performed");
5759
5760        // Before everything else, see whether we need to fstrim.
5761        try {
5762            IMountService ms = PackageHelper.getMountService();
5763            if (ms != null) {
5764                final boolean isUpgrade = isUpgrade();
5765                boolean doTrim = isUpgrade;
5766                if (doTrim) {
5767                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
5768                } else {
5769                    final long interval = android.provider.Settings.Global.getLong(
5770                            mContext.getContentResolver(),
5771                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
5772                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
5773                    if (interval > 0) {
5774                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
5775                        if (timeSinceLast > interval) {
5776                            doTrim = true;
5777                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
5778                                    + "; running immediately");
5779                        }
5780                    }
5781                }
5782                if (doTrim) {
5783                    if (!isFirstBoot()) {
5784                        try {
5785                            ActivityManagerNative.getDefault().showBootMessage(
5786                                    mContext.getResources().getString(
5787                                            R.string.android_upgrading_fstrim), true);
5788                        } catch (RemoteException e) {
5789                        }
5790                    }
5791                    ms.runMaintenance();
5792                }
5793            } else {
5794                Slog.e(TAG, "Mount service unavailable!");
5795            }
5796        } catch (RemoteException e) {
5797            // Can't happen; MountService is local
5798        }
5799
5800        final ArraySet<PackageParser.Package> pkgs;
5801        synchronized (mPackages) {
5802            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
5803        }
5804
5805        if (pkgs != null) {
5806            // Sort apps by importance for dexopt ordering. Important apps are given more priority
5807            // in case the device runs out of space.
5808            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
5809            // Give priority to core apps.
5810            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5811                PackageParser.Package pkg = it.next();
5812                if (pkg.coreApp) {
5813                    if (DEBUG_DEXOPT) {
5814                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
5815                    }
5816                    sortedPkgs.add(pkg);
5817                    it.remove();
5818                }
5819            }
5820            // Give priority to system apps that listen for pre boot complete.
5821            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
5822            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
5823            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5824                PackageParser.Package pkg = it.next();
5825                if (pkgNames.contains(pkg.packageName)) {
5826                    if (DEBUG_DEXOPT) {
5827                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
5828                    }
5829                    sortedPkgs.add(pkg);
5830                    it.remove();
5831                }
5832            }
5833            // Give priority to system apps.
5834            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5835                PackageParser.Package pkg = it.next();
5836                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
5837                    if (DEBUG_DEXOPT) {
5838                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
5839                    }
5840                    sortedPkgs.add(pkg);
5841                    it.remove();
5842                }
5843            }
5844            // Give priority to updated system apps.
5845            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5846                PackageParser.Package pkg = it.next();
5847                if (pkg.isUpdatedSystemApp()) {
5848                    if (DEBUG_DEXOPT) {
5849                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
5850                    }
5851                    sortedPkgs.add(pkg);
5852                    it.remove();
5853                }
5854            }
5855            // Give priority to apps that listen for boot complete.
5856            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
5857            pkgNames = getPackageNamesForIntent(intent);
5858            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5859                PackageParser.Package pkg = it.next();
5860                if (pkgNames.contains(pkg.packageName)) {
5861                    if (DEBUG_DEXOPT) {
5862                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
5863                    }
5864                    sortedPkgs.add(pkg);
5865                    it.remove();
5866                }
5867            }
5868            // Filter out packages that aren't recently used.
5869            filterRecentlyUsedApps(pkgs);
5870            // Add all remaining apps.
5871            for (PackageParser.Package pkg : pkgs) {
5872                if (DEBUG_DEXOPT) {
5873                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
5874                }
5875                sortedPkgs.add(pkg);
5876            }
5877
5878            // If we want to be lazy, filter everything that wasn't recently used.
5879            if (mLazyDexOpt) {
5880                filterRecentlyUsedApps(sortedPkgs);
5881            }
5882
5883            int i = 0;
5884            int total = sortedPkgs.size();
5885            File dataDir = Environment.getDataDirectory();
5886            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
5887            if (lowThreshold == 0) {
5888                throw new IllegalStateException("Invalid low memory threshold");
5889            }
5890            for (PackageParser.Package pkg : sortedPkgs) {
5891                long usableSpace = dataDir.getUsableSpace();
5892                if (usableSpace < lowThreshold) {
5893                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
5894                    break;
5895                }
5896                performBootDexOpt(pkg, ++i, total);
5897            }
5898        }
5899    }
5900
5901    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
5902        // Filter out packages that aren't recently used.
5903        //
5904        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
5905        // should do a full dexopt.
5906        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
5907            int total = pkgs.size();
5908            int skipped = 0;
5909            long now = System.currentTimeMillis();
5910            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
5911                PackageParser.Package pkg = i.next();
5912                long then = pkg.mLastPackageUsageTimeInMills;
5913                if (then + mDexOptLRUThresholdInMills < now) {
5914                    if (DEBUG_DEXOPT) {
5915                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
5916                              ((then == 0) ? "never" : new Date(then)));
5917                    }
5918                    i.remove();
5919                    skipped++;
5920                }
5921            }
5922            if (DEBUG_DEXOPT) {
5923                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
5924            }
5925        }
5926    }
5927
5928    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
5929        List<ResolveInfo> ris = null;
5930        try {
5931            ris = AppGlobals.getPackageManager().queryIntentReceivers(
5932                    intent, null, 0, UserHandle.USER_OWNER);
5933        } catch (RemoteException e) {
5934        }
5935        ArraySet<String> pkgNames = new ArraySet<String>();
5936        if (ris != null) {
5937            for (ResolveInfo ri : ris) {
5938                pkgNames.add(ri.activityInfo.packageName);
5939            }
5940        }
5941        return pkgNames;
5942    }
5943
5944    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
5945        if (DEBUG_DEXOPT) {
5946            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
5947        }
5948        if (!isFirstBoot()) {
5949            try {
5950                ActivityManagerNative.getDefault().showBootMessage(
5951                        mContext.getResources().getString(R.string.android_upgrading_apk,
5952                                curr, total), true);
5953            } catch (RemoteException e) {
5954            }
5955        }
5956        PackageParser.Package p = pkg;
5957        synchronized (mInstallLock) {
5958            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
5959                    false /* force dex */, false /* defer */, true /* include dependencies */);
5960        }
5961    }
5962
5963    @Override
5964    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
5965        return performDexOpt(packageName, instructionSet, false);
5966    }
5967
5968    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
5969        boolean dexopt = mLazyDexOpt || backgroundDexopt;
5970        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
5971        if (!dexopt && !updateUsage) {
5972            // We aren't going to dexopt or update usage, so bail early.
5973            return false;
5974        }
5975        PackageParser.Package p;
5976        final String targetInstructionSet;
5977        synchronized (mPackages) {
5978            p = mPackages.get(packageName);
5979            if (p == null) {
5980                return false;
5981            }
5982            if (updateUsage) {
5983                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
5984            }
5985            mPackageUsage.write(false);
5986            if (!dexopt) {
5987                // We aren't going to dexopt, so bail early.
5988                return false;
5989            }
5990
5991            targetInstructionSet = instructionSet != null ? instructionSet :
5992                    getPrimaryInstructionSet(p.applicationInfo);
5993            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
5994                return false;
5995            }
5996        }
5997
5998        synchronized (mInstallLock) {
5999            final String[] instructionSets = new String[] { targetInstructionSet };
6000            int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6001                    false /* forceDex */, false /* defer */, true /* inclDependencies */);
6002            return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6003        }
6004    }
6005
6006    public ArraySet<String> getPackagesThatNeedDexOpt() {
6007        ArraySet<String> pkgs = null;
6008        synchronized (mPackages) {
6009            for (PackageParser.Package p : mPackages.values()) {
6010                if (DEBUG_DEXOPT) {
6011                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6012                }
6013                if (!p.mDexOptPerformed.isEmpty()) {
6014                    continue;
6015                }
6016                if (pkgs == null) {
6017                    pkgs = new ArraySet<String>();
6018                }
6019                pkgs.add(p.packageName);
6020            }
6021        }
6022        return pkgs;
6023    }
6024
6025    public void shutdown() {
6026        mPackageUsage.write(true);
6027    }
6028
6029    @Override
6030    public void forceDexOpt(String packageName) {
6031        enforceSystemOrRoot("forceDexOpt");
6032
6033        PackageParser.Package pkg;
6034        synchronized (mPackages) {
6035            pkg = mPackages.get(packageName);
6036            if (pkg == null) {
6037                throw new IllegalArgumentException("Missing package: " + packageName);
6038            }
6039        }
6040
6041        synchronized (mInstallLock) {
6042            final String[] instructionSets = new String[] {
6043                    getPrimaryInstructionSet(pkg.applicationInfo) };
6044            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6045                    true /*forceDex*/, false /* defer */, true /* inclDependencies */);
6046            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6047                throw new IllegalStateException("Failed to dexopt: " + res);
6048            }
6049        }
6050    }
6051
6052    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6053        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6054            Slog.w(TAG, "Unable to update from " + oldPkg.name
6055                    + " to " + newPkg.packageName
6056                    + ": old package not in system partition");
6057            return false;
6058        } else if (mPackages.get(oldPkg.name) != null) {
6059            Slog.w(TAG, "Unable to update from " + oldPkg.name
6060                    + " to " + newPkg.packageName
6061                    + ": old package still exists");
6062            return false;
6063        }
6064        return true;
6065    }
6066
6067    private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
6068        int[] users = sUserManager.getUserIds();
6069        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
6070        if (res < 0) {
6071            return res;
6072        }
6073        for (int user : users) {
6074            if (user != 0) {
6075                res = mInstaller.createUserData(volumeUuid, packageName,
6076                        UserHandle.getUid(user, uid), user, seinfo);
6077                if (res < 0) {
6078                    return res;
6079                }
6080            }
6081        }
6082        return res;
6083    }
6084
6085    private int removeDataDirsLI(String volumeUuid, String packageName) {
6086        int[] users = sUserManager.getUserIds();
6087        int res = 0;
6088        for (int user : users) {
6089            int resInner = mInstaller.remove(volumeUuid, packageName, user);
6090            if (resInner < 0) {
6091                res = resInner;
6092            }
6093        }
6094
6095        return res;
6096    }
6097
6098    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6099        int[] users = sUserManager.getUserIds();
6100        int res = 0;
6101        for (int user : users) {
6102            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
6103            if (resInner < 0) {
6104                res = resInner;
6105            }
6106        }
6107        return res;
6108    }
6109
6110    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6111            PackageParser.Package changingLib) {
6112        if (file.path != null) {
6113            usesLibraryFiles.add(file.path);
6114            return;
6115        }
6116        PackageParser.Package p = mPackages.get(file.apk);
6117        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6118            // If we are doing this while in the middle of updating a library apk,
6119            // then we need to make sure to use that new apk for determining the
6120            // dependencies here.  (We haven't yet finished committing the new apk
6121            // to the package manager state.)
6122            if (p == null || p.packageName.equals(changingLib.packageName)) {
6123                p = changingLib;
6124            }
6125        }
6126        if (p != null) {
6127            usesLibraryFiles.addAll(p.getAllCodePaths());
6128        }
6129    }
6130
6131    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6132            PackageParser.Package changingLib) throws PackageManagerException {
6133        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6134            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6135            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6136            for (int i=0; i<N; i++) {
6137                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6138                if (file == null) {
6139                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6140                            "Package " + pkg.packageName + " requires unavailable shared library "
6141                            + pkg.usesLibraries.get(i) + "; failing!");
6142                }
6143                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6144            }
6145            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6146            for (int i=0; i<N; i++) {
6147                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6148                if (file == null) {
6149                    Slog.w(TAG, "Package " + pkg.packageName
6150                            + " desires unavailable shared library "
6151                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6152                } else {
6153                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6154                }
6155            }
6156            N = usesLibraryFiles.size();
6157            if (N > 0) {
6158                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6159            } else {
6160                pkg.usesLibraryFiles = null;
6161            }
6162        }
6163    }
6164
6165    private static boolean hasString(List<String> list, List<String> which) {
6166        if (list == null) {
6167            return false;
6168        }
6169        for (int i=list.size()-1; i>=0; i--) {
6170            for (int j=which.size()-1; j>=0; j--) {
6171                if (which.get(j).equals(list.get(i))) {
6172                    return true;
6173                }
6174            }
6175        }
6176        return false;
6177    }
6178
6179    private void updateAllSharedLibrariesLPw() {
6180        for (PackageParser.Package pkg : mPackages.values()) {
6181            try {
6182                updateSharedLibrariesLPw(pkg, null);
6183            } catch (PackageManagerException e) {
6184                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6185            }
6186        }
6187    }
6188
6189    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6190            PackageParser.Package changingPkg) {
6191        ArrayList<PackageParser.Package> res = null;
6192        for (PackageParser.Package pkg : mPackages.values()) {
6193            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6194                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6195                if (res == null) {
6196                    res = new ArrayList<PackageParser.Package>();
6197                }
6198                res.add(pkg);
6199                try {
6200                    updateSharedLibrariesLPw(pkg, changingPkg);
6201                } catch (PackageManagerException e) {
6202                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6203                }
6204            }
6205        }
6206        return res;
6207    }
6208
6209    /**
6210     * Derive the value of the {@code cpuAbiOverride} based on the provided
6211     * value and an optional stored value from the package settings.
6212     */
6213    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6214        String cpuAbiOverride = null;
6215
6216        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6217            cpuAbiOverride = null;
6218        } else if (abiOverride != null) {
6219            cpuAbiOverride = abiOverride;
6220        } else if (settings != null) {
6221            cpuAbiOverride = settings.cpuAbiOverrideString;
6222        }
6223
6224        return cpuAbiOverride;
6225    }
6226
6227    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6228            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6229        boolean success = false;
6230        try {
6231            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6232                    currentTime, user);
6233            success = true;
6234            return res;
6235        } finally {
6236            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6237                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6238            }
6239        }
6240    }
6241
6242    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6243            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6244        final File scanFile = new File(pkg.codePath);
6245        if (pkg.applicationInfo.getCodePath() == null ||
6246                pkg.applicationInfo.getResourcePath() == null) {
6247            // Bail out. The resource and code paths haven't been set.
6248            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6249                    "Code and resource paths haven't been set correctly");
6250        }
6251
6252        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6253            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6254        } else {
6255            // Only allow system apps to be flagged as core apps.
6256            pkg.coreApp = false;
6257        }
6258
6259        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6260            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6261        }
6262
6263        if (mCustomResolverComponentName != null &&
6264                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6265            setUpCustomResolverActivity(pkg);
6266        }
6267
6268        if (pkg.packageName.equals("android")) {
6269            synchronized (mPackages) {
6270                if (mAndroidApplication != null) {
6271                    Slog.w(TAG, "*************************************************");
6272                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6273                    Slog.w(TAG, " file=" + scanFile);
6274                    Slog.w(TAG, "*************************************************");
6275                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6276                            "Core android package being redefined.  Skipping.");
6277                }
6278
6279                // Set up information for our fall-back user intent resolution activity.
6280                mPlatformPackage = pkg;
6281                pkg.mVersionCode = mSdkVersion;
6282                mAndroidApplication = pkg.applicationInfo;
6283
6284                if (!mResolverReplaced) {
6285                    mResolveActivity.applicationInfo = mAndroidApplication;
6286                    mResolveActivity.name = ResolverActivity.class.getName();
6287                    mResolveActivity.packageName = mAndroidApplication.packageName;
6288                    mResolveActivity.processName = "system:ui";
6289                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6290                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6291                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6292                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6293                    mResolveActivity.exported = true;
6294                    mResolveActivity.enabled = true;
6295                    mResolveInfo.activityInfo = mResolveActivity;
6296                    mResolveInfo.priority = 0;
6297                    mResolveInfo.preferredOrder = 0;
6298                    mResolveInfo.match = 0;
6299                    mResolveComponentName = new ComponentName(
6300                            mAndroidApplication.packageName, mResolveActivity.name);
6301                }
6302            }
6303        }
6304
6305        if (DEBUG_PACKAGE_SCANNING) {
6306            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6307                Log.d(TAG, "Scanning package " + pkg.packageName);
6308        }
6309
6310        if (mPackages.containsKey(pkg.packageName)
6311                || mSharedLibraries.containsKey(pkg.packageName)) {
6312            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6313                    "Application package " + pkg.packageName
6314                    + " already installed.  Skipping duplicate.");
6315        }
6316
6317        // If we're only installing presumed-existing packages, require that the
6318        // scanned APK is both already known and at the path previously established
6319        // for it.  Previously unknown packages we pick up normally, but if we have an
6320        // a priori expectation about this package's install presence, enforce it.
6321        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6322            PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6323            if (known != null) {
6324                if (DEBUG_PACKAGE_SCANNING) {
6325                    Log.d(TAG, "Examining " + pkg.codePath
6326                            + " and requiring known paths " + known.codePathString
6327                            + " & " + known.resourcePathString);
6328                }
6329                if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6330                        || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6331                    throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6332                            "Application package " + pkg.packageName
6333                            + " found at " + pkg.applicationInfo.getCodePath()
6334                            + " but expected at " + known.codePathString + "; ignoring.");
6335                }
6336            }
6337        }
6338
6339        // Initialize package source and resource directories
6340        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6341        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6342
6343        SharedUserSetting suid = null;
6344        PackageSetting pkgSetting = null;
6345
6346        if (!isSystemApp(pkg)) {
6347            // Only system apps can use these features.
6348            pkg.mOriginalPackages = null;
6349            pkg.mRealPackage = null;
6350            pkg.mAdoptPermissions = null;
6351        }
6352
6353        // writer
6354        synchronized (mPackages) {
6355            if (pkg.mSharedUserId != null) {
6356                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6357                if (suid == null) {
6358                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6359                            "Creating application package " + pkg.packageName
6360                            + " for shared user failed");
6361                }
6362                if (DEBUG_PACKAGE_SCANNING) {
6363                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6364                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6365                                + "): packages=" + suid.packages);
6366                }
6367            }
6368
6369            // Check if we are renaming from an original package name.
6370            PackageSetting origPackage = null;
6371            String realName = null;
6372            if (pkg.mOriginalPackages != null) {
6373                // This package may need to be renamed to a previously
6374                // installed name.  Let's check on that...
6375                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
6376                if (pkg.mOriginalPackages.contains(renamed)) {
6377                    // This package had originally been installed as the
6378                    // original name, and we have already taken care of
6379                    // transitioning to the new one.  Just update the new
6380                    // one to continue using the old name.
6381                    realName = pkg.mRealPackage;
6382                    if (!pkg.packageName.equals(renamed)) {
6383                        // Callers into this function may have already taken
6384                        // care of renaming the package; only do it here if
6385                        // it is not already done.
6386                        pkg.setPackageName(renamed);
6387                    }
6388
6389                } else {
6390                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
6391                        if ((origPackage = mSettings.peekPackageLPr(
6392                                pkg.mOriginalPackages.get(i))) != null) {
6393                            // We do have the package already installed under its
6394                            // original name...  should we use it?
6395                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
6396                                // New package is not compatible with original.
6397                                origPackage = null;
6398                                continue;
6399                            } else if (origPackage.sharedUser != null) {
6400                                // Make sure uid is compatible between packages.
6401                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6402                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6403                                            + " to " + pkg.packageName + ": old uid "
6404                                            + origPackage.sharedUser.name
6405                                            + " differs from " + pkg.mSharedUserId);
6406                                    origPackage = null;
6407                                    continue;
6408                                }
6409                            } else {
6410                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6411                                        + pkg.packageName + " to old name " + origPackage.name);
6412                            }
6413                            break;
6414                        }
6415                    }
6416                }
6417            }
6418
6419            if (mTransferedPackages.contains(pkg.packageName)) {
6420                Slog.w(TAG, "Package " + pkg.packageName
6421                        + " was transferred to another, but its .apk remains");
6422            }
6423
6424            // Just create the setting, don't add it yet. For already existing packages
6425            // the PkgSetting exists already and doesn't have to be created.
6426            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6427                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6428                    pkg.applicationInfo.primaryCpuAbi,
6429                    pkg.applicationInfo.secondaryCpuAbi,
6430                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6431                    user, false);
6432            if (pkgSetting == null) {
6433                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6434                        "Creating application package " + pkg.packageName + " failed");
6435            }
6436
6437            if (pkgSetting.origPackage != null) {
6438                // If we are first transitioning from an original package,
6439                // fix up the new package's name now.  We need to do this after
6440                // looking up the package under its new name, so getPackageLP
6441                // can take care of fiddling things correctly.
6442                pkg.setPackageName(origPackage.name);
6443
6444                // File a report about this.
6445                String msg = "New package " + pkgSetting.realName
6446                        + " renamed to replace old package " + pkgSetting.name;
6447                reportSettingsProblem(Log.WARN, msg);
6448
6449                // Make a note of it.
6450                mTransferedPackages.add(origPackage.name);
6451
6452                // No longer need to retain this.
6453                pkgSetting.origPackage = null;
6454            }
6455
6456            if (realName != null) {
6457                // Make a note of it.
6458                mTransferedPackages.add(pkg.packageName);
6459            }
6460
6461            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6462                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6463            }
6464
6465            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6466                // Check all shared libraries and map to their actual file path.
6467                // We only do this here for apps not on a system dir, because those
6468                // are the only ones that can fail an install due to this.  We
6469                // will take care of the system apps by updating all of their
6470                // library paths after the scan is done.
6471                updateSharedLibrariesLPw(pkg, null);
6472            }
6473
6474            if (mFoundPolicyFile) {
6475                SELinuxMMAC.assignSeinfoValue(pkg);
6476            }
6477
6478            pkg.applicationInfo.uid = pkgSetting.appId;
6479            pkg.mExtras = pkgSetting;
6480            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
6481                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
6482                    // We just determined the app is signed correctly, so bring
6483                    // over the latest parsed certs.
6484                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6485                } else {
6486                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6487                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6488                                "Package " + pkg.packageName + " upgrade keys do not match the "
6489                                + "previously installed version");
6490                    } else {
6491                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
6492                        String msg = "System package " + pkg.packageName
6493                            + " signature changed; retaining data.";
6494                        reportSettingsProblem(Log.WARN, msg);
6495                    }
6496                }
6497            } else {
6498                try {
6499                    verifySignaturesLP(pkgSetting, pkg);
6500                    // We just determined the app is signed correctly, so bring
6501                    // over the latest parsed certs.
6502                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6503                } catch (PackageManagerException e) {
6504                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6505                        throw e;
6506                    }
6507                    // The signature has changed, but this package is in the system
6508                    // image...  let's recover!
6509                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6510                    // However...  if this package is part of a shared user, but it
6511                    // doesn't match the signature of the shared user, let's fail.
6512                    // What this means is that you can't change the signatures
6513                    // associated with an overall shared user, which doesn't seem all
6514                    // that unreasonable.
6515                    if (pkgSetting.sharedUser != null) {
6516                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6517                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
6518                            throw new PackageManagerException(
6519                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
6520                                            "Signature mismatch for shared user : "
6521                                            + pkgSetting.sharedUser);
6522                        }
6523                    }
6524                    // File a report about this.
6525                    String msg = "System package " + pkg.packageName
6526                        + " signature changed; retaining data.";
6527                    reportSettingsProblem(Log.WARN, msg);
6528                }
6529            }
6530            // Verify that this new package doesn't have any content providers
6531            // that conflict with existing packages.  Only do this if the
6532            // package isn't already installed, since we don't want to break
6533            // things that are installed.
6534            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6535                final int N = pkg.providers.size();
6536                int i;
6537                for (i=0; i<N; i++) {
6538                    PackageParser.Provider p = pkg.providers.get(i);
6539                    if (p.info.authority != null) {
6540                        String names[] = p.info.authority.split(";");
6541                        for (int j = 0; j < names.length; j++) {
6542                            if (mProvidersByAuthority.containsKey(names[j])) {
6543                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6544                                final String otherPackageName =
6545                                        ((other != null && other.getComponentName() != null) ?
6546                                                other.getComponentName().getPackageName() : "?");
6547                                throw new PackageManagerException(
6548                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
6549                                                "Can't install because provider name " + names[j]
6550                                                + " (in package " + pkg.applicationInfo.packageName
6551                                                + ") is already used by " + otherPackageName);
6552                            }
6553                        }
6554                    }
6555                }
6556            }
6557
6558            if (pkg.mAdoptPermissions != null) {
6559                // This package wants to adopt ownership of permissions from
6560                // another package.
6561                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6562                    final String origName = pkg.mAdoptPermissions.get(i);
6563                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
6564                    if (orig != null) {
6565                        if (verifyPackageUpdateLPr(orig, pkg)) {
6566                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
6567                                    + pkg.packageName);
6568                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
6569                        }
6570                    }
6571                }
6572            }
6573        }
6574
6575        final String pkgName = pkg.packageName;
6576
6577        final long scanFileTime = scanFile.lastModified();
6578        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6579        pkg.applicationInfo.processName = fixProcessName(
6580                pkg.applicationInfo.packageName,
6581                pkg.applicationInfo.processName,
6582                pkg.applicationInfo.uid);
6583
6584        File dataPath;
6585        if (mPlatformPackage == pkg) {
6586            // The system package is special.
6587            dataPath = new File(Environment.getDataDirectory(), "system");
6588
6589            pkg.applicationInfo.dataDir = dataPath.getPath();
6590
6591        } else {
6592            // This is a normal package, need to make its data directory.
6593            dataPath = PackageManager.getDataDirForUser(pkg.volumeUuid, pkg.packageName,
6594                    UserHandle.USER_OWNER);
6595
6596            boolean uidError = false;
6597            if (dataPath.exists()) {
6598                int currentUid = 0;
6599                try {
6600                    StructStat stat = Os.stat(dataPath.getPath());
6601                    currentUid = stat.st_uid;
6602                } catch (ErrnoException e) {
6603                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6604                }
6605
6606                // If we have mismatched owners for the data path, we have a problem.
6607                if (currentUid != pkg.applicationInfo.uid) {
6608                    boolean recovered = false;
6609                    if (currentUid == 0) {
6610                        // The directory somehow became owned by root.  Wow.
6611                        // This is probably because the system was stopped while
6612                        // installd was in the middle of messing with its libs
6613                        // directory.  Ask installd to fix that.
6614                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
6615                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
6616                        if (ret >= 0) {
6617                            recovered = true;
6618                            String msg = "Package " + pkg.packageName
6619                                    + " unexpectedly changed to uid 0; recovered to " +
6620                                    + pkg.applicationInfo.uid;
6621                            reportSettingsProblem(Log.WARN, msg);
6622                        }
6623                    }
6624                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6625                            || (scanFlags&SCAN_BOOTING) != 0)) {
6626                        // If this is a system app, we can at least delete its
6627                        // current data so the application will still work.
6628                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
6629                        if (ret >= 0) {
6630                            // TODO: Kill the processes first
6631                            // Old data gone!
6632                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6633                                    ? "System package " : "Third party package ";
6634                            String msg = prefix + pkg.packageName
6635                                    + " has changed from uid: "
6636                                    + currentUid + " to "
6637                                    + pkg.applicationInfo.uid + "; old data erased";
6638                            reportSettingsProblem(Log.WARN, msg);
6639                            recovered = true;
6640
6641                            // And now re-install the app.
6642                            ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6643                                    pkg.applicationInfo.seinfo);
6644                            if (ret == -1) {
6645                                // Ack should not happen!
6646                                msg = prefix + pkg.packageName
6647                                        + " could not have data directory re-created after delete.";
6648                                reportSettingsProblem(Log.WARN, msg);
6649                                throw new PackageManagerException(
6650                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6651                            }
6652                        }
6653                        if (!recovered) {
6654                            mHasSystemUidErrors = true;
6655                        }
6656                    } else if (!recovered) {
6657                        // If we allow this install to proceed, we will be broken.
6658                        // Abort, abort!
6659                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
6660                                "scanPackageLI");
6661                    }
6662                    if (!recovered) {
6663                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
6664                            + pkg.applicationInfo.uid + "/fs_"
6665                            + currentUid;
6666                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
6667                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
6668                        String msg = "Package " + pkg.packageName
6669                                + " has mismatched uid: "
6670                                + currentUid + " on disk, "
6671                                + pkg.applicationInfo.uid + " in settings";
6672                        // writer
6673                        synchronized (mPackages) {
6674                            mSettings.mReadMessages.append(msg);
6675                            mSettings.mReadMessages.append('\n');
6676                            uidError = true;
6677                            if (!pkgSetting.uidError) {
6678                                reportSettingsProblem(Log.ERROR, msg);
6679                            }
6680                        }
6681                    }
6682                }
6683                pkg.applicationInfo.dataDir = dataPath.getPath();
6684                if (mShouldRestoreconData) {
6685                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
6686                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
6687                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
6688                }
6689            } else {
6690                if (DEBUG_PACKAGE_SCANNING) {
6691                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6692                        Log.v(TAG, "Want this data dir: " + dataPath);
6693                }
6694                //invoke installer to do the actual installation
6695                int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6696                        pkg.applicationInfo.seinfo);
6697                if (ret < 0) {
6698                    // Error from installer
6699                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6700                            "Unable to create data dirs [errorCode=" + ret + "]");
6701                }
6702
6703                if (dataPath.exists()) {
6704                    pkg.applicationInfo.dataDir = dataPath.getPath();
6705                } else {
6706                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
6707                    pkg.applicationInfo.dataDir = null;
6708                }
6709            }
6710
6711            pkgSetting.uidError = uidError;
6712        }
6713
6714        final String path = scanFile.getPath();
6715        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
6716
6717        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
6718            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
6719
6720            // Some system apps still use directory structure for native libraries
6721            // in which case we might end up not detecting abi solely based on apk
6722            // structure. Try to detect abi based on directory structure.
6723            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
6724                    pkg.applicationInfo.primaryCpuAbi == null) {
6725                setBundledAppAbisAndRoots(pkg, pkgSetting);
6726                setNativeLibraryPaths(pkg);
6727            }
6728
6729        } else {
6730            if ((scanFlags & SCAN_MOVE) != 0) {
6731                // We haven't run dex-opt for this move (since we've moved the compiled output too)
6732                // but we already have this packages package info in the PackageSetting. We just
6733                // use that and derive the native library path based on the new codepath.
6734                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
6735                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
6736            }
6737
6738            // Set native library paths again. For moves, the path will be updated based on the
6739            // ABIs we've determined above. For non-moves, the path will be updated based on the
6740            // ABIs we determined during compilation, but the path will depend on the final
6741            // package path (after the rename away from the stage path).
6742            setNativeLibraryPaths(pkg);
6743        }
6744
6745        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
6746        final int[] userIds = sUserManager.getUserIds();
6747        synchronized (mInstallLock) {
6748            // Create a native library symlink only if we have native libraries
6749            // and if the native libraries are 32 bit libraries. We do not provide
6750            // this symlink for 64 bit libraries.
6751            if (pkg.applicationInfo.primaryCpuAbi != null &&
6752                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
6753                final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
6754                for (int userId : userIds) {
6755                    if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
6756                            nativeLibPath, userId) < 0) {
6757                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
6758                                "Failed linking native library dir (user=" + userId + ")");
6759                    }
6760                }
6761            }
6762        }
6763
6764        // This is a special case for the "system" package, where the ABI is
6765        // dictated by the zygote configuration (and init.rc). We should keep track
6766        // of this ABI so that we can deal with "normal" applications that run under
6767        // the same UID correctly.
6768        if (mPlatformPackage == pkg) {
6769            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
6770                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
6771        }
6772
6773        // If there's a mismatch between the abi-override in the package setting
6774        // and the abiOverride specified for the install. Warn about this because we
6775        // would've already compiled the app without taking the package setting into
6776        // account.
6777        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
6778            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
6779                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
6780                        " for package: " + pkg.packageName);
6781            }
6782        }
6783
6784        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6785        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6786        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
6787
6788        // Copy the derived override back to the parsed package, so that we can
6789        // update the package settings accordingly.
6790        pkg.cpuAbiOverride = cpuAbiOverride;
6791
6792        if (DEBUG_ABI_SELECTION) {
6793            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
6794                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
6795                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
6796        }
6797
6798        // Push the derived path down into PackageSettings so we know what to
6799        // clean up at uninstall time.
6800        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
6801
6802        if (DEBUG_ABI_SELECTION) {
6803            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
6804                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
6805                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
6806        }
6807
6808        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
6809            // We don't do this here during boot because we can do it all
6810            // at once after scanning all existing packages.
6811            //
6812            // We also do this *before* we perform dexopt on this package, so that
6813            // we can avoid redundant dexopts, and also to make sure we've got the
6814            // code and package path correct.
6815            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
6816                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
6817        }
6818
6819        if ((scanFlags & SCAN_NO_DEX) == 0) {
6820            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
6821                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */);
6822            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6823                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
6824            }
6825        }
6826        if (mFactoryTest && pkg.requestedPermissions.contains(
6827                android.Manifest.permission.FACTORY_TEST)) {
6828            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
6829        }
6830
6831        ArrayList<PackageParser.Package> clientLibPkgs = null;
6832
6833        // writer
6834        synchronized (mPackages) {
6835            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6836                // Only system apps can add new shared libraries.
6837                if (pkg.libraryNames != null) {
6838                    for (int i=0; i<pkg.libraryNames.size(); i++) {
6839                        String name = pkg.libraryNames.get(i);
6840                        boolean allowed = false;
6841                        if (pkg.isUpdatedSystemApp()) {
6842                            // New library entries can only be added through the
6843                            // system image.  This is important to get rid of a lot
6844                            // of nasty edge cases: for example if we allowed a non-
6845                            // system update of the app to add a library, then uninstalling
6846                            // the update would make the library go away, and assumptions
6847                            // we made such as through app install filtering would now
6848                            // have allowed apps on the device which aren't compatible
6849                            // with it.  Better to just have the restriction here, be
6850                            // conservative, and create many fewer cases that can negatively
6851                            // impact the user experience.
6852                            final PackageSetting sysPs = mSettings
6853                                    .getDisabledSystemPkgLPr(pkg.packageName);
6854                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
6855                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
6856                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
6857                                        allowed = true;
6858                                        allowed = true;
6859                                        break;
6860                                    }
6861                                }
6862                            }
6863                        } else {
6864                            allowed = true;
6865                        }
6866                        if (allowed) {
6867                            if (!mSharedLibraries.containsKey(name)) {
6868                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
6869                            } else if (!name.equals(pkg.packageName)) {
6870                                Slog.w(TAG, "Package " + pkg.packageName + " library "
6871                                        + name + " already exists; skipping");
6872                            }
6873                        } else {
6874                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
6875                                    + name + " that is not declared on system image; skipping");
6876                        }
6877                    }
6878                    if ((scanFlags&SCAN_BOOTING) == 0) {
6879                        // If we are not booting, we need to update any applications
6880                        // that are clients of our shared library.  If we are booting,
6881                        // this will all be done once the scan is complete.
6882                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
6883                    }
6884                }
6885            }
6886        }
6887
6888        // We also need to dexopt any apps that are dependent on this library.  Note that
6889        // if these fail, we should abort the install since installing the library will
6890        // result in some apps being broken.
6891        if (clientLibPkgs != null) {
6892            if ((scanFlags & SCAN_NO_DEX) == 0) {
6893                for (int i = 0; i < clientLibPkgs.size(); i++) {
6894                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
6895                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
6896                            null /* instruction sets */, forceDex,
6897                            (scanFlags & SCAN_DEFER_DEX) != 0, false);
6898                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6899                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
6900                                "scanPackageLI failed to dexopt clientLibPkgs");
6901                    }
6902                }
6903            }
6904        }
6905
6906        // Also need to kill any apps that are dependent on the library.
6907        if (clientLibPkgs != null) {
6908            for (int i=0; i<clientLibPkgs.size(); i++) {
6909                PackageParser.Package clientPkg = clientLibPkgs.get(i);
6910                killApplication(clientPkg.applicationInfo.packageName,
6911                        clientPkg.applicationInfo.uid, "update lib");
6912            }
6913        }
6914
6915        // Make sure we're not adding any bogus keyset info
6916        KeySetManagerService ksms = mSettings.mKeySetManagerService;
6917        ksms.assertScannedPackageValid(pkg);
6918
6919        // writer
6920        synchronized (mPackages) {
6921            // We don't expect installation to fail beyond this point
6922
6923            // Add the new setting to mSettings
6924            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
6925            // Add the new setting to mPackages
6926            mPackages.put(pkg.applicationInfo.packageName, pkg);
6927            // Make sure we don't accidentally delete its data.
6928            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
6929            while (iter.hasNext()) {
6930                PackageCleanItem item = iter.next();
6931                if (pkgName.equals(item.packageName)) {
6932                    iter.remove();
6933                }
6934            }
6935
6936            // Take care of first install / last update times.
6937            if (currentTime != 0) {
6938                if (pkgSetting.firstInstallTime == 0) {
6939                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
6940                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
6941                    pkgSetting.lastUpdateTime = currentTime;
6942                }
6943            } else if (pkgSetting.firstInstallTime == 0) {
6944                // We need *something*.  Take time time stamp of the file.
6945                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
6946            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
6947                if (scanFileTime != pkgSetting.timeStamp) {
6948                    // A package on the system image has changed; consider this
6949                    // to be an update.
6950                    pkgSetting.lastUpdateTime = scanFileTime;
6951                }
6952            }
6953
6954            // Add the package's KeySets to the global KeySetManagerService
6955            ksms.addScannedPackageLPw(pkg);
6956
6957            int N = pkg.providers.size();
6958            StringBuilder r = null;
6959            int i;
6960            for (i=0; i<N; i++) {
6961                PackageParser.Provider p = pkg.providers.get(i);
6962                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
6963                        p.info.processName, pkg.applicationInfo.uid);
6964                mProviders.addProvider(p);
6965                p.syncable = p.info.isSyncable;
6966                if (p.info.authority != null) {
6967                    String names[] = p.info.authority.split(";");
6968                    p.info.authority = null;
6969                    for (int j = 0; j < names.length; j++) {
6970                        if (j == 1 && p.syncable) {
6971                            // We only want the first authority for a provider to possibly be
6972                            // syncable, so if we already added this provider using a different
6973                            // authority clear the syncable flag. We copy the provider before
6974                            // changing it because the mProviders object contains a reference
6975                            // to a provider that we don't want to change.
6976                            // Only do this for the second authority since the resulting provider
6977                            // object can be the same for all future authorities for this provider.
6978                            p = new PackageParser.Provider(p);
6979                            p.syncable = false;
6980                        }
6981                        if (!mProvidersByAuthority.containsKey(names[j])) {
6982                            mProvidersByAuthority.put(names[j], p);
6983                            if (p.info.authority == null) {
6984                                p.info.authority = names[j];
6985                            } else {
6986                                p.info.authority = p.info.authority + ";" + names[j];
6987                            }
6988                            if (DEBUG_PACKAGE_SCANNING) {
6989                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6990                                    Log.d(TAG, "Registered content provider: " + names[j]
6991                                            + ", className = " + p.info.name + ", isSyncable = "
6992                                            + p.info.isSyncable);
6993                            }
6994                        } else {
6995                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6996                            Slog.w(TAG, "Skipping provider name " + names[j] +
6997                                    " (in package " + pkg.applicationInfo.packageName +
6998                                    "): name already used by "
6999                                    + ((other != null && other.getComponentName() != null)
7000                                            ? other.getComponentName().getPackageName() : "?"));
7001                        }
7002                    }
7003                }
7004                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7005                    if (r == null) {
7006                        r = new StringBuilder(256);
7007                    } else {
7008                        r.append(' ');
7009                    }
7010                    r.append(p.info.name);
7011                }
7012            }
7013            if (r != null) {
7014                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7015            }
7016
7017            N = pkg.services.size();
7018            r = null;
7019            for (i=0; i<N; i++) {
7020                PackageParser.Service s = pkg.services.get(i);
7021                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7022                        s.info.processName, pkg.applicationInfo.uid);
7023                mServices.addService(s);
7024                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7025                    if (r == null) {
7026                        r = new StringBuilder(256);
7027                    } else {
7028                        r.append(' ');
7029                    }
7030                    r.append(s.info.name);
7031                }
7032            }
7033            if (r != null) {
7034                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7035            }
7036
7037            N = pkg.receivers.size();
7038            r = null;
7039            for (i=0; i<N; i++) {
7040                PackageParser.Activity a = pkg.receivers.get(i);
7041                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7042                        a.info.processName, pkg.applicationInfo.uid);
7043                mReceivers.addActivity(a, "receiver");
7044                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7045                    if (r == null) {
7046                        r = new StringBuilder(256);
7047                    } else {
7048                        r.append(' ');
7049                    }
7050                    r.append(a.info.name);
7051                }
7052            }
7053            if (r != null) {
7054                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7055            }
7056
7057            N = pkg.activities.size();
7058            r = null;
7059            for (i=0; i<N; i++) {
7060                PackageParser.Activity a = pkg.activities.get(i);
7061                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7062                        a.info.processName, pkg.applicationInfo.uid);
7063                mActivities.addActivity(a, "activity");
7064                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7065                    if (r == null) {
7066                        r = new StringBuilder(256);
7067                    } else {
7068                        r.append(' ');
7069                    }
7070                    r.append(a.info.name);
7071                }
7072            }
7073            if (r != null) {
7074                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7075            }
7076
7077            N = pkg.permissionGroups.size();
7078            r = null;
7079            for (i=0; i<N; i++) {
7080                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7081                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7082                if (cur == null) {
7083                    mPermissionGroups.put(pg.info.name, pg);
7084                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7085                        if (r == null) {
7086                            r = new StringBuilder(256);
7087                        } else {
7088                            r.append(' ');
7089                        }
7090                        r.append(pg.info.name);
7091                    }
7092                } else {
7093                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7094                            + pg.info.packageName + " ignored: original from "
7095                            + cur.info.packageName);
7096                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7097                        if (r == null) {
7098                            r = new StringBuilder(256);
7099                        } else {
7100                            r.append(' ');
7101                        }
7102                        r.append("DUP:");
7103                        r.append(pg.info.name);
7104                    }
7105                }
7106            }
7107            if (r != null) {
7108                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7109            }
7110
7111            N = pkg.permissions.size();
7112            r = null;
7113            for (i=0; i<N; i++) {
7114                PackageParser.Permission p = pkg.permissions.get(i);
7115
7116                // Now that permission groups have a special meaning, we ignore permission
7117                // groups for legacy apps to prevent unexpected behavior. In particular,
7118                // permissions for one app being granted to someone just becuase they happen
7119                // to be in a group defined by another app (before this had no implications).
7120                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7121                    p.group = mPermissionGroups.get(p.info.group);
7122                    // Warn for a permission in an unknown group.
7123                    if (p.info.group != null && p.group == null) {
7124                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7125                                + p.info.packageName + " in an unknown group " + p.info.group);
7126                    }
7127                }
7128
7129                ArrayMap<String, BasePermission> permissionMap =
7130                        p.tree ? mSettings.mPermissionTrees
7131                                : mSettings.mPermissions;
7132                BasePermission bp = permissionMap.get(p.info.name);
7133
7134                // Allow system apps to redefine non-system permissions
7135                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7136                    final boolean currentOwnerIsSystem = (bp.perm != null
7137                            && isSystemApp(bp.perm.owner));
7138                    if (isSystemApp(p.owner)) {
7139                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7140                            // It's a built-in permission and no owner, take ownership now
7141                            bp.packageSetting = pkgSetting;
7142                            bp.perm = p;
7143                            bp.uid = pkg.applicationInfo.uid;
7144                            bp.sourcePackage = p.info.packageName;
7145                        } else if (!currentOwnerIsSystem) {
7146                            String msg = "New decl " + p.owner + " of permission  "
7147                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7148                            reportSettingsProblem(Log.WARN, msg);
7149                            bp = null;
7150                        }
7151                    }
7152                }
7153
7154                if (bp == null) {
7155                    bp = new BasePermission(p.info.name, p.info.packageName,
7156                            BasePermission.TYPE_NORMAL);
7157                    permissionMap.put(p.info.name, bp);
7158                }
7159
7160                if (bp.perm == null) {
7161                    if (bp.sourcePackage == null
7162                            || bp.sourcePackage.equals(p.info.packageName)) {
7163                        BasePermission tree = findPermissionTreeLP(p.info.name);
7164                        if (tree == null
7165                                || tree.sourcePackage.equals(p.info.packageName)) {
7166                            bp.packageSetting = pkgSetting;
7167                            bp.perm = p;
7168                            bp.uid = pkg.applicationInfo.uid;
7169                            bp.sourcePackage = p.info.packageName;
7170                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7171                                if (r == null) {
7172                                    r = new StringBuilder(256);
7173                                } else {
7174                                    r.append(' ');
7175                                }
7176                                r.append(p.info.name);
7177                            }
7178                        } else {
7179                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7180                                    + p.info.packageName + " ignored: base tree "
7181                                    + tree.name + " is from package "
7182                                    + tree.sourcePackage);
7183                        }
7184                    } else {
7185                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7186                                + p.info.packageName + " ignored: original from "
7187                                + bp.sourcePackage);
7188                    }
7189                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7190                    if (r == null) {
7191                        r = new StringBuilder(256);
7192                    } else {
7193                        r.append(' ');
7194                    }
7195                    r.append("DUP:");
7196                    r.append(p.info.name);
7197                }
7198                if (bp.perm == p) {
7199                    bp.protectionLevel = p.info.protectionLevel;
7200                }
7201            }
7202
7203            if (r != null) {
7204                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7205            }
7206
7207            N = pkg.instrumentation.size();
7208            r = null;
7209            for (i=0; i<N; i++) {
7210                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7211                a.info.packageName = pkg.applicationInfo.packageName;
7212                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7213                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7214                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7215                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7216                a.info.dataDir = pkg.applicationInfo.dataDir;
7217
7218                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7219                // need other information about the application, like the ABI and what not ?
7220                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7221                mInstrumentation.put(a.getComponentName(), a);
7222                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7223                    if (r == null) {
7224                        r = new StringBuilder(256);
7225                    } else {
7226                        r.append(' ');
7227                    }
7228                    r.append(a.info.name);
7229                }
7230            }
7231            if (r != null) {
7232                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7233            }
7234
7235            if (pkg.protectedBroadcasts != null) {
7236                N = pkg.protectedBroadcasts.size();
7237                for (i=0; i<N; i++) {
7238                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7239                }
7240            }
7241
7242            pkgSetting.setTimeStamp(scanFileTime);
7243
7244            // Create idmap files for pairs of (packages, overlay packages).
7245            // Note: "android", ie framework-res.apk, is handled by native layers.
7246            if (pkg.mOverlayTarget != null) {
7247                // This is an overlay package.
7248                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7249                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7250                        mOverlays.put(pkg.mOverlayTarget,
7251                                new ArrayMap<String, PackageParser.Package>());
7252                    }
7253                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7254                    map.put(pkg.packageName, pkg);
7255                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7256                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7257                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7258                                "scanPackageLI failed to createIdmap");
7259                    }
7260                }
7261            } else if (mOverlays.containsKey(pkg.packageName) &&
7262                    !pkg.packageName.equals("android")) {
7263                // This is a regular package, with one or more known overlay packages.
7264                createIdmapsForPackageLI(pkg);
7265            }
7266        }
7267
7268        return pkg;
7269    }
7270
7271    /**
7272     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7273     * is derived purely on the basis of the contents of {@code scanFile} and
7274     * {@code cpuAbiOverride}.
7275     *
7276     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7277     */
7278    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7279                                 String cpuAbiOverride, boolean extractLibs)
7280            throws PackageManagerException {
7281        // TODO: We can probably be smarter about this stuff. For installed apps,
7282        // we can calculate this information at install time once and for all. For
7283        // system apps, we can probably assume that this information doesn't change
7284        // after the first boot scan. As things stand, we do lots of unnecessary work.
7285
7286        // Give ourselves some initial paths; we'll come back for another
7287        // pass once we've determined ABI below.
7288        setNativeLibraryPaths(pkg);
7289
7290        // We would never need to extract libs for forward-locked and external packages,
7291        // since the container service will do it for us. We shouldn't attempt to
7292        // extract libs from system app when it was not updated.
7293        if (pkg.isForwardLocked() || isExternal(pkg) ||
7294            (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) {
7295            extractLibs = false;
7296        }
7297
7298        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7299        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7300
7301        NativeLibraryHelper.Handle handle = null;
7302        try {
7303            handle = NativeLibraryHelper.Handle.create(scanFile);
7304            // TODO(multiArch): This can be null for apps that didn't go through the
7305            // usual installation process. We can calculate it again, like we
7306            // do during install time.
7307            //
7308            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7309            // unnecessary.
7310            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7311
7312            // Null out the abis so that they can be recalculated.
7313            pkg.applicationInfo.primaryCpuAbi = null;
7314            pkg.applicationInfo.secondaryCpuAbi = null;
7315            if (isMultiArch(pkg.applicationInfo)) {
7316                // Warn if we've set an abiOverride for multi-lib packages..
7317                // By definition, we need to copy both 32 and 64 bit libraries for
7318                // such packages.
7319                if (pkg.cpuAbiOverride != null
7320                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7321                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7322                }
7323
7324                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7325                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7326                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7327                    if (extractLibs) {
7328                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7329                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7330                                useIsaSpecificSubdirs);
7331                    } else {
7332                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7333                    }
7334                }
7335
7336                maybeThrowExceptionForMultiArchCopy(
7337                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7338
7339                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7340                    if (extractLibs) {
7341                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7342                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7343                                useIsaSpecificSubdirs);
7344                    } else {
7345                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7346                    }
7347                }
7348
7349                maybeThrowExceptionForMultiArchCopy(
7350                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7351
7352                if (abi64 >= 0) {
7353                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7354                }
7355
7356                if (abi32 >= 0) {
7357                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7358                    if (abi64 >= 0) {
7359                        pkg.applicationInfo.secondaryCpuAbi = abi;
7360                    } else {
7361                        pkg.applicationInfo.primaryCpuAbi = abi;
7362                    }
7363                }
7364            } else {
7365                String[] abiList = (cpuAbiOverride != null) ?
7366                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7367
7368                // Enable gross and lame hacks for apps that are built with old
7369                // SDK tools. We must scan their APKs for renderscript bitcode and
7370                // not launch them if it's present. Don't bother checking on devices
7371                // that don't have 64 bit support.
7372                boolean needsRenderScriptOverride = false;
7373                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7374                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7375                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7376                    needsRenderScriptOverride = true;
7377                }
7378
7379                final int copyRet;
7380                if (extractLibs) {
7381                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7382                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7383                } else {
7384                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7385                }
7386
7387                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7388                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7389                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7390                }
7391
7392                if (copyRet >= 0) {
7393                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7394                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7395                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7396                } else if (needsRenderScriptOverride) {
7397                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7398                }
7399            }
7400        } catch (IOException ioe) {
7401            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7402        } finally {
7403            IoUtils.closeQuietly(handle);
7404        }
7405
7406        // Now that we've calculated the ABIs and determined if it's an internal app,
7407        // we will go ahead and populate the nativeLibraryPath.
7408        setNativeLibraryPaths(pkg);
7409    }
7410
7411    /**
7412     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7413     * i.e, so that all packages can be run inside a single process if required.
7414     *
7415     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7416     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7417     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7418     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7419     * updating a package that belongs to a shared user.
7420     *
7421     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7422     * adds unnecessary complexity.
7423     */
7424    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7425            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
7426        String requiredInstructionSet = null;
7427        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7428            requiredInstructionSet = VMRuntime.getInstructionSet(
7429                     scannedPackage.applicationInfo.primaryCpuAbi);
7430        }
7431
7432        PackageSetting requirer = null;
7433        for (PackageSetting ps : packagesForUser) {
7434            // If packagesForUser contains scannedPackage, we skip it. This will happen
7435            // when scannedPackage is an update of an existing package. Without this check,
7436            // we will never be able to change the ABI of any package belonging to a shared
7437            // user, even if it's compatible with other packages.
7438            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7439                if (ps.primaryCpuAbiString == null) {
7440                    continue;
7441                }
7442
7443                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7444                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7445                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7446                    // this but there's not much we can do.
7447                    String errorMessage = "Instruction set mismatch, "
7448                            + ((requirer == null) ? "[caller]" : requirer)
7449                            + " requires " + requiredInstructionSet + " whereas " + ps
7450                            + " requires " + instructionSet;
7451                    Slog.w(TAG, errorMessage);
7452                }
7453
7454                if (requiredInstructionSet == null) {
7455                    requiredInstructionSet = instructionSet;
7456                    requirer = ps;
7457                }
7458            }
7459        }
7460
7461        if (requiredInstructionSet != null) {
7462            String adjustedAbi;
7463            if (requirer != null) {
7464                // requirer != null implies that either scannedPackage was null or that scannedPackage
7465                // did not require an ABI, in which case we have to adjust scannedPackage to match
7466                // the ABI of the set (which is the same as requirer's ABI)
7467                adjustedAbi = requirer.primaryCpuAbiString;
7468                if (scannedPackage != null) {
7469                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7470                }
7471            } else {
7472                // requirer == null implies that we're updating all ABIs in the set to
7473                // match scannedPackage.
7474                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7475            }
7476
7477            for (PackageSetting ps : packagesForUser) {
7478                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7479                    if (ps.primaryCpuAbiString != null) {
7480                        continue;
7481                    }
7482
7483                    ps.primaryCpuAbiString = adjustedAbi;
7484                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7485                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7486                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7487
7488                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
7489                                null /* instruction sets */, forceDexOpt, deferDexOpt, true);
7490                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7491                            ps.primaryCpuAbiString = null;
7492                            ps.pkg.applicationInfo.primaryCpuAbi = null;
7493                            return;
7494                        } else {
7495                            mInstaller.rmdex(ps.codePathString,
7496                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
7497                        }
7498                    }
7499                }
7500            }
7501        }
7502    }
7503
7504    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7505        synchronized (mPackages) {
7506            mResolverReplaced = true;
7507            // Set up information for custom user intent resolution activity.
7508            mResolveActivity.applicationInfo = pkg.applicationInfo;
7509            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7510            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7511            mResolveActivity.processName = pkg.applicationInfo.packageName;
7512            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7513            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7514                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7515            mResolveActivity.theme = 0;
7516            mResolveActivity.exported = true;
7517            mResolveActivity.enabled = true;
7518            mResolveInfo.activityInfo = mResolveActivity;
7519            mResolveInfo.priority = 0;
7520            mResolveInfo.preferredOrder = 0;
7521            mResolveInfo.match = 0;
7522            mResolveComponentName = mCustomResolverComponentName;
7523            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7524                    mResolveComponentName);
7525        }
7526    }
7527
7528    private static String calculateBundledApkRoot(final String codePathString) {
7529        final File codePath = new File(codePathString);
7530        final File codeRoot;
7531        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7532            codeRoot = Environment.getRootDirectory();
7533        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7534            codeRoot = Environment.getOemDirectory();
7535        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7536            codeRoot = Environment.getVendorDirectory();
7537        } else {
7538            // Unrecognized code path; take its top real segment as the apk root:
7539            // e.g. /something/app/blah.apk => /something
7540            try {
7541                File f = codePath.getCanonicalFile();
7542                File parent = f.getParentFile();    // non-null because codePath is a file
7543                File tmp;
7544                while ((tmp = parent.getParentFile()) != null) {
7545                    f = parent;
7546                    parent = tmp;
7547                }
7548                codeRoot = f;
7549                Slog.w(TAG, "Unrecognized code path "
7550                        + codePath + " - using " + codeRoot);
7551            } catch (IOException e) {
7552                // Can't canonicalize the code path -- shenanigans?
7553                Slog.w(TAG, "Can't canonicalize code path " + codePath);
7554                return Environment.getRootDirectory().getPath();
7555            }
7556        }
7557        return codeRoot.getPath();
7558    }
7559
7560    /**
7561     * Derive and set the location of native libraries for the given package,
7562     * which varies depending on where and how the package was installed.
7563     */
7564    private void setNativeLibraryPaths(PackageParser.Package pkg) {
7565        final ApplicationInfo info = pkg.applicationInfo;
7566        final String codePath = pkg.codePath;
7567        final File codeFile = new File(codePath);
7568        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7569        final boolean asecApp = info.isForwardLocked() || isExternal(info);
7570
7571        info.nativeLibraryRootDir = null;
7572        info.nativeLibraryRootRequiresIsa = false;
7573        info.nativeLibraryDir = null;
7574        info.secondaryNativeLibraryDir = null;
7575
7576        if (isApkFile(codeFile)) {
7577            // Monolithic install
7578            if (bundledApp) {
7579                // If "/system/lib64/apkname" exists, assume that is the per-package
7580                // native library directory to use; otherwise use "/system/lib/apkname".
7581                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
7582                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
7583                        getPrimaryInstructionSet(info));
7584
7585                // This is a bundled system app so choose the path based on the ABI.
7586                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
7587                // is just the default path.
7588                final String apkName = deriveCodePathName(codePath);
7589                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
7590                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
7591                        apkName).getAbsolutePath();
7592
7593                if (info.secondaryCpuAbi != null) {
7594                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7595                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7596                            secondaryLibDir, apkName).getAbsolutePath();
7597                }
7598            } else if (asecApp) {
7599                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
7600                        .getAbsolutePath();
7601            } else {
7602                final String apkName = deriveCodePathName(codePath);
7603                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
7604                        .getAbsolutePath();
7605            }
7606
7607            info.nativeLibraryRootRequiresIsa = false;
7608            info.nativeLibraryDir = info.nativeLibraryRootDir;
7609        } else {
7610            // Cluster install
7611            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7612            info.nativeLibraryRootRequiresIsa = true;
7613
7614            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7615                    getPrimaryInstructionSet(info)).getAbsolutePath();
7616
7617            if (info.secondaryCpuAbi != null) {
7618                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7619                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7620            }
7621        }
7622    }
7623
7624    /**
7625     * Calculate the abis and roots for a bundled app. These can uniquely
7626     * be determined from the contents of the system partition, i.e whether
7627     * it contains 64 or 32 bit shared libraries etc. We do not validate any
7628     * of this information, and instead assume that the system was built
7629     * sensibly.
7630     */
7631    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
7632                                           PackageSetting pkgSetting) {
7633        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
7634
7635        // If "/system/lib64/apkname" exists, assume that is the per-package
7636        // native library directory to use; otherwise use "/system/lib/apkname".
7637        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
7638        setBundledAppAbi(pkg, apkRoot, apkName);
7639        // pkgSetting might be null during rescan following uninstall of updates
7640        // to a bundled app, so accommodate that possibility.  The settings in
7641        // that case will be established later from the parsed package.
7642        //
7643        // If the settings aren't null, sync them up with what we've just derived.
7644        // note that apkRoot isn't stored in the package settings.
7645        if (pkgSetting != null) {
7646            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7647            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7648        }
7649    }
7650
7651    /**
7652     * Deduces the ABI of a bundled app and sets the relevant fields on the
7653     * parsed pkg object.
7654     *
7655     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
7656     *        under which system libraries are installed.
7657     * @param apkName the name of the installed package.
7658     */
7659    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7660        final File codeFile = new File(pkg.codePath);
7661
7662        final boolean has64BitLibs;
7663        final boolean has32BitLibs;
7664        if (isApkFile(codeFile)) {
7665            // Monolithic install
7666            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7667            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7668        } else {
7669            // Cluster install
7670            final File rootDir = new File(codeFile, LIB_DIR_NAME);
7671            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7672                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7673                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7674                has64BitLibs = (new File(rootDir, isa)).exists();
7675            } else {
7676                has64BitLibs = false;
7677            }
7678            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7679                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7680                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7681                has32BitLibs = (new File(rootDir, isa)).exists();
7682            } else {
7683                has32BitLibs = false;
7684            }
7685        }
7686
7687        if (has64BitLibs && !has32BitLibs) {
7688            // The package has 64 bit libs, but not 32 bit libs. Its primary
7689            // ABI should be 64 bit. We can safely assume here that the bundled
7690            // native libraries correspond to the most preferred ABI in the list.
7691
7692            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7693            pkg.applicationInfo.secondaryCpuAbi = null;
7694        } else if (has32BitLibs && !has64BitLibs) {
7695            // The package has 32 bit libs but not 64 bit libs. Its primary
7696            // ABI should be 32 bit.
7697
7698            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7699            pkg.applicationInfo.secondaryCpuAbi = null;
7700        } else if (has32BitLibs && has64BitLibs) {
7701            // The application has both 64 and 32 bit bundled libraries. We check
7702            // here that the app declares multiArch support, and warn if it doesn't.
7703            //
7704            // We will be lenient here and record both ABIs. The primary will be the
7705            // ABI that's higher on the list, i.e, a device that's configured to prefer
7706            // 64 bit apps will see a 64 bit primary ABI,
7707
7708            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
7709                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
7710            }
7711
7712            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
7713                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7714                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7715            } else {
7716                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7717                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7718            }
7719        } else {
7720            pkg.applicationInfo.primaryCpuAbi = null;
7721            pkg.applicationInfo.secondaryCpuAbi = null;
7722        }
7723    }
7724
7725    private void killApplication(String pkgName, int appId, String reason) {
7726        // Request the ActivityManager to kill the process(only for existing packages)
7727        // so that we do not end up in a confused state while the user is still using the older
7728        // version of the application while the new one gets installed.
7729        IActivityManager am = ActivityManagerNative.getDefault();
7730        if (am != null) {
7731            try {
7732                am.killApplicationWithAppId(pkgName, appId, reason);
7733            } catch (RemoteException e) {
7734            }
7735        }
7736    }
7737
7738    void removePackageLI(PackageSetting ps, boolean chatty) {
7739        if (DEBUG_INSTALL) {
7740            if (chatty)
7741                Log.d(TAG, "Removing package " + ps.name);
7742        }
7743
7744        // writer
7745        synchronized (mPackages) {
7746            mPackages.remove(ps.name);
7747            final PackageParser.Package pkg = ps.pkg;
7748            if (pkg != null) {
7749                cleanPackageDataStructuresLILPw(pkg, chatty);
7750            }
7751        }
7752    }
7753
7754    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
7755        if (DEBUG_INSTALL) {
7756            if (chatty)
7757                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
7758        }
7759
7760        // writer
7761        synchronized (mPackages) {
7762            mPackages.remove(pkg.applicationInfo.packageName);
7763            cleanPackageDataStructuresLILPw(pkg, chatty);
7764        }
7765    }
7766
7767    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
7768        int N = pkg.providers.size();
7769        StringBuilder r = null;
7770        int i;
7771        for (i=0; i<N; i++) {
7772            PackageParser.Provider p = pkg.providers.get(i);
7773            mProviders.removeProvider(p);
7774            if (p.info.authority == null) {
7775
7776                /* There was another ContentProvider with this authority when
7777                 * this app was installed so this authority is null,
7778                 * Ignore it as we don't have to unregister the provider.
7779                 */
7780                continue;
7781            }
7782            String names[] = p.info.authority.split(";");
7783            for (int j = 0; j < names.length; j++) {
7784                if (mProvidersByAuthority.get(names[j]) == p) {
7785                    mProvidersByAuthority.remove(names[j]);
7786                    if (DEBUG_REMOVE) {
7787                        if (chatty)
7788                            Log.d(TAG, "Unregistered content provider: " + names[j]
7789                                    + ", className = " + p.info.name + ", isSyncable = "
7790                                    + p.info.isSyncable);
7791                    }
7792                }
7793            }
7794            if (DEBUG_REMOVE && chatty) {
7795                if (r == null) {
7796                    r = new StringBuilder(256);
7797                } else {
7798                    r.append(' ');
7799                }
7800                r.append(p.info.name);
7801            }
7802        }
7803        if (r != null) {
7804            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
7805        }
7806
7807        N = pkg.services.size();
7808        r = null;
7809        for (i=0; i<N; i++) {
7810            PackageParser.Service s = pkg.services.get(i);
7811            mServices.removeService(s);
7812            if (chatty) {
7813                if (r == null) {
7814                    r = new StringBuilder(256);
7815                } else {
7816                    r.append(' ');
7817                }
7818                r.append(s.info.name);
7819            }
7820        }
7821        if (r != null) {
7822            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
7823        }
7824
7825        N = pkg.receivers.size();
7826        r = null;
7827        for (i=0; i<N; i++) {
7828            PackageParser.Activity a = pkg.receivers.get(i);
7829            mReceivers.removeActivity(a, "receiver");
7830            if (DEBUG_REMOVE && chatty) {
7831                if (r == null) {
7832                    r = new StringBuilder(256);
7833                } else {
7834                    r.append(' ');
7835                }
7836                r.append(a.info.name);
7837            }
7838        }
7839        if (r != null) {
7840            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
7841        }
7842
7843        N = pkg.activities.size();
7844        r = null;
7845        for (i=0; i<N; i++) {
7846            PackageParser.Activity a = pkg.activities.get(i);
7847            mActivities.removeActivity(a, "activity");
7848            if (DEBUG_REMOVE && chatty) {
7849                if (r == null) {
7850                    r = new StringBuilder(256);
7851                } else {
7852                    r.append(' ');
7853                }
7854                r.append(a.info.name);
7855            }
7856        }
7857        if (r != null) {
7858            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
7859        }
7860
7861        N = pkg.permissions.size();
7862        r = null;
7863        for (i=0; i<N; i++) {
7864            PackageParser.Permission p = pkg.permissions.get(i);
7865            BasePermission bp = mSettings.mPermissions.get(p.info.name);
7866            if (bp == null) {
7867                bp = mSettings.mPermissionTrees.get(p.info.name);
7868            }
7869            if (bp != null && bp.perm == p) {
7870                bp.perm = null;
7871                if (DEBUG_REMOVE && chatty) {
7872                    if (r == null) {
7873                        r = new StringBuilder(256);
7874                    } else {
7875                        r.append(' ');
7876                    }
7877                    r.append(p.info.name);
7878                }
7879            }
7880            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7881                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
7882                if (appOpPerms != null) {
7883                    appOpPerms.remove(pkg.packageName);
7884                }
7885            }
7886        }
7887        if (r != null) {
7888            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
7889        }
7890
7891        N = pkg.requestedPermissions.size();
7892        r = null;
7893        for (i=0; i<N; i++) {
7894            String perm = pkg.requestedPermissions.get(i);
7895            BasePermission bp = mSettings.mPermissions.get(perm);
7896            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7897                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
7898                if (appOpPerms != null) {
7899                    appOpPerms.remove(pkg.packageName);
7900                    if (appOpPerms.isEmpty()) {
7901                        mAppOpPermissionPackages.remove(perm);
7902                    }
7903                }
7904            }
7905        }
7906        if (r != null) {
7907            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
7908        }
7909
7910        N = pkg.instrumentation.size();
7911        r = null;
7912        for (i=0; i<N; i++) {
7913            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7914            mInstrumentation.remove(a.getComponentName());
7915            if (DEBUG_REMOVE && chatty) {
7916                if (r == null) {
7917                    r = new StringBuilder(256);
7918                } else {
7919                    r.append(' ');
7920                }
7921                r.append(a.info.name);
7922            }
7923        }
7924        if (r != null) {
7925            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
7926        }
7927
7928        r = null;
7929        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7930            // Only system apps can hold shared libraries.
7931            if (pkg.libraryNames != null) {
7932                for (i=0; i<pkg.libraryNames.size(); i++) {
7933                    String name = pkg.libraryNames.get(i);
7934                    SharedLibraryEntry cur = mSharedLibraries.get(name);
7935                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
7936                        mSharedLibraries.remove(name);
7937                        if (DEBUG_REMOVE && chatty) {
7938                            if (r == null) {
7939                                r = new StringBuilder(256);
7940                            } else {
7941                                r.append(' ');
7942                            }
7943                            r.append(name);
7944                        }
7945                    }
7946                }
7947            }
7948        }
7949        if (r != null) {
7950            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
7951        }
7952    }
7953
7954    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
7955        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
7956            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
7957                return true;
7958            }
7959        }
7960        return false;
7961    }
7962
7963    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
7964    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
7965    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
7966
7967    private void updatePermissionsLPw(String changingPkg,
7968            PackageParser.Package pkgInfo, int flags) {
7969        // Make sure there are no dangling permission trees.
7970        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
7971        while (it.hasNext()) {
7972            final BasePermission bp = it.next();
7973            if (bp.packageSetting == null) {
7974                // We may not yet have parsed the package, so just see if
7975                // we still know about its settings.
7976                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
7977            }
7978            if (bp.packageSetting == null) {
7979                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
7980                        + " from package " + bp.sourcePackage);
7981                it.remove();
7982            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
7983                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
7984                    Slog.i(TAG, "Removing old permission tree: " + bp.name
7985                            + " from package " + bp.sourcePackage);
7986                    flags |= UPDATE_PERMISSIONS_ALL;
7987                    it.remove();
7988                }
7989            }
7990        }
7991
7992        // Make sure all dynamic permissions have been assigned to a package,
7993        // and make sure there are no dangling permissions.
7994        it = mSettings.mPermissions.values().iterator();
7995        while (it.hasNext()) {
7996            final BasePermission bp = it.next();
7997            if (bp.type == BasePermission.TYPE_DYNAMIC) {
7998                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
7999                        + bp.name + " pkg=" + bp.sourcePackage
8000                        + " info=" + bp.pendingInfo);
8001                if (bp.packageSetting == null && bp.pendingInfo != null) {
8002                    final BasePermission tree = findPermissionTreeLP(bp.name);
8003                    if (tree != null && tree.perm != null) {
8004                        bp.packageSetting = tree.packageSetting;
8005                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8006                                new PermissionInfo(bp.pendingInfo));
8007                        bp.perm.info.packageName = tree.perm.info.packageName;
8008                        bp.perm.info.name = bp.name;
8009                        bp.uid = tree.uid;
8010                    }
8011                }
8012            }
8013            if (bp.packageSetting == null) {
8014                // We may not yet have parsed the package, so just see if
8015                // we still know about its settings.
8016                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8017            }
8018            if (bp.packageSetting == null) {
8019                Slog.w(TAG, "Removing dangling permission: " + bp.name
8020                        + " from package " + bp.sourcePackage);
8021                it.remove();
8022            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8023                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8024                    Slog.i(TAG, "Removing old permission: " + bp.name
8025                            + " from package " + bp.sourcePackage);
8026                    flags |= UPDATE_PERMISSIONS_ALL;
8027                    it.remove();
8028                }
8029            }
8030        }
8031
8032        // Now update the permissions for all packages, in particular
8033        // replace the granted permissions of the system packages.
8034        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8035            for (PackageParser.Package pkg : mPackages.values()) {
8036                if (pkg != pkgInfo) {
8037                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
8038                            changingPkg);
8039                }
8040            }
8041        }
8042
8043        if (pkgInfo != null) {
8044            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
8045        }
8046    }
8047
8048    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8049            String packageOfInterest) {
8050        // IMPORTANT: There are two types of permissions: install and runtime.
8051        // Install time permissions are granted when the app is installed to
8052        // all device users and users added in the future. Runtime permissions
8053        // are granted at runtime explicitly to specific users. Normal and signature
8054        // protected permissions are install time permissions. Dangerous permissions
8055        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8056        // otherwise they are runtime permissions. This function does not manage
8057        // runtime permissions except for the case an app targeting Lollipop MR1
8058        // being upgraded to target a newer SDK, in which case dangerous permissions
8059        // are transformed from install time to runtime ones.
8060
8061        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8062        if (ps == null) {
8063            return;
8064        }
8065
8066        PermissionsState permissionsState = ps.getPermissionsState();
8067        PermissionsState origPermissions = permissionsState;
8068
8069        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8070
8071        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8072
8073        boolean changedInstallPermission = false;
8074
8075        if (replace) {
8076            ps.installPermissionsFixed = false;
8077            if (!ps.isSharedUser()) {
8078                origPermissions = new PermissionsState(permissionsState);
8079                permissionsState.reset();
8080            }
8081        }
8082
8083        permissionsState.setGlobalGids(mGlobalGids);
8084
8085        final int N = pkg.requestedPermissions.size();
8086        for (int i=0; i<N; i++) {
8087            final String name = pkg.requestedPermissions.get(i);
8088            final BasePermission bp = mSettings.mPermissions.get(name);
8089
8090            if (DEBUG_INSTALL) {
8091                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8092            }
8093
8094            if (bp == null || bp.packageSetting == null) {
8095                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8096                    Slog.w(TAG, "Unknown permission " + name
8097                            + " in package " + pkg.packageName);
8098                }
8099                continue;
8100            }
8101
8102            final String perm = bp.name;
8103            boolean allowedSig = false;
8104            int grant = GRANT_DENIED;
8105
8106            // Keep track of app op permissions.
8107            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8108                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8109                if (pkgs == null) {
8110                    pkgs = new ArraySet<>();
8111                    mAppOpPermissionPackages.put(bp.name, pkgs);
8112                }
8113                pkgs.add(pkg.packageName);
8114            }
8115
8116            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8117            switch (level) {
8118                case PermissionInfo.PROTECTION_NORMAL: {
8119                    // For all apps normal permissions are install time ones.
8120                    grant = GRANT_INSTALL;
8121                } break;
8122
8123                case PermissionInfo.PROTECTION_DANGEROUS: {
8124                    if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
8125                        // For legacy apps dangerous permissions are install time ones.
8126                        grant = GRANT_INSTALL_LEGACY;
8127                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8128                        // For legacy apps that became modern, install becomes runtime.
8129                        grant = GRANT_UPGRADE;
8130                    } else {
8131                        // For modern apps keep runtime permissions unchanged.
8132                        grant = GRANT_RUNTIME;
8133                    }
8134                } break;
8135
8136                case PermissionInfo.PROTECTION_SIGNATURE: {
8137                    // For all apps signature permissions are install time ones.
8138                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8139                    if (allowedSig) {
8140                        grant = GRANT_INSTALL;
8141                    }
8142                } break;
8143            }
8144
8145            if (DEBUG_INSTALL) {
8146                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8147            }
8148
8149            if (grant != GRANT_DENIED) {
8150                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8151                    // If this is an existing, non-system package, then
8152                    // we can't add any new permissions to it.
8153                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8154                        // Except...  if this is a permission that was added
8155                        // to the platform (note: need to only do this when
8156                        // updating the platform).
8157                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8158                            grant = GRANT_DENIED;
8159                        }
8160                    }
8161                }
8162
8163                switch (grant) {
8164                    case GRANT_INSTALL: {
8165                        // Revoke this as runtime permission to handle the case of
8166                        // a runtime permission being downgraded to an install one.
8167                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8168                            if (origPermissions.getRuntimePermissionState(
8169                                    bp.name, userId) != null) {
8170                                // Revoke the runtime permission and clear the flags.
8171                                origPermissions.revokeRuntimePermission(bp, userId);
8172                                origPermissions.updatePermissionFlags(bp, userId,
8173                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8174                                // If we revoked a permission permission, we have to write.
8175                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8176                                        changedRuntimePermissionUserIds, userId);
8177                            }
8178                        }
8179                        // Grant an install permission.
8180                        if (permissionsState.grantInstallPermission(bp) !=
8181                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8182                            changedInstallPermission = true;
8183                        }
8184                    } break;
8185
8186                    case GRANT_INSTALL_LEGACY: {
8187                        // Grant an install permission.
8188                        if (permissionsState.grantInstallPermission(bp) !=
8189                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8190                            changedInstallPermission = true;
8191                        }
8192                    } break;
8193
8194                    case GRANT_RUNTIME: {
8195                        // Grant previously granted runtime permissions.
8196                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8197                            PermissionState permissionState = origPermissions
8198                                    .getRuntimePermissionState(bp.name, userId);
8199                            final int flags = permissionState != null
8200                                    ? permissionState.getFlags() : 0;
8201                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8202                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8203                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8204                                    // If we cannot put the permission as it was, we have to write.
8205                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8206                                            changedRuntimePermissionUserIds, userId);
8207                                }
8208                            }
8209                            // Propagate the permission flags.
8210                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8211                        }
8212                    } break;
8213
8214                    case GRANT_UPGRADE: {
8215                        // Grant runtime permissions for a previously held install permission.
8216                        PermissionState permissionState = origPermissions
8217                                .getInstallPermissionState(bp.name);
8218                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8219
8220                        if (origPermissions.revokeInstallPermission(bp)
8221                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8222                            // We will be transferring the permission flags, so clear them.
8223                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8224                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8225                            changedInstallPermission = true;
8226                        }
8227
8228                        // If the permission is not to be promoted to runtime we ignore it and
8229                        // also its other flags as they are not applicable to install permissions.
8230                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8231                            for (int userId : currentUserIds) {
8232                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8233                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8234                                    // Transfer the permission flags.
8235                                    permissionsState.updatePermissionFlags(bp, userId,
8236                                            flags, flags);
8237                                    // If we granted the permission, we have to write.
8238                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8239                                            changedRuntimePermissionUserIds, userId);
8240                                }
8241                            }
8242                        }
8243                    } break;
8244
8245                    default: {
8246                        if (packageOfInterest == null
8247                                || packageOfInterest.equals(pkg.packageName)) {
8248                            Slog.w(TAG, "Not granting permission " + perm
8249                                    + " to package " + pkg.packageName
8250                                    + " because it was previously installed without");
8251                        }
8252                    } break;
8253                }
8254            } else {
8255                if (permissionsState.revokeInstallPermission(bp) !=
8256                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8257                    // Also drop the permission flags.
8258                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8259                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8260                    changedInstallPermission = true;
8261                    Slog.i(TAG, "Un-granting permission " + perm
8262                            + " from package " + pkg.packageName
8263                            + " (protectionLevel=" + bp.protectionLevel
8264                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8265                            + ")");
8266                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8267                    // Don't print warning for app op permissions, since it is fine for them
8268                    // not to be granted, there is a UI for the user to decide.
8269                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8270                        Slog.w(TAG, "Not granting permission " + perm
8271                                + " to package " + pkg.packageName
8272                                + " (protectionLevel=" + bp.protectionLevel
8273                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8274                                + ")");
8275                    }
8276                }
8277            }
8278        }
8279
8280        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8281                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8282            // This is the first that we have heard about this package, so the
8283            // permissions we have now selected are fixed until explicitly
8284            // changed.
8285            ps.installPermissionsFixed = true;
8286        }
8287
8288        // Persist the runtime permissions state for users with changes.
8289        for (int userId : changedRuntimePermissionUserIds) {
8290            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
8291        }
8292    }
8293
8294    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8295        boolean allowed = false;
8296        final int NP = PackageParser.NEW_PERMISSIONS.length;
8297        for (int ip=0; ip<NP; ip++) {
8298            final PackageParser.NewPermissionInfo npi
8299                    = PackageParser.NEW_PERMISSIONS[ip];
8300            if (npi.name.equals(perm)
8301                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8302                allowed = true;
8303                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8304                        + pkg.packageName);
8305                break;
8306            }
8307        }
8308        return allowed;
8309    }
8310
8311    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8312            BasePermission bp, PermissionsState origPermissions) {
8313        boolean allowed;
8314        allowed = (compareSignatures(
8315                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8316                        == PackageManager.SIGNATURE_MATCH)
8317                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8318                        == PackageManager.SIGNATURE_MATCH);
8319        if (!allowed && (bp.protectionLevel
8320                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
8321            if (isSystemApp(pkg)) {
8322                // For updated system applications, a system permission
8323                // is granted only if it had been defined by the original application.
8324                if (pkg.isUpdatedSystemApp()) {
8325                    final PackageSetting sysPs = mSettings
8326                            .getDisabledSystemPkgLPr(pkg.packageName);
8327                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8328                        // If the original was granted this permission, we take
8329                        // that grant decision as read and propagate it to the
8330                        // update.
8331                        if (sysPs.isPrivileged()) {
8332                            allowed = true;
8333                        }
8334                    } else {
8335                        // The system apk may have been updated with an older
8336                        // version of the one on the data partition, but which
8337                        // granted a new system permission that it didn't have
8338                        // before.  In this case we do want to allow the app to
8339                        // now get the new permission if the ancestral apk is
8340                        // privileged to get it.
8341                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
8342                            for (int j=0;
8343                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
8344                                if (perm.equals(
8345                                        sysPs.pkg.requestedPermissions.get(j))) {
8346                                    allowed = true;
8347                                    break;
8348                                }
8349                            }
8350                        }
8351                    }
8352                } else {
8353                    allowed = isPrivilegedApp(pkg);
8354                }
8355            }
8356        }
8357        if (!allowed && (bp.protectionLevel
8358                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8359            // For development permissions, a development permission
8360            // is granted only if it was already granted.
8361            allowed = origPermissions.hasInstallPermission(perm);
8362        }
8363        return allowed;
8364    }
8365
8366    final class ActivityIntentResolver
8367            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8368        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8369                boolean defaultOnly, int userId) {
8370            if (!sUserManager.exists(userId)) return null;
8371            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8372            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8373        }
8374
8375        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8376                int userId) {
8377            if (!sUserManager.exists(userId)) return null;
8378            mFlags = flags;
8379            return super.queryIntent(intent, resolvedType,
8380                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8381        }
8382
8383        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8384                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8385            if (!sUserManager.exists(userId)) return null;
8386            if (packageActivities == null) {
8387                return null;
8388            }
8389            mFlags = flags;
8390            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8391            final int N = packageActivities.size();
8392            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8393                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8394
8395            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8396            for (int i = 0; i < N; ++i) {
8397                intentFilters = packageActivities.get(i).intents;
8398                if (intentFilters != null && intentFilters.size() > 0) {
8399                    PackageParser.ActivityIntentInfo[] array =
8400                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
8401                    intentFilters.toArray(array);
8402                    listCut.add(array);
8403                }
8404            }
8405            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8406        }
8407
8408        public final void addActivity(PackageParser.Activity a, String type) {
8409            final boolean systemApp = a.info.applicationInfo.isSystemApp();
8410            mActivities.put(a.getComponentName(), a);
8411            if (DEBUG_SHOW_INFO)
8412                Log.v(
8413                TAG, "  " + type + " " +
8414                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8415            if (DEBUG_SHOW_INFO)
8416                Log.v(TAG, "    Class=" + a.info.name);
8417            final int NI = a.intents.size();
8418            for (int j=0; j<NI; j++) {
8419                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8420                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
8421                    intent.setPriority(0);
8422                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
8423                            + a.className + " with priority > 0, forcing to 0");
8424                }
8425                if (DEBUG_SHOW_INFO) {
8426                    Log.v(TAG, "    IntentFilter:");
8427                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8428                }
8429                if (!intent.debugCheck()) {
8430                    Log.w(TAG, "==> For Activity " + a.info.name);
8431                }
8432                addFilter(intent);
8433            }
8434        }
8435
8436        public final void removeActivity(PackageParser.Activity a, String type) {
8437            mActivities.remove(a.getComponentName());
8438            if (DEBUG_SHOW_INFO) {
8439                Log.v(TAG, "  " + type + " "
8440                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
8441                                : a.info.name) + ":");
8442                Log.v(TAG, "    Class=" + a.info.name);
8443            }
8444            final int NI = a.intents.size();
8445            for (int j=0; j<NI; j++) {
8446                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8447                if (DEBUG_SHOW_INFO) {
8448                    Log.v(TAG, "    IntentFilter:");
8449                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8450                }
8451                removeFilter(intent);
8452            }
8453        }
8454
8455        @Override
8456        protected boolean allowFilterResult(
8457                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
8458            ActivityInfo filterAi = filter.activity.info;
8459            for (int i=dest.size()-1; i>=0; i--) {
8460                ActivityInfo destAi = dest.get(i).activityInfo;
8461                if (destAi.name == filterAi.name
8462                        && destAi.packageName == filterAi.packageName) {
8463                    return false;
8464                }
8465            }
8466            return true;
8467        }
8468
8469        @Override
8470        protected ActivityIntentInfo[] newArray(int size) {
8471            return new ActivityIntentInfo[size];
8472        }
8473
8474        @Override
8475        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
8476            if (!sUserManager.exists(userId)) return true;
8477            PackageParser.Package p = filter.activity.owner;
8478            if (p != null) {
8479                PackageSetting ps = (PackageSetting)p.mExtras;
8480                if (ps != null) {
8481                    // System apps are never considered stopped for purposes of
8482                    // filtering, because there may be no way for the user to
8483                    // actually re-launch them.
8484                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
8485                            && ps.getStopped(userId);
8486                }
8487            }
8488            return false;
8489        }
8490
8491        @Override
8492        protected boolean isPackageForFilter(String packageName,
8493                PackageParser.ActivityIntentInfo info) {
8494            return packageName.equals(info.activity.owner.packageName);
8495        }
8496
8497        @Override
8498        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
8499                int match, int userId) {
8500            if (!sUserManager.exists(userId)) return null;
8501            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
8502                return null;
8503            }
8504            final PackageParser.Activity activity = info.activity;
8505            if (mSafeMode && (activity.info.applicationInfo.flags
8506                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8507                return null;
8508            }
8509            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
8510            if (ps == null) {
8511                return null;
8512            }
8513            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
8514                    ps.readUserState(userId), userId);
8515            if (ai == null) {
8516                return null;
8517            }
8518            final ResolveInfo res = new ResolveInfo();
8519            res.activityInfo = ai;
8520            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8521                res.filter = info;
8522            }
8523            if (info != null) {
8524                res.handleAllWebDataURI = info.handleAllWebDataURI();
8525            }
8526            res.priority = info.getPriority();
8527            res.preferredOrder = activity.owner.mPreferredOrder;
8528            //System.out.println("Result: " + res.activityInfo.className +
8529            //                   " = " + res.priority);
8530            res.match = match;
8531            res.isDefault = info.hasDefault;
8532            res.labelRes = info.labelRes;
8533            res.nonLocalizedLabel = info.nonLocalizedLabel;
8534            if (userNeedsBadging(userId)) {
8535                res.noResourceId = true;
8536            } else {
8537                res.icon = info.icon;
8538            }
8539            res.iconResourceId = info.icon;
8540            res.system = res.activityInfo.applicationInfo.isSystemApp();
8541            return res;
8542        }
8543
8544        @Override
8545        protected void sortResults(List<ResolveInfo> results) {
8546            Collections.sort(results, mResolvePrioritySorter);
8547        }
8548
8549        @Override
8550        protected void dumpFilter(PrintWriter out, String prefix,
8551                PackageParser.ActivityIntentInfo filter) {
8552            out.print(prefix); out.print(
8553                    Integer.toHexString(System.identityHashCode(filter.activity)));
8554                    out.print(' ');
8555                    filter.activity.printComponentShortName(out);
8556                    out.print(" filter ");
8557                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8558        }
8559
8560        @Override
8561        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
8562            return filter.activity;
8563        }
8564
8565        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8566            PackageParser.Activity activity = (PackageParser.Activity)label;
8567            out.print(prefix); out.print(
8568                    Integer.toHexString(System.identityHashCode(activity)));
8569                    out.print(' ');
8570                    activity.printComponentShortName(out);
8571            if (count > 1) {
8572                out.print(" ("); out.print(count); out.print(" filters)");
8573            }
8574            out.println();
8575        }
8576
8577//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8578//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8579//            final List<ResolveInfo> retList = Lists.newArrayList();
8580//            while (i.hasNext()) {
8581//                final ResolveInfo resolveInfo = i.next();
8582//                if (isEnabledLP(resolveInfo.activityInfo)) {
8583//                    retList.add(resolveInfo);
8584//                }
8585//            }
8586//            return retList;
8587//        }
8588
8589        // Keys are String (activity class name), values are Activity.
8590        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
8591                = new ArrayMap<ComponentName, PackageParser.Activity>();
8592        private int mFlags;
8593    }
8594
8595    private final class ServiceIntentResolver
8596            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
8597        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8598                boolean defaultOnly, int userId) {
8599            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8600            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8601        }
8602
8603        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8604                int userId) {
8605            if (!sUserManager.exists(userId)) return null;
8606            mFlags = flags;
8607            return super.queryIntent(intent, resolvedType,
8608                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8609        }
8610
8611        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8612                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
8613            if (!sUserManager.exists(userId)) return null;
8614            if (packageServices == null) {
8615                return null;
8616            }
8617            mFlags = flags;
8618            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8619            final int N = packageServices.size();
8620            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
8621                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
8622
8623            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
8624            for (int i = 0; i < N; ++i) {
8625                intentFilters = packageServices.get(i).intents;
8626                if (intentFilters != null && intentFilters.size() > 0) {
8627                    PackageParser.ServiceIntentInfo[] array =
8628                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
8629                    intentFilters.toArray(array);
8630                    listCut.add(array);
8631                }
8632            }
8633            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8634        }
8635
8636        public final void addService(PackageParser.Service s) {
8637            mServices.put(s.getComponentName(), s);
8638            if (DEBUG_SHOW_INFO) {
8639                Log.v(TAG, "  "
8640                        + (s.info.nonLocalizedLabel != null
8641                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8642                Log.v(TAG, "    Class=" + s.info.name);
8643            }
8644            final int NI = s.intents.size();
8645            int j;
8646            for (j=0; j<NI; j++) {
8647                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8648                if (DEBUG_SHOW_INFO) {
8649                    Log.v(TAG, "    IntentFilter:");
8650                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8651                }
8652                if (!intent.debugCheck()) {
8653                    Log.w(TAG, "==> For Service " + s.info.name);
8654                }
8655                addFilter(intent);
8656            }
8657        }
8658
8659        public final void removeService(PackageParser.Service s) {
8660            mServices.remove(s.getComponentName());
8661            if (DEBUG_SHOW_INFO) {
8662                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
8663                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8664                Log.v(TAG, "    Class=" + s.info.name);
8665            }
8666            final int NI = s.intents.size();
8667            int j;
8668            for (j=0; j<NI; j++) {
8669                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8670                if (DEBUG_SHOW_INFO) {
8671                    Log.v(TAG, "    IntentFilter:");
8672                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8673                }
8674                removeFilter(intent);
8675            }
8676        }
8677
8678        @Override
8679        protected boolean allowFilterResult(
8680                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
8681            ServiceInfo filterSi = filter.service.info;
8682            for (int i=dest.size()-1; i>=0; i--) {
8683                ServiceInfo destAi = dest.get(i).serviceInfo;
8684                if (destAi.name == filterSi.name
8685                        && destAi.packageName == filterSi.packageName) {
8686                    return false;
8687                }
8688            }
8689            return true;
8690        }
8691
8692        @Override
8693        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
8694            return new PackageParser.ServiceIntentInfo[size];
8695        }
8696
8697        @Override
8698        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
8699            if (!sUserManager.exists(userId)) return true;
8700            PackageParser.Package p = filter.service.owner;
8701            if (p != null) {
8702                PackageSetting ps = (PackageSetting)p.mExtras;
8703                if (ps != null) {
8704                    // System apps are never considered stopped for purposes of
8705                    // filtering, because there may be no way for the user to
8706                    // actually re-launch them.
8707                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8708                            && ps.getStopped(userId);
8709                }
8710            }
8711            return false;
8712        }
8713
8714        @Override
8715        protected boolean isPackageForFilter(String packageName,
8716                PackageParser.ServiceIntentInfo info) {
8717            return packageName.equals(info.service.owner.packageName);
8718        }
8719
8720        @Override
8721        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
8722                int match, int userId) {
8723            if (!sUserManager.exists(userId)) return null;
8724            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
8725            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
8726                return null;
8727            }
8728            final PackageParser.Service service = info.service;
8729            if (mSafeMode && (service.info.applicationInfo.flags
8730                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8731                return null;
8732            }
8733            PackageSetting ps = (PackageSetting) service.owner.mExtras;
8734            if (ps == null) {
8735                return null;
8736            }
8737            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
8738                    ps.readUserState(userId), userId);
8739            if (si == null) {
8740                return null;
8741            }
8742            final ResolveInfo res = new ResolveInfo();
8743            res.serviceInfo = si;
8744            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8745                res.filter = filter;
8746            }
8747            res.priority = info.getPriority();
8748            res.preferredOrder = service.owner.mPreferredOrder;
8749            res.match = match;
8750            res.isDefault = info.hasDefault;
8751            res.labelRes = info.labelRes;
8752            res.nonLocalizedLabel = info.nonLocalizedLabel;
8753            res.icon = info.icon;
8754            res.system = res.serviceInfo.applicationInfo.isSystemApp();
8755            return res;
8756        }
8757
8758        @Override
8759        protected void sortResults(List<ResolveInfo> results) {
8760            Collections.sort(results, mResolvePrioritySorter);
8761        }
8762
8763        @Override
8764        protected void dumpFilter(PrintWriter out, String prefix,
8765                PackageParser.ServiceIntentInfo filter) {
8766            out.print(prefix); out.print(
8767                    Integer.toHexString(System.identityHashCode(filter.service)));
8768                    out.print(' ');
8769                    filter.service.printComponentShortName(out);
8770                    out.print(" filter ");
8771                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8772        }
8773
8774        @Override
8775        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
8776            return filter.service;
8777        }
8778
8779        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8780            PackageParser.Service service = (PackageParser.Service)label;
8781            out.print(prefix); out.print(
8782                    Integer.toHexString(System.identityHashCode(service)));
8783                    out.print(' ');
8784                    service.printComponentShortName(out);
8785            if (count > 1) {
8786                out.print(" ("); out.print(count); out.print(" filters)");
8787            }
8788            out.println();
8789        }
8790
8791//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8792//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8793//            final List<ResolveInfo> retList = Lists.newArrayList();
8794//            while (i.hasNext()) {
8795//                final ResolveInfo resolveInfo = (ResolveInfo) i;
8796//                if (isEnabledLP(resolveInfo.serviceInfo)) {
8797//                    retList.add(resolveInfo);
8798//                }
8799//            }
8800//            return retList;
8801//        }
8802
8803        // Keys are String (activity class name), values are Activity.
8804        private final ArrayMap<ComponentName, PackageParser.Service> mServices
8805                = new ArrayMap<ComponentName, PackageParser.Service>();
8806        private int mFlags;
8807    };
8808
8809    private final class ProviderIntentResolver
8810            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
8811        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8812                boolean defaultOnly, int userId) {
8813            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8814            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8815        }
8816
8817        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8818                int userId) {
8819            if (!sUserManager.exists(userId))
8820                return null;
8821            mFlags = flags;
8822            return super.queryIntent(intent, resolvedType,
8823                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8824        }
8825
8826        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8827                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
8828            if (!sUserManager.exists(userId))
8829                return null;
8830            if (packageProviders == null) {
8831                return null;
8832            }
8833            mFlags = flags;
8834            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
8835            final int N = packageProviders.size();
8836            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
8837                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
8838
8839            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
8840            for (int i = 0; i < N; ++i) {
8841                intentFilters = packageProviders.get(i).intents;
8842                if (intentFilters != null && intentFilters.size() > 0) {
8843                    PackageParser.ProviderIntentInfo[] array =
8844                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
8845                    intentFilters.toArray(array);
8846                    listCut.add(array);
8847                }
8848            }
8849            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8850        }
8851
8852        public final void addProvider(PackageParser.Provider p) {
8853            if (mProviders.containsKey(p.getComponentName())) {
8854                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
8855                return;
8856            }
8857
8858            mProviders.put(p.getComponentName(), p);
8859            if (DEBUG_SHOW_INFO) {
8860                Log.v(TAG, "  "
8861                        + (p.info.nonLocalizedLabel != null
8862                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
8863                Log.v(TAG, "    Class=" + p.info.name);
8864            }
8865            final int NI = p.intents.size();
8866            int j;
8867            for (j = 0; j < NI; j++) {
8868                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
8869                if (DEBUG_SHOW_INFO) {
8870                    Log.v(TAG, "    IntentFilter:");
8871                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8872                }
8873                if (!intent.debugCheck()) {
8874                    Log.w(TAG, "==> For Provider " + p.info.name);
8875                }
8876                addFilter(intent);
8877            }
8878        }
8879
8880        public final void removeProvider(PackageParser.Provider p) {
8881            mProviders.remove(p.getComponentName());
8882            if (DEBUG_SHOW_INFO) {
8883                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
8884                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
8885                Log.v(TAG, "    Class=" + p.info.name);
8886            }
8887            final int NI = p.intents.size();
8888            int j;
8889            for (j = 0; j < NI; j++) {
8890                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
8891                if (DEBUG_SHOW_INFO) {
8892                    Log.v(TAG, "    IntentFilter:");
8893                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8894                }
8895                removeFilter(intent);
8896            }
8897        }
8898
8899        @Override
8900        protected boolean allowFilterResult(
8901                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
8902            ProviderInfo filterPi = filter.provider.info;
8903            for (int i = dest.size() - 1; i >= 0; i--) {
8904                ProviderInfo destPi = dest.get(i).providerInfo;
8905                if (destPi.name == filterPi.name
8906                        && destPi.packageName == filterPi.packageName) {
8907                    return false;
8908                }
8909            }
8910            return true;
8911        }
8912
8913        @Override
8914        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
8915            return new PackageParser.ProviderIntentInfo[size];
8916        }
8917
8918        @Override
8919        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
8920            if (!sUserManager.exists(userId))
8921                return true;
8922            PackageParser.Package p = filter.provider.owner;
8923            if (p != null) {
8924                PackageSetting ps = (PackageSetting) p.mExtras;
8925                if (ps != null) {
8926                    // System apps are never considered stopped for purposes of
8927                    // filtering, because there may be no way for the user to
8928                    // actually re-launch them.
8929                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8930                            && ps.getStopped(userId);
8931                }
8932            }
8933            return false;
8934        }
8935
8936        @Override
8937        protected boolean isPackageForFilter(String packageName,
8938                PackageParser.ProviderIntentInfo info) {
8939            return packageName.equals(info.provider.owner.packageName);
8940        }
8941
8942        @Override
8943        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
8944                int match, int userId) {
8945            if (!sUserManager.exists(userId))
8946                return null;
8947            final PackageParser.ProviderIntentInfo info = filter;
8948            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
8949                return null;
8950            }
8951            final PackageParser.Provider provider = info.provider;
8952            if (mSafeMode && (provider.info.applicationInfo.flags
8953                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
8954                return null;
8955            }
8956            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
8957            if (ps == null) {
8958                return null;
8959            }
8960            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
8961                    ps.readUserState(userId), userId);
8962            if (pi == null) {
8963                return null;
8964            }
8965            final ResolveInfo res = new ResolveInfo();
8966            res.providerInfo = pi;
8967            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
8968                res.filter = filter;
8969            }
8970            res.priority = info.getPriority();
8971            res.preferredOrder = provider.owner.mPreferredOrder;
8972            res.match = match;
8973            res.isDefault = info.hasDefault;
8974            res.labelRes = info.labelRes;
8975            res.nonLocalizedLabel = info.nonLocalizedLabel;
8976            res.icon = info.icon;
8977            res.system = res.providerInfo.applicationInfo.isSystemApp();
8978            return res;
8979        }
8980
8981        @Override
8982        protected void sortResults(List<ResolveInfo> results) {
8983            Collections.sort(results, mResolvePrioritySorter);
8984        }
8985
8986        @Override
8987        protected void dumpFilter(PrintWriter out, String prefix,
8988                PackageParser.ProviderIntentInfo filter) {
8989            out.print(prefix);
8990            out.print(
8991                    Integer.toHexString(System.identityHashCode(filter.provider)));
8992            out.print(' ');
8993            filter.provider.printComponentShortName(out);
8994            out.print(" filter ");
8995            out.println(Integer.toHexString(System.identityHashCode(filter)));
8996        }
8997
8998        @Override
8999        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9000            return filter.provider;
9001        }
9002
9003        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9004            PackageParser.Provider provider = (PackageParser.Provider)label;
9005            out.print(prefix); out.print(
9006                    Integer.toHexString(System.identityHashCode(provider)));
9007                    out.print(' ');
9008                    provider.printComponentShortName(out);
9009            if (count > 1) {
9010                out.print(" ("); out.print(count); out.print(" filters)");
9011            }
9012            out.println();
9013        }
9014
9015        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9016                = new ArrayMap<ComponentName, PackageParser.Provider>();
9017        private int mFlags;
9018    };
9019
9020    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9021            new Comparator<ResolveInfo>() {
9022        public int compare(ResolveInfo r1, ResolveInfo r2) {
9023            int v1 = r1.priority;
9024            int v2 = r2.priority;
9025            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9026            if (v1 != v2) {
9027                return (v1 > v2) ? -1 : 1;
9028            }
9029            v1 = r1.preferredOrder;
9030            v2 = r2.preferredOrder;
9031            if (v1 != v2) {
9032                return (v1 > v2) ? -1 : 1;
9033            }
9034            if (r1.isDefault != r2.isDefault) {
9035                return r1.isDefault ? -1 : 1;
9036            }
9037            v1 = r1.match;
9038            v2 = r2.match;
9039            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9040            if (v1 != v2) {
9041                return (v1 > v2) ? -1 : 1;
9042            }
9043            if (r1.system != r2.system) {
9044                return r1.system ? -1 : 1;
9045            }
9046            return 0;
9047        }
9048    };
9049
9050    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9051            new Comparator<ProviderInfo>() {
9052        public int compare(ProviderInfo p1, ProviderInfo p2) {
9053            final int v1 = p1.initOrder;
9054            final int v2 = p2.initOrder;
9055            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9056        }
9057    };
9058
9059    final void sendPackageBroadcast(final String action, final String pkg,
9060            final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
9061            final int[] userIds) {
9062        mHandler.post(new Runnable() {
9063            @Override
9064            public void run() {
9065                try {
9066                    final IActivityManager am = ActivityManagerNative.getDefault();
9067                    if (am == null) return;
9068                    final int[] resolvedUserIds;
9069                    if (userIds == null) {
9070                        resolvedUserIds = am.getRunningUserIds();
9071                    } else {
9072                        resolvedUserIds = userIds;
9073                    }
9074                    for (int id : resolvedUserIds) {
9075                        final Intent intent = new Intent(action,
9076                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9077                        if (extras != null) {
9078                            intent.putExtras(extras);
9079                        }
9080                        if (targetPkg != null) {
9081                            intent.setPackage(targetPkg);
9082                        }
9083                        // Modify the UID when posting to other users
9084                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9085                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9086                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9087                            intent.putExtra(Intent.EXTRA_UID, uid);
9088                        }
9089                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9090                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
9091                        if (DEBUG_BROADCASTS) {
9092                            RuntimeException here = new RuntimeException("here");
9093                            here.fillInStackTrace();
9094                            Slog.d(TAG, "Sending to user " + id + ": "
9095                                    + intent.toShortString(false, true, false, false)
9096                                    + " " + intent.getExtras(), here);
9097                        }
9098                        am.broadcastIntent(null, intent, null, finishedReceiver,
9099                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9100                                null, finishedReceiver != null, false, id);
9101                    }
9102                } catch (RemoteException ex) {
9103                }
9104            }
9105        });
9106    }
9107
9108    /**
9109     * Check if the external storage media is available. This is true if there
9110     * is a mounted external storage medium or if the external storage is
9111     * emulated.
9112     */
9113    private boolean isExternalMediaAvailable() {
9114        return mMediaMounted || Environment.isExternalStorageEmulated();
9115    }
9116
9117    @Override
9118    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9119        // writer
9120        synchronized (mPackages) {
9121            if (!isExternalMediaAvailable()) {
9122                // If the external storage is no longer mounted at this point,
9123                // the caller may not have been able to delete all of this
9124                // packages files and can not delete any more.  Bail.
9125                return null;
9126            }
9127            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9128            if (lastPackage != null) {
9129                pkgs.remove(lastPackage);
9130            }
9131            if (pkgs.size() > 0) {
9132                return pkgs.get(0);
9133            }
9134        }
9135        return null;
9136    }
9137
9138    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9139        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9140                userId, andCode ? 1 : 0, packageName);
9141        if (mSystemReady) {
9142            msg.sendToTarget();
9143        } else {
9144            if (mPostSystemReadyMessages == null) {
9145                mPostSystemReadyMessages = new ArrayList<>();
9146            }
9147            mPostSystemReadyMessages.add(msg);
9148        }
9149    }
9150
9151    void startCleaningPackages() {
9152        // reader
9153        synchronized (mPackages) {
9154            if (!isExternalMediaAvailable()) {
9155                return;
9156            }
9157            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9158                return;
9159            }
9160        }
9161        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9162        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9163        IActivityManager am = ActivityManagerNative.getDefault();
9164        if (am != null) {
9165            try {
9166                am.startService(null, intent, null, UserHandle.USER_OWNER);
9167            } catch (RemoteException e) {
9168            }
9169        }
9170    }
9171
9172    @Override
9173    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9174            int installFlags, String installerPackageName, VerificationParams verificationParams,
9175            String packageAbiOverride) {
9176        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9177                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9178    }
9179
9180    @Override
9181    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9182            int installFlags, String installerPackageName, VerificationParams verificationParams,
9183            String packageAbiOverride, int userId) {
9184        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9185
9186        final int callingUid = Binder.getCallingUid();
9187        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9188
9189        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9190            try {
9191                if (observer != null) {
9192                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9193                }
9194            } catch (RemoteException re) {
9195            }
9196            return;
9197        }
9198
9199        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9200            installFlags |= PackageManager.INSTALL_FROM_ADB;
9201
9202        } else {
9203            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9204            // about installerPackageName.
9205
9206            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9207            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9208        }
9209
9210        UserHandle user;
9211        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9212            user = UserHandle.ALL;
9213        } else {
9214            user = new UserHandle(userId);
9215        }
9216
9217        // Only system components can circumvent runtime permissions when installing.
9218        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9219                && mContext.checkCallingOrSelfPermission(Manifest.permission
9220                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9221            throw new SecurityException("You need the "
9222                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9223                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9224        }
9225
9226        verificationParams.setInstallerUid(callingUid);
9227
9228        final File originFile = new File(originPath);
9229        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9230
9231        final Message msg = mHandler.obtainMessage(INIT_COPY);
9232        msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName,
9233                null, verificationParams, user, packageAbiOverride);
9234        mHandler.sendMessage(msg);
9235    }
9236
9237    void installStage(String packageName, File stagedDir, String stagedCid,
9238            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
9239            String installerPackageName, int installerUid, UserHandle user) {
9240        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
9241                params.referrerUri, installerUid, null);
9242        verifParams.setInstallerUid(installerUid);
9243
9244        final OriginInfo origin;
9245        if (stagedDir != null) {
9246            origin = OriginInfo.fromStagedFile(stagedDir);
9247        } else {
9248            origin = OriginInfo.fromStagedContainer(stagedCid);
9249        }
9250
9251        final Message msg = mHandler.obtainMessage(INIT_COPY);
9252        msg.obj = new InstallParams(origin, null, observer, params.installFlags,
9253                installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride);
9254        mHandler.sendMessage(msg);
9255    }
9256
9257    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
9258        Bundle extras = new Bundle(1);
9259        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
9260
9261        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
9262                packageName, extras, null, null, new int[] {userId});
9263        try {
9264            IActivityManager am = ActivityManagerNative.getDefault();
9265            final boolean isSystem =
9266                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
9267            if (isSystem && am.isUserRunning(userId, false)) {
9268                // The just-installed/enabled app is bundled on the system, so presumed
9269                // to be able to run automatically without needing an explicit launch.
9270                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
9271                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
9272                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
9273                        .setPackage(packageName);
9274                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
9275                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
9276            }
9277        } catch (RemoteException e) {
9278            // shouldn't happen
9279            Slog.w(TAG, "Unable to bootstrap installed package", e);
9280        }
9281    }
9282
9283    @Override
9284    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9285            int userId) {
9286        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9287        PackageSetting pkgSetting;
9288        final int uid = Binder.getCallingUid();
9289        enforceCrossUserPermission(uid, userId, true, true,
9290                "setApplicationHiddenSetting for user " + userId);
9291
9292        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9293            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9294            return false;
9295        }
9296
9297        long callingId = Binder.clearCallingIdentity();
9298        try {
9299            boolean sendAdded = false;
9300            boolean sendRemoved = false;
9301            // writer
9302            synchronized (mPackages) {
9303                pkgSetting = mSettings.mPackages.get(packageName);
9304                if (pkgSetting == null) {
9305                    return false;
9306                }
9307                if (pkgSetting.getHidden(userId) != hidden) {
9308                    pkgSetting.setHidden(hidden, userId);
9309                    mSettings.writePackageRestrictionsLPr(userId);
9310                    if (hidden) {
9311                        sendRemoved = true;
9312                    } else {
9313                        sendAdded = true;
9314                    }
9315                }
9316            }
9317            if (sendAdded) {
9318                sendPackageAddedForUser(packageName, pkgSetting, userId);
9319                return true;
9320            }
9321            if (sendRemoved) {
9322                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
9323                        "hiding pkg");
9324                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
9325            }
9326        } finally {
9327            Binder.restoreCallingIdentity(callingId);
9328        }
9329        return false;
9330    }
9331
9332    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9333            int userId) {
9334        final PackageRemovedInfo info = new PackageRemovedInfo();
9335        info.removedPackage = packageName;
9336        info.removedUsers = new int[] {userId};
9337        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9338        info.sendBroadcast(false, false, false);
9339    }
9340
9341    /**
9342     * Returns true if application is not found or there was an error. Otherwise it returns
9343     * the hidden state of the package for the given user.
9344     */
9345    @Override
9346    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9347        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9348        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9349                false, "getApplicationHidden for user " + userId);
9350        PackageSetting pkgSetting;
9351        long callingId = Binder.clearCallingIdentity();
9352        try {
9353            // writer
9354            synchronized (mPackages) {
9355                pkgSetting = mSettings.mPackages.get(packageName);
9356                if (pkgSetting == null) {
9357                    return true;
9358                }
9359                return pkgSetting.getHidden(userId);
9360            }
9361        } finally {
9362            Binder.restoreCallingIdentity(callingId);
9363        }
9364    }
9365
9366    /**
9367     * @hide
9368     */
9369    @Override
9370    public int installExistingPackageAsUser(String packageName, int userId) {
9371        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9372                null);
9373        PackageSetting pkgSetting;
9374        final int uid = Binder.getCallingUid();
9375        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9376                + userId);
9377        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9378            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9379        }
9380
9381        long callingId = Binder.clearCallingIdentity();
9382        try {
9383            boolean sendAdded = false;
9384
9385            // writer
9386            synchronized (mPackages) {
9387                pkgSetting = mSettings.mPackages.get(packageName);
9388                if (pkgSetting == null) {
9389                    return PackageManager.INSTALL_FAILED_INVALID_URI;
9390                }
9391                if (!pkgSetting.getInstalled(userId)) {
9392                    pkgSetting.setInstalled(true, userId);
9393                    pkgSetting.setHidden(false, userId);
9394                    mSettings.writePackageRestrictionsLPr(userId);
9395                    sendAdded = true;
9396                }
9397            }
9398
9399            if (sendAdded) {
9400                sendPackageAddedForUser(packageName, pkgSetting, userId);
9401            }
9402        } finally {
9403            Binder.restoreCallingIdentity(callingId);
9404        }
9405
9406        return PackageManager.INSTALL_SUCCEEDED;
9407    }
9408
9409    boolean isUserRestricted(int userId, String restrictionKey) {
9410        Bundle restrictions = sUserManager.getUserRestrictions(userId);
9411        if (restrictions.getBoolean(restrictionKey, false)) {
9412            Log.w(TAG, "User is restricted: " + restrictionKey);
9413            return true;
9414        }
9415        return false;
9416    }
9417
9418    @Override
9419    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
9420        mContext.enforceCallingOrSelfPermission(
9421                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9422                "Only package verification agents can verify applications");
9423
9424        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9425        final PackageVerificationResponse response = new PackageVerificationResponse(
9426                verificationCode, Binder.getCallingUid());
9427        msg.arg1 = id;
9428        msg.obj = response;
9429        mHandler.sendMessage(msg);
9430    }
9431
9432    @Override
9433    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
9434            long millisecondsToDelay) {
9435        mContext.enforceCallingOrSelfPermission(
9436                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9437                "Only package verification agents can extend verification timeouts");
9438
9439        final PackageVerificationState state = mPendingVerification.get(id);
9440        final PackageVerificationResponse response = new PackageVerificationResponse(
9441                verificationCodeAtTimeout, Binder.getCallingUid());
9442
9443        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
9444            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
9445        }
9446        if (millisecondsToDelay < 0) {
9447            millisecondsToDelay = 0;
9448        }
9449        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9450                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9451            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9452        }
9453
9454        if ((state != null) && !state.timeoutExtended()) {
9455            state.extendTimeout();
9456
9457            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9458            msg.arg1 = id;
9459            msg.obj = response;
9460            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
9461        }
9462    }
9463
9464    private void broadcastPackageVerified(int verificationId, Uri packageUri,
9465            int verificationCode, UserHandle user) {
9466        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
9467        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
9468        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9469        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9470        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
9471
9472        mContext.sendBroadcastAsUser(intent, user,
9473                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
9474    }
9475
9476    private ComponentName matchComponentForVerifier(String packageName,
9477            List<ResolveInfo> receivers) {
9478        ActivityInfo targetReceiver = null;
9479
9480        final int NR = receivers.size();
9481        for (int i = 0; i < NR; i++) {
9482            final ResolveInfo info = receivers.get(i);
9483            if (info.activityInfo == null) {
9484                continue;
9485            }
9486
9487            if (packageName.equals(info.activityInfo.packageName)) {
9488                targetReceiver = info.activityInfo;
9489                break;
9490            }
9491        }
9492
9493        if (targetReceiver == null) {
9494            return null;
9495        }
9496
9497        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
9498    }
9499
9500    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
9501            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
9502        if (pkgInfo.verifiers.length == 0) {
9503            return null;
9504        }
9505
9506        final int N = pkgInfo.verifiers.length;
9507        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
9508        for (int i = 0; i < N; i++) {
9509            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
9510
9511            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
9512                    receivers);
9513            if (comp == null) {
9514                continue;
9515            }
9516
9517            final int verifierUid = getUidForVerifier(verifierInfo);
9518            if (verifierUid == -1) {
9519                continue;
9520            }
9521
9522            if (DEBUG_VERIFY) {
9523                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
9524                        + " with the correct signature");
9525            }
9526            sufficientVerifiers.add(comp);
9527            verificationState.addSufficientVerifier(verifierUid);
9528        }
9529
9530        return sufficientVerifiers;
9531    }
9532
9533    private int getUidForVerifier(VerifierInfo verifierInfo) {
9534        synchronized (mPackages) {
9535            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
9536            if (pkg == null) {
9537                return -1;
9538            } else if (pkg.mSignatures.length != 1) {
9539                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9540                        + " has more than one signature; ignoring");
9541                return -1;
9542            }
9543
9544            /*
9545             * If the public key of the package's signature does not match
9546             * our expected public key, then this is a different package and
9547             * we should skip.
9548             */
9549
9550            final byte[] expectedPublicKey;
9551            try {
9552                final Signature verifierSig = pkg.mSignatures[0];
9553                final PublicKey publicKey = verifierSig.getPublicKey();
9554                expectedPublicKey = publicKey.getEncoded();
9555            } catch (CertificateException e) {
9556                return -1;
9557            }
9558
9559            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
9560
9561            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
9562                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9563                        + " does not have the expected public key; ignoring");
9564                return -1;
9565            }
9566
9567            return pkg.applicationInfo.uid;
9568        }
9569    }
9570
9571    @Override
9572    public void finishPackageInstall(int token) {
9573        enforceSystemOrRoot("Only the system is allowed to finish installs");
9574
9575        if (DEBUG_INSTALL) {
9576            Slog.v(TAG, "BM finishing package install for " + token);
9577        }
9578
9579        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9580        mHandler.sendMessage(msg);
9581    }
9582
9583    /**
9584     * Get the verification agent timeout.
9585     *
9586     * @return verification timeout in milliseconds
9587     */
9588    private long getVerificationTimeout() {
9589        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
9590                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
9591                DEFAULT_VERIFICATION_TIMEOUT);
9592    }
9593
9594    /**
9595     * Get the default verification agent response code.
9596     *
9597     * @return default verification response code
9598     */
9599    private int getDefaultVerificationResponse() {
9600        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9601                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
9602                DEFAULT_VERIFICATION_RESPONSE);
9603    }
9604
9605    /**
9606     * Check whether or not package verification has been enabled.
9607     *
9608     * @return true if verification should be performed
9609     */
9610    private boolean isVerificationEnabled(int userId, int installFlags) {
9611        if (!DEFAULT_VERIFY_ENABLE) {
9612            return false;
9613        }
9614
9615        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
9616
9617        // Check if installing from ADB
9618        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
9619            // Do not run verification in a test harness environment
9620            if (ActivityManager.isRunningInTestHarness()) {
9621                return false;
9622            }
9623            if (ensureVerifyAppsEnabled) {
9624                return true;
9625            }
9626            // Check if the developer does not want package verification for ADB installs
9627            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9628                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
9629                return false;
9630            }
9631        }
9632
9633        if (ensureVerifyAppsEnabled) {
9634            return true;
9635        }
9636
9637        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9638                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9639    }
9640
9641    @Override
9642    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9643            throws RemoteException {
9644        mContext.enforceCallingOrSelfPermission(
9645                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9646                "Only intentfilter verification agents can verify applications");
9647
9648        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9649        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9650                Binder.getCallingUid(), verificationCode, failedDomains);
9651        msg.arg1 = id;
9652        msg.obj = response;
9653        mHandler.sendMessage(msg);
9654    }
9655
9656    @Override
9657    public int getIntentVerificationStatus(String packageName, int userId) {
9658        synchronized (mPackages) {
9659            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
9660        }
9661    }
9662
9663    @Override
9664    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
9665        mContext.enforceCallingOrSelfPermission(
9666                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9667
9668        boolean result = false;
9669        synchronized (mPackages) {
9670            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
9671        }
9672        if (result) {
9673            scheduleWritePackageRestrictionsLocked(userId);
9674        }
9675        return result;
9676    }
9677
9678    @Override
9679    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
9680        synchronized (mPackages) {
9681            return mSettings.getIntentFilterVerificationsLPr(packageName);
9682        }
9683    }
9684
9685    @Override
9686    public List<IntentFilter> getAllIntentFilters(String packageName) {
9687        if (TextUtils.isEmpty(packageName)) {
9688            return Collections.<IntentFilter>emptyList();
9689        }
9690        synchronized (mPackages) {
9691            PackageParser.Package pkg = mPackages.get(packageName);
9692            if (pkg == null || pkg.activities == null) {
9693                return Collections.<IntentFilter>emptyList();
9694            }
9695            final int count = pkg.activities.size();
9696            ArrayList<IntentFilter> result = new ArrayList<>();
9697            for (int n=0; n<count; n++) {
9698                PackageParser.Activity activity = pkg.activities.get(n);
9699                if (activity.intents != null || activity.intents.size() > 0) {
9700                    result.addAll(activity.intents);
9701                }
9702            }
9703            return result;
9704        }
9705    }
9706
9707    @Override
9708    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
9709        mContext.enforceCallingOrSelfPermission(
9710                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9711
9712        synchronized (mPackages) {
9713            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
9714            if (packageName != null) {
9715                result |= updateIntentVerificationStatus(packageName,
9716                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
9717                        UserHandle.myUserId());
9718                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
9719                        packageName, userId);
9720            }
9721            return result;
9722        }
9723    }
9724
9725    @Override
9726    public String getDefaultBrowserPackageName(int userId) {
9727        synchronized (mPackages) {
9728            return mSettings.getDefaultBrowserPackageNameLPw(userId);
9729        }
9730    }
9731
9732    /**
9733     * Get the "allow unknown sources" setting.
9734     *
9735     * @return the current "allow unknown sources" setting
9736     */
9737    private int getUnknownSourcesSettings() {
9738        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9739                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
9740                -1);
9741    }
9742
9743    @Override
9744    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
9745        final int uid = Binder.getCallingUid();
9746        // writer
9747        synchronized (mPackages) {
9748            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
9749            if (targetPackageSetting == null) {
9750                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
9751            }
9752
9753            PackageSetting installerPackageSetting;
9754            if (installerPackageName != null) {
9755                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
9756                if (installerPackageSetting == null) {
9757                    throw new IllegalArgumentException("Unknown installer package: "
9758                            + installerPackageName);
9759                }
9760            } else {
9761                installerPackageSetting = null;
9762            }
9763
9764            Signature[] callerSignature;
9765            Object obj = mSettings.getUserIdLPr(uid);
9766            if (obj != null) {
9767                if (obj instanceof SharedUserSetting) {
9768                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
9769                } else if (obj instanceof PackageSetting) {
9770                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
9771                } else {
9772                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
9773                }
9774            } else {
9775                throw new SecurityException("Unknown calling uid " + uid);
9776            }
9777
9778            // Verify: can't set installerPackageName to a package that is
9779            // not signed with the same cert as the caller.
9780            if (installerPackageSetting != null) {
9781                if (compareSignatures(callerSignature,
9782                        installerPackageSetting.signatures.mSignatures)
9783                        != PackageManager.SIGNATURE_MATCH) {
9784                    throw new SecurityException(
9785                            "Caller does not have same cert as new installer package "
9786                            + installerPackageName);
9787                }
9788            }
9789
9790            // Verify: if target already has an installer package, it must
9791            // be signed with the same cert as the caller.
9792            if (targetPackageSetting.installerPackageName != null) {
9793                PackageSetting setting = mSettings.mPackages.get(
9794                        targetPackageSetting.installerPackageName);
9795                // If the currently set package isn't valid, then it's always
9796                // okay to change it.
9797                if (setting != null) {
9798                    if (compareSignatures(callerSignature,
9799                            setting.signatures.mSignatures)
9800                            != PackageManager.SIGNATURE_MATCH) {
9801                        throw new SecurityException(
9802                                "Caller does not have same cert as old installer package "
9803                                + targetPackageSetting.installerPackageName);
9804                    }
9805                }
9806            }
9807
9808            // Okay!
9809            targetPackageSetting.installerPackageName = installerPackageName;
9810            scheduleWriteSettingsLocked();
9811        }
9812    }
9813
9814    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
9815        // Queue up an async operation since the package installation may take a little while.
9816        mHandler.post(new Runnable() {
9817            public void run() {
9818                mHandler.removeCallbacks(this);
9819                 // Result object to be returned
9820                PackageInstalledInfo res = new PackageInstalledInfo();
9821                res.returnCode = currentStatus;
9822                res.uid = -1;
9823                res.pkg = null;
9824                res.removedInfo = new PackageRemovedInfo();
9825                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
9826                    args.doPreInstall(res.returnCode);
9827                    synchronized (mInstallLock) {
9828                        installPackageLI(args, res);
9829                    }
9830                    args.doPostInstall(res.returnCode, res.uid);
9831                }
9832
9833                // A restore should be performed at this point if (a) the install
9834                // succeeded, (b) the operation is not an update, and (c) the new
9835                // package has not opted out of backup participation.
9836                final boolean update = res.removedInfo.removedPackage != null;
9837                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
9838                boolean doRestore = !update
9839                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
9840
9841                // Set up the post-install work request bookkeeping.  This will be used
9842                // and cleaned up by the post-install event handling regardless of whether
9843                // there's a restore pass performed.  Token values are >= 1.
9844                int token;
9845                if (mNextInstallToken < 0) mNextInstallToken = 1;
9846                token = mNextInstallToken++;
9847
9848                PostInstallData data = new PostInstallData(args, res);
9849                mRunningInstalls.put(token, data);
9850                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
9851
9852                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
9853                    // Pass responsibility to the Backup Manager.  It will perform a
9854                    // restore if appropriate, then pass responsibility back to the
9855                    // Package Manager to run the post-install observer callbacks
9856                    // and broadcasts.
9857                    IBackupManager bm = IBackupManager.Stub.asInterface(
9858                            ServiceManager.getService(Context.BACKUP_SERVICE));
9859                    if (bm != null) {
9860                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
9861                                + " to BM for possible restore");
9862                        try {
9863                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
9864                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
9865                            } else {
9866                                doRestore = false;
9867                            }
9868                        } catch (RemoteException e) {
9869                            // can't happen; the backup manager is local
9870                        } catch (Exception e) {
9871                            Slog.e(TAG, "Exception trying to enqueue restore", e);
9872                            doRestore = false;
9873                        }
9874                    } else {
9875                        Slog.e(TAG, "Backup Manager not found!");
9876                        doRestore = false;
9877                    }
9878                }
9879
9880                if (!doRestore) {
9881                    // No restore possible, or the Backup Manager was mysteriously not
9882                    // available -- just fire the post-install work request directly.
9883                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
9884                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9885                    mHandler.sendMessage(msg);
9886                }
9887            }
9888        });
9889    }
9890
9891    private abstract class HandlerParams {
9892        private static final int MAX_RETRIES = 4;
9893
9894        /**
9895         * Number of times startCopy() has been attempted and had a non-fatal
9896         * error.
9897         */
9898        private int mRetries = 0;
9899
9900        /** User handle for the user requesting the information or installation. */
9901        private final UserHandle mUser;
9902
9903        HandlerParams(UserHandle user) {
9904            mUser = user;
9905        }
9906
9907        UserHandle getUser() {
9908            return mUser;
9909        }
9910
9911        final boolean startCopy() {
9912            boolean res;
9913            try {
9914                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
9915
9916                if (++mRetries > MAX_RETRIES) {
9917                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
9918                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
9919                    handleServiceError();
9920                    return false;
9921                } else {
9922                    handleStartCopy();
9923                    res = true;
9924                }
9925            } catch (RemoteException e) {
9926                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
9927                mHandler.sendEmptyMessage(MCS_RECONNECT);
9928                res = false;
9929            }
9930            handleReturnCode();
9931            return res;
9932        }
9933
9934        final void serviceError() {
9935            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
9936            handleServiceError();
9937            handleReturnCode();
9938        }
9939
9940        abstract void handleStartCopy() throws RemoteException;
9941        abstract void handleServiceError();
9942        abstract void handleReturnCode();
9943    }
9944
9945    class MeasureParams extends HandlerParams {
9946        private final PackageStats mStats;
9947        private boolean mSuccess;
9948
9949        private final IPackageStatsObserver mObserver;
9950
9951        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
9952            super(new UserHandle(stats.userHandle));
9953            mObserver = observer;
9954            mStats = stats;
9955        }
9956
9957        @Override
9958        public String toString() {
9959            return "MeasureParams{"
9960                + Integer.toHexString(System.identityHashCode(this))
9961                + " " + mStats.packageName + "}";
9962        }
9963
9964        @Override
9965        void handleStartCopy() throws RemoteException {
9966            synchronized (mInstallLock) {
9967                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
9968            }
9969
9970            if (mSuccess) {
9971                final boolean mounted;
9972                if (Environment.isExternalStorageEmulated()) {
9973                    mounted = true;
9974                } else {
9975                    final String status = Environment.getExternalStorageState();
9976                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
9977                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
9978                }
9979
9980                if (mounted) {
9981                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
9982
9983                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
9984                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
9985
9986                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
9987                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
9988
9989                    // Always subtract cache size, since it's a subdirectory
9990                    mStats.externalDataSize -= mStats.externalCacheSize;
9991
9992                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
9993                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
9994
9995                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
9996                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
9997                }
9998            }
9999        }
10000
10001        @Override
10002        void handleReturnCode() {
10003            if (mObserver != null) {
10004                try {
10005                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10006                } catch (RemoteException e) {
10007                    Slog.i(TAG, "Observer no longer exists.");
10008                }
10009            }
10010        }
10011
10012        @Override
10013        void handleServiceError() {
10014            Slog.e(TAG, "Could not measure application " + mStats.packageName
10015                            + " external storage");
10016        }
10017    }
10018
10019    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10020            throws RemoteException {
10021        long result = 0;
10022        for (File path : paths) {
10023            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10024        }
10025        return result;
10026    }
10027
10028    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10029        for (File path : paths) {
10030            try {
10031                mcs.clearDirectory(path.getAbsolutePath());
10032            } catch (RemoteException e) {
10033            }
10034        }
10035    }
10036
10037    static class OriginInfo {
10038        /**
10039         * Location where install is coming from, before it has been
10040         * copied/renamed into place. This could be a single monolithic APK
10041         * file, or a cluster directory. This location may be untrusted.
10042         */
10043        final File file;
10044        final String cid;
10045
10046        /**
10047         * Flag indicating that {@link #file} or {@link #cid} has already been
10048         * staged, meaning downstream users don't need to defensively copy the
10049         * contents.
10050         */
10051        final boolean staged;
10052
10053        /**
10054         * Flag indicating that {@link #file} or {@link #cid} is an already
10055         * installed app that is being moved.
10056         */
10057        final boolean existing;
10058
10059        final String resolvedPath;
10060        final File resolvedFile;
10061
10062        static OriginInfo fromNothing() {
10063            return new OriginInfo(null, null, false, false);
10064        }
10065
10066        static OriginInfo fromUntrustedFile(File file) {
10067            return new OriginInfo(file, null, false, false);
10068        }
10069
10070        static OriginInfo fromExistingFile(File file) {
10071            return new OriginInfo(file, null, false, true);
10072        }
10073
10074        static OriginInfo fromStagedFile(File file) {
10075            return new OriginInfo(file, null, true, false);
10076        }
10077
10078        static OriginInfo fromStagedContainer(String cid) {
10079            return new OriginInfo(null, cid, true, false);
10080        }
10081
10082        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10083            this.file = file;
10084            this.cid = cid;
10085            this.staged = staged;
10086            this.existing = existing;
10087
10088            if (cid != null) {
10089                resolvedPath = PackageHelper.getSdDir(cid);
10090                resolvedFile = new File(resolvedPath);
10091            } else if (file != null) {
10092                resolvedPath = file.getAbsolutePath();
10093                resolvedFile = file;
10094            } else {
10095                resolvedPath = null;
10096                resolvedFile = null;
10097            }
10098        }
10099    }
10100
10101    class MoveInfo {
10102        final int moveId;
10103        final String fromUuid;
10104        final String toUuid;
10105        final String packageName;
10106        final String dataAppName;
10107        final int appId;
10108        final String seinfo;
10109
10110        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10111                String dataAppName, int appId, String seinfo) {
10112            this.moveId = moveId;
10113            this.fromUuid = fromUuid;
10114            this.toUuid = toUuid;
10115            this.packageName = packageName;
10116            this.dataAppName = dataAppName;
10117            this.appId = appId;
10118            this.seinfo = seinfo;
10119        }
10120    }
10121
10122    class InstallParams extends HandlerParams {
10123        final OriginInfo origin;
10124        final MoveInfo move;
10125        final IPackageInstallObserver2 observer;
10126        int installFlags;
10127        final String installerPackageName;
10128        final String volumeUuid;
10129        final VerificationParams verificationParams;
10130        private InstallArgs mArgs;
10131        private int mRet;
10132        final String packageAbiOverride;
10133
10134        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10135                int installFlags, String installerPackageName, String volumeUuid,
10136                VerificationParams verificationParams, UserHandle user, String packageAbiOverride) {
10137            super(user);
10138            this.origin = origin;
10139            this.move = move;
10140            this.observer = observer;
10141            this.installFlags = installFlags;
10142            this.installerPackageName = installerPackageName;
10143            this.volumeUuid = volumeUuid;
10144            this.verificationParams = verificationParams;
10145            this.packageAbiOverride = packageAbiOverride;
10146        }
10147
10148        @Override
10149        public String toString() {
10150            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10151                    + " file=" + origin.file + " cid=" + origin.cid + "}";
10152        }
10153
10154        public ManifestDigest getManifestDigest() {
10155            if (verificationParams == null) {
10156                return null;
10157            }
10158            return verificationParams.getManifestDigest();
10159        }
10160
10161        private int installLocationPolicy(PackageInfoLite pkgLite) {
10162            String packageName = pkgLite.packageName;
10163            int installLocation = pkgLite.installLocation;
10164            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10165            // reader
10166            synchronized (mPackages) {
10167                PackageParser.Package pkg = mPackages.get(packageName);
10168                if (pkg != null) {
10169                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10170                        // Check for downgrading.
10171                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10172                            try {
10173                                checkDowngrade(pkg, pkgLite);
10174                            } catch (PackageManagerException e) {
10175                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10176                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
10177                            }
10178                        }
10179                        // Check for updated system application.
10180                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10181                            if (onSd) {
10182                                Slog.w(TAG, "Cannot install update to system app on sdcard");
10183                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
10184                            }
10185                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10186                        } else {
10187                            if (onSd) {
10188                                // Install flag overrides everything.
10189                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10190                            }
10191                            // If current upgrade specifies particular preference
10192                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
10193                                // Application explicitly specified internal.
10194                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10195                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
10196                                // App explictly prefers external. Let policy decide
10197                            } else {
10198                                // Prefer previous location
10199                                if (isExternal(pkg)) {
10200                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10201                                }
10202                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10203                            }
10204                        }
10205                    } else {
10206                        // Invalid install. Return error code
10207                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
10208                    }
10209                }
10210            }
10211            // All the special cases have been taken care of.
10212            // Return result based on recommended install location.
10213            if (onSd) {
10214                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10215            }
10216            return pkgLite.recommendedInstallLocation;
10217        }
10218
10219        /*
10220         * Invoke remote method to get package information and install
10221         * location values. Override install location based on default
10222         * policy if needed and then create install arguments based
10223         * on the install location.
10224         */
10225        public void handleStartCopy() throws RemoteException {
10226            int ret = PackageManager.INSTALL_SUCCEEDED;
10227
10228            // If we're already staged, we've firmly committed to an install location
10229            if (origin.staged) {
10230                if (origin.file != null) {
10231                    installFlags |= PackageManager.INSTALL_INTERNAL;
10232                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10233                } else if (origin.cid != null) {
10234                    installFlags |= PackageManager.INSTALL_EXTERNAL;
10235                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
10236                } else {
10237                    throw new IllegalStateException("Invalid stage location");
10238                }
10239            }
10240
10241            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10242            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
10243
10244            PackageInfoLite pkgLite = null;
10245
10246            if (onInt && onSd) {
10247                // Check if both bits are set.
10248                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
10249                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10250            } else {
10251                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
10252                        packageAbiOverride);
10253
10254                /*
10255                 * If we have too little free space, try to free cache
10256                 * before giving up.
10257                 */
10258                if (!origin.staged && pkgLite.recommendedInstallLocation
10259                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10260                    // TODO: focus freeing disk space on the target device
10261                    final StorageManager storage = StorageManager.from(mContext);
10262                    final long lowThreshold = storage.getStorageLowBytes(
10263                            Environment.getDataDirectory());
10264
10265                    final long sizeBytes = mContainerService.calculateInstalledSize(
10266                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
10267
10268                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
10269                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
10270                                installFlags, packageAbiOverride);
10271                    }
10272
10273                    /*
10274                     * The cache free must have deleted the file we
10275                     * downloaded to install.
10276                     *
10277                     * TODO: fix the "freeCache" call to not delete
10278                     *       the file we care about.
10279                     */
10280                    if (pkgLite.recommendedInstallLocation
10281                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10282                        pkgLite.recommendedInstallLocation
10283                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
10284                    }
10285                }
10286            }
10287
10288            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10289                int loc = pkgLite.recommendedInstallLocation;
10290                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
10291                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10292                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
10293                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
10294                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10295                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10296                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
10297                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
10298                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10299                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
10300                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
10301                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
10302                } else {
10303                    // Override with defaults if needed.
10304                    loc = installLocationPolicy(pkgLite);
10305                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
10306                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
10307                    } else if (!onSd && !onInt) {
10308                        // Override install location with flags
10309                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
10310                            // Set the flag to install on external media.
10311                            installFlags |= PackageManager.INSTALL_EXTERNAL;
10312                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
10313                        } else {
10314                            // Make sure the flag for installing on external
10315                            // media is unset
10316                            installFlags |= PackageManager.INSTALL_INTERNAL;
10317                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10318                        }
10319                    }
10320                }
10321            }
10322
10323            final InstallArgs args = createInstallArgs(this);
10324            mArgs = args;
10325
10326            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10327                 /*
10328                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
10329                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
10330                 */
10331                int userIdentifier = getUser().getIdentifier();
10332                if (userIdentifier == UserHandle.USER_ALL
10333                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
10334                    userIdentifier = UserHandle.USER_OWNER;
10335                }
10336
10337                /*
10338                 * Determine if we have any installed package verifiers. If we
10339                 * do, then we'll defer to them to verify the packages.
10340                 */
10341                final int requiredUid = mRequiredVerifierPackage == null ? -1
10342                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
10343                if (!origin.existing && requiredUid != -1
10344                        && isVerificationEnabled(userIdentifier, installFlags)) {
10345                    final Intent verification = new Intent(
10346                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
10347                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10348                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
10349                            PACKAGE_MIME_TYPE);
10350                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10351
10352                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
10353                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10354                            0 /* TODO: Which userId? */);
10355
10356                    if (DEBUG_VERIFY) {
10357                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10358                                + verification.toString() + " with " + pkgLite.verifiers.length
10359                                + " optional verifiers");
10360                    }
10361
10362                    final int verificationId = mPendingVerificationToken++;
10363
10364                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10365
10366                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10367                            installerPackageName);
10368
10369                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10370                            installFlags);
10371
10372                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10373                            pkgLite.packageName);
10374
10375                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10376                            pkgLite.versionCode);
10377
10378                    if (verificationParams != null) {
10379                        if (verificationParams.getVerificationURI() != null) {
10380                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10381                                 verificationParams.getVerificationURI());
10382                        }
10383                        if (verificationParams.getOriginatingURI() != null) {
10384                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10385                                  verificationParams.getOriginatingURI());
10386                        }
10387                        if (verificationParams.getReferrer() != null) {
10388                            verification.putExtra(Intent.EXTRA_REFERRER,
10389                                  verificationParams.getReferrer());
10390                        }
10391                        if (verificationParams.getOriginatingUid() >= 0) {
10392                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
10393                                  verificationParams.getOriginatingUid());
10394                        }
10395                        if (verificationParams.getInstallerUid() >= 0) {
10396                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
10397                                  verificationParams.getInstallerUid());
10398                        }
10399                    }
10400
10401                    final PackageVerificationState verificationState = new PackageVerificationState(
10402                            requiredUid, args);
10403
10404                    mPendingVerification.append(verificationId, verificationState);
10405
10406                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
10407                            receivers, verificationState);
10408
10409                    /*
10410                     * If any sufficient verifiers were listed in the package
10411                     * manifest, attempt to ask them.
10412                     */
10413                    if (sufficientVerifiers != null) {
10414                        final int N = sufficientVerifiers.size();
10415                        if (N == 0) {
10416                            Slog.i(TAG, "Additional verifiers required, but none installed.");
10417                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
10418                        } else {
10419                            for (int i = 0; i < N; i++) {
10420                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
10421
10422                                final Intent sufficientIntent = new Intent(verification);
10423                                sufficientIntent.setComponent(verifierComponent);
10424
10425                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
10426                            }
10427                        }
10428                    }
10429
10430                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
10431                            mRequiredVerifierPackage, receivers);
10432                    if (ret == PackageManager.INSTALL_SUCCEEDED
10433                            && mRequiredVerifierPackage != null) {
10434                        /*
10435                         * Send the intent to the required verification agent,
10436                         * but only start the verification timeout after the
10437                         * target BroadcastReceivers have run.
10438                         */
10439                        verification.setComponent(requiredVerifierComponent);
10440                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
10441                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10442                                new BroadcastReceiver() {
10443                                    @Override
10444                                    public void onReceive(Context context, Intent intent) {
10445                                        final Message msg = mHandler
10446                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
10447                                        msg.arg1 = verificationId;
10448                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
10449                                    }
10450                                }, null, 0, null, null);
10451
10452                        /*
10453                         * We don't want the copy to proceed until verification
10454                         * succeeds, so null out this field.
10455                         */
10456                        mArgs = null;
10457                    }
10458                } else {
10459                    /*
10460                     * No package verification is enabled, so immediately start
10461                     * the remote call to initiate copy using temporary file.
10462                     */
10463                    ret = args.copyApk(mContainerService, true);
10464                }
10465            }
10466
10467            mRet = ret;
10468        }
10469
10470        @Override
10471        void handleReturnCode() {
10472            // If mArgs is null, then MCS couldn't be reached. When it
10473            // reconnects, it will try again to install. At that point, this
10474            // will succeed.
10475            if (mArgs != null) {
10476                processPendingInstall(mArgs, mRet);
10477            }
10478        }
10479
10480        @Override
10481        void handleServiceError() {
10482            mArgs = createInstallArgs(this);
10483            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10484        }
10485
10486        public boolean isForwardLocked() {
10487            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10488        }
10489    }
10490
10491    /**
10492     * Used during creation of InstallArgs
10493     *
10494     * @param installFlags package installation flags
10495     * @return true if should be installed on external storage
10496     */
10497    private static boolean installOnExternalAsec(int installFlags) {
10498        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
10499            return false;
10500        }
10501        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
10502            return true;
10503        }
10504        return false;
10505    }
10506
10507    /**
10508     * Used during creation of InstallArgs
10509     *
10510     * @param installFlags package installation flags
10511     * @return true if should be installed as forward locked
10512     */
10513    private static boolean installForwardLocked(int installFlags) {
10514        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10515    }
10516
10517    private InstallArgs createInstallArgs(InstallParams params) {
10518        if (params.move != null) {
10519            return new MoveInstallArgs(params);
10520        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
10521            return new AsecInstallArgs(params);
10522        } else {
10523            return new FileInstallArgs(params);
10524        }
10525    }
10526
10527    /**
10528     * Create args that describe an existing installed package. Typically used
10529     * when cleaning up old installs, or used as a move source.
10530     */
10531    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
10532            String resourcePath, String[] instructionSets) {
10533        final boolean isInAsec;
10534        if (installOnExternalAsec(installFlags)) {
10535            /* Apps on SD card are always in ASEC containers. */
10536            isInAsec = true;
10537        } else if (installForwardLocked(installFlags)
10538                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
10539            /*
10540             * Forward-locked apps are only in ASEC containers if they're the
10541             * new style
10542             */
10543            isInAsec = true;
10544        } else {
10545            isInAsec = false;
10546        }
10547
10548        if (isInAsec) {
10549            return new AsecInstallArgs(codePath, instructionSets,
10550                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
10551        } else {
10552            return new FileInstallArgs(codePath, resourcePath, instructionSets);
10553        }
10554    }
10555
10556    static abstract class InstallArgs {
10557        /** @see InstallParams#origin */
10558        final OriginInfo origin;
10559        /** @see InstallParams#move */
10560        final MoveInfo move;
10561
10562        final IPackageInstallObserver2 observer;
10563        // Always refers to PackageManager flags only
10564        final int installFlags;
10565        final String installerPackageName;
10566        final String volumeUuid;
10567        final ManifestDigest manifestDigest;
10568        final UserHandle user;
10569        final String abiOverride;
10570
10571        // The list of instruction sets supported by this app. This is currently
10572        // only used during the rmdex() phase to clean up resources. We can get rid of this
10573        // if we move dex files under the common app path.
10574        /* nullable */ String[] instructionSets;
10575
10576        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10577                int installFlags, String installerPackageName, String volumeUuid,
10578                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
10579                String abiOverride) {
10580            this.origin = origin;
10581            this.move = move;
10582            this.installFlags = installFlags;
10583            this.observer = observer;
10584            this.installerPackageName = installerPackageName;
10585            this.volumeUuid = volumeUuid;
10586            this.manifestDigest = manifestDigest;
10587            this.user = user;
10588            this.instructionSets = instructionSets;
10589            this.abiOverride = abiOverride;
10590        }
10591
10592        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
10593        abstract int doPreInstall(int status);
10594
10595        /**
10596         * Rename package into final resting place. All paths on the given
10597         * scanned package should be updated to reflect the rename.
10598         */
10599        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
10600        abstract int doPostInstall(int status, int uid);
10601
10602        /** @see PackageSettingBase#codePathString */
10603        abstract String getCodePath();
10604        /** @see PackageSettingBase#resourcePathString */
10605        abstract String getResourcePath();
10606
10607        // Need installer lock especially for dex file removal.
10608        abstract void cleanUpResourcesLI();
10609        abstract boolean doPostDeleteLI(boolean delete);
10610
10611        /**
10612         * Called before the source arguments are copied. This is used mostly
10613         * for MoveParams when it needs to read the source file to put it in the
10614         * destination.
10615         */
10616        int doPreCopy() {
10617            return PackageManager.INSTALL_SUCCEEDED;
10618        }
10619
10620        /**
10621         * Called after the source arguments are copied. This is used mostly for
10622         * MoveParams when it needs to read the source file to put it in the
10623         * destination.
10624         *
10625         * @return
10626         */
10627        int doPostCopy(int uid) {
10628            return PackageManager.INSTALL_SUCCEEDED;
10629        }
10630
10631        protected boolean isFwdLocked() {
10632            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10633        }
10634
10635        protected boolean isExternalAsec() {
10636            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10637        }
10638
10639        UserHandle getUser() {
10640            return user;
10641        }
10642    }
10643
10644    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
10645        if (!allCodePaths.isEmpty()) {
10646            if (instructionSets == null) {
10647                throw new IllegalStateException("instructionSet == null");
10648            }
10649            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
10650            for (String codePath : allCodePaths) {
10651                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
10652                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
10653                    if (retCode < 0) {
10654                        Slog.w(TAG, "Couldn't remove dex file for package: "
10655                                + " at location " + codePath + ", retcode=" + retCode);
10656                        // we don't consider this to be a failure of the core package deletion
10657                    }
10658                }
10659            }
10660        }
10661    }
10662
10663    /**
10664     * Logic to handle installation of non-ASEC applications, including copying
10665     * and renaming logic.
10666     */
10667    class FileInstallArgs extends InstallArgs {
10668        private File codeFile;
10669        private File resourceFile;
10670
10671        // Example topology:
10672        // /data/app/com.example/base.apk
10673        // /data/app/com.example/split_foo.apk
10674        // /data/app/com.example/lib/arm/libfoo.so
10675        // /data/app/com.example/lib/arm64/libfoo.so
10676        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
10677
10678        /** New install */
10679        FileInstallArgs(InstallParams params) {
10680            super(params.origin, params.move, params.observer, params.installFlags,
10681                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10682                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10683            if (isFwdLocked()) {
10684                throw new IllegalArgumentException("Forward locking only supported in ASEC");
10685            }
10686        }
10687
10688        /** Existing install */
10689        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
10690            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
10691                    null);
10692            this.codeFile = (codePath != null) ? new File(codePath) : null;
10693            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
10694        }
10695
10696        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10697            if (origin.staged) {
10698                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
10699                codeFile = origin.file;
10700                resourceFile = origin.file;
10701                return PackageManager.INSTALL_SUCCEEDED;
10702            }
10703
10704            try {
10705                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
10706                codeFile = tempDir;
10707                resourceFile = tempDir;
10708            } catch (IOException e) {
10709                Slog.w(TAG, "Failed to create copy file: " + e);
10710                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10711            }
10712
10713            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
10714                @Override
10715                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
10716                    if (!FileUtils.isValidExtFilename(name)) {
10717                        throw new IllegalArgumentException("Invalid filename: " + name);
10718                    }
10719                    try {
10720                        final File file = new File(codeFile, name);
10721                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
10722                                O_RDWR | O_CREAT, 0644);
10723                        Os.chmod(file.getAbsolutePath(), 0644);
10724                        return new ParcelFileDescriptor(fd);
10725                    } catch (ErrnoException e) {
10726                        throw new RemoteException("Failed to open: " + e.getMessage());
10727                    }
10728                }
10729            };
10730
10731            int ret = PackageManager.INSTALL_SUCCEEDED;
10732            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
10733            if (ret != PackageManager.INSTALL_SUCCEEDED) {
10734                Slog.e(TAG, "Failed to copy package");
10735                return ret;
10736            }
10737
10738            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
10739            NativeLibraryHelper.Handle handle = null;
10740            try {
10741                handle = NativeLibraryHelper.Handle.create(codeFile);
10742                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
10743                        abiOverride);
10744            } catch (IOException e) {
10745                Slog.e(TAG, "Copying native libraries failed", e);
10746                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10747            } finally {
10748                IoUtils.closeQuietly(handle);
10749            }
10750
10751            return ret;
10752        }
10753
10754        int doPreInstall(int status) {
10755            if (status != PackageManager.INSTALL_SUCCEEDED) {
10756                cleanUp();
10757            }
10758            return status;
10759        }
10760
10761        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10762            if (status != PackageManager.INSTALL_SUCCEEDED) {
10763                cleanUp();
10764                return false;
10765            }
10766
10767            final File targetDir = codeFile.getParentFile();
10768            final File beforeCodeFile = codeFile;
10769            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
10770
10771            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
10772            try {
10773                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
10774            } catch (ErrnoException e) {
10775                Slog.w(TAG, "Failed to rename", e);
10776                return false;
10777            }
10778
10779            if (!SELinux.restoreconRecursive(afterCodeFile)) {
10780                Slog.w(TAG, "Failed to restorecon");
10781                return false;
10782            }
10783
10784            // Reflect the rename internally
10785            codeFile = afterCodeFile;
10786            resourceFile = afterCodeFile;
10787
10788            // Reflect the rename in scanned details
10789            pkg.codePath = afterCodeFile.getAbsolutePath();
10790            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10791                    pkg.baseCodePath);
10792            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10793                    pkg.splitCodePaths);
10794
10795            // Reflect the rename in app info
10796            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10797            pkg.applicationInfo.setCodePath(pkg.codePath);
10798            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10799            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10800            pkg.applicationInfo.setResourcePath(pkg.codePath);
10801            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10802            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10803
10804            return true;
10805        }
10806
10807        int doPostInstall(int status, int uid) {
10808            if (status != PackageManager.INSTALL_SUCCEEDED) {
10809                cleanUp();
10810            }
10811            return status;
10812        }
10813
10814        @Override
10815        String getCodePath() {
10816            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
10817        }
10818
10819        @Override
10820        String getResourcePath() {
10821            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
10822        }
10823
10824        private boolean cleanUp() {
10825            if (codeFile == null || !codeFile.exists()) {
10826                return false;
10827            }
10828
10829            if (codeFile.isDirectory()) {
10830                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
10831            } else {
10832                codeFile.delete();
10833            }
10834
10835            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
10836                resourceFile.delete();
10837            }
10838
10839            return true;
10840        }
10841
10842        void cleanUpResourcesLI() {
10843            // Try enumerating all code paths before deleting
10844            List<String> allCodePaths = Collections.EMPTY_LIST;
10845            if (codeFile != null && codeFile.exists()) {
10846                try {
10847                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
10848                    allCodePaths = pkg.getAllCodePaths();
10849                } catch (PackageParserException e) {
10850                    // Ignored; we tried our best
10851                }
10852            }
10853
10854            cleanUp();
10855            removeDexFiles(allCodePaths, instructionSets);
10856        }
10857
10858        boolean doPostDeleteLI(boolean delete) {
10859            // XXX err, shouldn't we respect the delete flag?
10860            cleanUpResourcesLI();
10861            return true;
10862        }
10863    }
10864
10865    private boolean isAsecExternal(String cid) {
10866        final String asecPath = PackageHelper.getSdFilesystem(cid);
10867        return !asecPath.startsWith(mAsecInternalPath);
10868    }
10869
10870    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
10871            PackageManagerException {
10872        if (copyRet < 0) {
10873            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
10874                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
10875                throw new PackageManagerException(copyRet, message);
10876            }
10877        }
10878    }
10879
10880    /**
10881     * Extract the MountService "container ID" from the full code path of an
10882     * .apk.
10883     */
10884    static String cidFromCodePath(String fullCodePath) {
10885        int eidx = fullCodePath.lastIndexOf("/");
10886        String subStr1 = fullCodePath.substring(0, eidx);
10887        int sidx = subStr1.lastIndexOf("/");
10888        return subStr1.substring(sidx+1, eidx);
10889    }
10890
10891    /**
10892     * Logic to handle installation of ASEC applications, including copying and
10893     * renaming logic.
10894     */
10895    class AsecInstallArgs extends InstallArgs {
10896        static final String RES_FILE_NAME = "pkg.apk";
10897        static final String PUBLIC_RES_FILE_NAME = "res.zip";
10898
10899        String cid;
10900        String packagePath;
10901        String resourcePath;
10902
10903        /** New install */
10904        AsecInstallArgs(InstallParams params) {
10905            super(params.origin, params.move, params.observer, params.installFlags,
10906                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10907                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10908        }
10909
10910        /** Existing install */
10911        AsecInstallArgs(String fullCodePath, String[] instructionSets,
10912                        boolean isExternal, boolean isForwardLocked) {
10913            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
10914                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
10915                    instructionSets, null);
10916            // Hackily pretend we're still looking at a full code path
10917            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
10918                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
10919            }
10920
10921            // Extract cid from fullCodePath
10922            int eidx = fullCodePath.lastIndexOf("/");
10923            String subStr1 = fullCodePath.substring(0, eidx);
10924            int sidx = subStr1.lastIndexOf("/");
10925            cid = subStr1.substring(sidx+1, eidx);
10926            setMountPath(subStr1);
10927        }
10928
10929        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
10930            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
10931                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
10932                    instructionSets, null);
10933            this.cid = cid;
10934            setMountPath(PackageHelper.getSdDir(cid));
10935        }
10936
10937        void createCopyFile() {
10938            cid = mInstallerService.allocateExternalStageCidLegacy();
10939        }
10940
10941        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10942            if (origin.staged) {
10943                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
10944                cid = origin.cid;
10945                setMountPath(PackageHelper.getSdDir(cid));
10946                return PackageManager.INSTALL_SUCCEEDED;
10947            }
10948
10949            if (temp) {
10950                createCopyFile();
10951            } else {
10952                /*
10953                 * Pre-emptively destroy the container since it's destroyed if
10954                 * copying fails due to it existing anyway.
10955                 */
10956                PackageHelper.destroySdDir(cid);
10957            }
10958
10959            final String newMountPath = imcs.copyPackageToContainer(
10960                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
10961                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
10962
10963            if (newMountPath != null) {
10964                setMountPath(newMountPath);
10965                return PackageManager.INSTALL_SUCCEEDED;
10966            } else {
10967                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10968            }
10969        }
10970
10971        @Override
10972        String getCodePath() {
10973            return packagePath;
10974        }
10975
10976        @Override
10977        String getResourcePath() {
10978            return resourcePath;
10979        }
10980
10981        int doPreInstall(int status) {
10982            if (status != PackageManager.INSTALL_SUCCEEDED) {
10983                // Destroy container
10984                PackageHelper.destroySdDir(cid);
10985            } else {
10986                boolean mounted = PackageHelper.isContainerMounted(cid);
10987                if (!mounted) {
10988                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
10989                            Process.SYSTEM_UID);
10990                    if (newMountPath != null) {
10991                        setMountPath(newMountPath);
10992                    } else {
10993                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10994                    }
10995                }
10996            }
10997            return status;
10998        }
10999
11000        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11001            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11002            String newMountPath = null;
11003            if (PackageHelper.isContainerMounted(cid)) {
11004                // Unmount the container
11005                if (!PackageHelper.unMountSdDir(cid)) {
11006                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11007                    return false;
11008                }
11009            }
11010            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11011                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11012                        " which might be stale. Will try to clean up.");
11013                // Clean up the stale container and proceed to recreate.
11014                if (!PackageHelper.destroySdDir(newCacheId)) {
11015                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11016                    return false;
11017                }
11018                // Successfully cleaned up stale container. Try to rename again.
11019                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11020                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11021                            + " inspite of cleaning it up.");
11022                    return false;
11023                }
11024            }
11025            if (!PackageHelper.isContainerMounted(newCacheId)) {
11026                Slog.w(TAG, "Mounting container " + newCacheId);
11027                newMountPath = PackageHelper.mountSdDir(newCacheId,
11028                        getEncryptKey(), Process.SYSTEM_UID);
11029            } else {
11030                newMountPath = PackageHelper.getSdDir(newCacheId);
11031            }
11032            if (newMountPath == null) {
11033                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11034                return false;
11035            }
11036            Log.i(TAG, "Succesfully renamed " + cid +
11037                    " to " + newCacheId +
11038                    " at new path: " + newMountPath);
11039            cid = newCacheId;
11040
11041            final File beforeCodeFile = new File(packagePath);
11042            setMountPath(newMountPath);
11043            final File afterCodeFile = new File(packagePath);
11044
11045            // Reflect the rename in scanned details
11046            pkg.codePath = afterCodeFile.getAbsolutePath();
11047            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11048                    pkg.baseCodePath);
11049            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11050                    pkg.splitCodePaths);
11051
11052            // Reflect the rename in app info
11053            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11054            pkg.applicationInfo.setCodePath(pkg.codePath);
11055            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11056            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11057            pkg.applicationInfo.setResourcePath(pkg.codePath);
11058            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11059            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11060
11061            return true;
11062        }
11063
11064        private void setMountPath(String mountPath) {
11065            final File mountFile = new File(mountPath);
11066
11067            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11068            if (monolithicFile.exists()) {
11069                packagePath = monolithicFile.getAbsolutePath();
11070                if (isFwdLocked()) {
11071                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11072                } else {
11073                    resourcePath = packagePath;
11074                }
11075            } else {
11076                packagePath = mountFile.getAbsolutePath();
11077                resourcePath = packagePath;
11078            }
11079        }
11080
11081        int doPostInstall(int status, int uid) {
11082            if (status != PackageManager.INSTALL_SUCCEEDED) {
11083                cleanUp();
11084            } else {
11085                final int groupOwner;
11086                final String protectedFile;
11087                if (isFwdLocked()) {
11088                    groupOwner = UserHandle.getSharedAppGid(uid);
11089                    protectedFile = RES_FILE_NAME;
11090                } else {
11091                    groupOwner = -1;
11092                    protectedFile = null;
11093                }
11094
11095                if (uid < Process.FIRST_APPLICATION_UID
11096                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11097                    Slog.e(TAG, "Failed to finalize " + cid);
11098                    PackageHelper.destroySdDir(cid);
11099                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11100                }
11101
11102                boolean mounted = PackageHelper.isContainerMounted(cid);
11103                if (!mounted) {
11104                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11105                }
11106            }
11107            return status;
11108        }
11109
11110        private void cleanUp() {
11111            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11112
11113            // Destroy secure container
11114            PackageHelper.destroySdDir(cid);
11115        }
11116
11117        private List<String> getAllCodePaths() {
11118            final File codeFile = new File(getCodePath());
11119            if (codeFile != null && codeFile.exists()) {
11120                try {
11121                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11122                    return pkg.getAllCodePaths();
11123                } catch (PackageParserException e) {
11124                    // Ignored; we tried our best
11125                }
11126            }
11127            return Collections.EMPTY_LIST;
11128        }
11129
11130        void cleanUpResourcesLI() {
11131            // Enumerate all code paths before deleting
11132            cleanUpResourcesLI(getAllCodePaths());
11133        }
11134
11135        private void cleanUpResourcesLI(List<String> allCodePaths) {
11136            cleanUp();
11137            removeDexFiles(allCodePaths, instructionSets);
11138        }
11139
11140        String getPackageName() {
11141            return getAsecPackageName(cid);
11142        }
11143
11144        boolean doPostDeleteLI(boolean delete) {
11145            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
11146            final List<String> allCodePaths = getAllCodePaths();
11147            boolean mounted = PackageHelper.isContainerMounted(cid);
11148            if (mounted) {
11149                // Unmount first
11150                if (PackageHelper.unMountSdDir(cid)) {
11151                    mounted = false;
11152                }
11153            }
11154            if (!mounted && delete) {
11155                cleanUpResourcesLI(allCodePaths);
11156            }
11157            return !mounted;
11158        }
11159
11160        @Override
11161        int doPreCopy() {
11162            if (isFwdLocked()) {
11163                if (!PackageHelper.fixSdPermissions(cid,
11164                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
11165                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11166                }
11167            }
11168
11169            return PackageManager.INSTALL_SUCCEEDED;
11170        }
11171
11172        @Override
11173        int doPostCopy(int uid) {
11174            if (isFwdLocked()) {
11175                if (uid < Process.FIRST_APPLICATION_UID
11176                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
11177                                RES_FILE_NAME)) {
11178                    Slog.e(TAG, "Failed to finalize " + cid);
11179                    PackageHelper.destroySdDir(cid);
11180                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11181                }
11182            }
11183
11184            return PackageManager.INSTALL_SUCCEEDED;
11185        }
11186    }
11187
11188    /**
11189     * Logic to handle movement of existing installed applications.
11190     */
11191    class MoveInstallArgs extends InstallArgs {
11192        private File codeFile;
11193        private File resourceFile;
11194
11195        /** New install */
11196        MoveInstallArgs(InstallParams params) {
11197            super(params.origin, params.move, params.observer, params.installFlags,
11198                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11199                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
11200        }
11201
11202        int copyApk(IMediaContainerService imcs, boolean temp) {
11203            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
11204                    + move.fromUuid + " to " + move.toUuid);
11205            synchronized (mInstaller) {
11206                if (mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
11207                        move.dataAppName, move.appId, move.seinfo) != 0) {
11208                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11209                }
11210            }
11211
11212            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
11213            resourceFile = codeFile;
11214            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
11215
11216            return PackageManager.INSTALL_SUCCEEDED;
11217        }
11218
11219        int doPreInstall(int status) {
11220            if (status != PackageManager.INSTALL_SUCCEEDED) {
11221                cleanUp();
11222            }
11223            return status;
11224        }
11225
11226        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11227            if (status != PackageManager.INSTALL_SUCCEEDED) {
11228                cleanUp();
11229                return false;
11230            }
11231
11232            // Reflect the move in app info
11233            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11234            pkg.applicationInfo.setCodePath(pkg.codePath);
11235            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11236            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11237            pkg.applicationInfo.setResourcePath(pkg.codePath);
11238            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11239            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11240
11241            return true;
11242        }
11243
11244        int doPostInstall(int status, int uid) {
11245            if (status != PackageManager.INSTALL_SUCCEEDED) {
11246                cleanUp();
11247            }
11248            return status;
11249        }
11250
11251        @Override
11252        String getCodePath() {
11253            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11254        }
11255
11256        @Override
11257        String getResourcePath() {
11258            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11259        }
11260
11261        private boolean cleanUp() {
11262            if (codeFile == null || !codeFile.exists()) {
11263                return false;
11264            }
11265
11266            if (codeFile.isDirectory()) {
11267                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11268            } else {
11269                codeFile.delete();
11270            }
11271
11272            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11273                resourceFile.delete();
11274            }
11275
11276            return true;
11277        }
11278
11279        void cleanUpResourcesLI() {
11280            cleanUp();
11281        }
11282
11283        boolean doPostDeleteLI(boolean delete) {
11284            // XXX err, shouldn't we respect the delete flag?
11285            cleanUpResourcesLI();
11286            return true;
11287        }
11288    }
11289
11290    static String getAsecPackageName(String packageCid) {
11291        int idx = packageCid.lastIndexOf("-");
11292        if (idx == -1) {
11293            return packageCid;
11294        }
11295        return packageCid.substring(0, idx);
11296    }
11297
11298    // Utility method used to create code paths based on package name and available index.
11299    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
11300        String idxStr = "";
11301        int idx = 1;
11302        // Fall back to default value of idx=1 if prefix is not
11303        // part of oldCodePath
11304        if (oldCodePath != null) {
11305            String subStr = oldCodePath;
11306            // Drop the suffix right away
11307            if (suffix != null && subStr.endsWith(suffix)) {
11308                subStr = subStr.substring(0, subStr.length() - suffix.length());
11309            }
11310            // If oldCodePath already contains prefix find out the
11311            // ending index to either increment or decrement.
11312            int sidx = subStr.lastIndexOf(prefix);
11313            if (sidx != -1) {
11314                subStr = subStr.substring(sidx + prefix.length());
11315                if (subStr != null) {
11316                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
11317                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
11318                    }
11319                    try {
11320                        idx = Integer.parseInt(subStr);
11321                        if (idx <= 1) {
11322                            idx++;
11323                        } else {
11324                            idx--;
11325                        }
11326                    } catch(NumberFormatException e) {
11327                    }
11328                }
11329            }
11330        }
11331        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
11332        return prefix + idxStr;
11333    }
11334
11335    private File getNextCodePath(File targetDir, String packageName) {
11336        int suffix = 1;
11337        File result;
11338        do {
11339            result = new File(targetDir, packageName + "-" + suffix);
11340            suffix++;
11341        } while (result.exists());
11342        return result;
11343    }
11344
11345    // Utility method that returns the relative package path with respect
11346    // to the installation directory. Like say for /data/data/com.test-1.apk
11347    // string com.test-1 is returned.
11348    static String deriveCodePathName(String codePath) {
11349        if (codePath == null) {
11350            return null;
11351        }
11352        final File codeFile = new File(codePath);
11353        final String name = codeFile.getName();
11354        if (codeFile.isDirectory()) {
11355            return name;
11356        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
11357            final int lastDot = name.lastIndexOf('.');
11358            return name.substring(0, lastDot);
11359        } else {
11360            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11361            return null;
11362        }
11363    }
11364
11365    class PackageInstalledInfo {
11366        String name;
11367        int uid;
11368        // The set of users that originally had this package installed.
11369        int[] origUsers;
11370        // The set of users that now have this package installed.
11371        int[] newUsers;
11372        PackageParser.Package pkg;
11373        int returnCode;
11374        String returnMsg;
11375        PackageRemovedInfo removedInfo;
11376
11377        public void setError(int code, String msg) {
11378            returnCode = code;
11379            returnMsg = msg;
11380            Slog.w(TAG, msg);
11381        }
11382
11383        public void setError(String msg, PackageParserException e) {
11384            returnCode = e.error;
11385            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11386            Slog.w(TAG, msg, e);
11387        }
11388
11389        public void setError(String msg, PackageManagerException e) {
11390            returnCode = e.error;
11391            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11392            Slog.w(TAG, msg, e);
11393        }
11394
11395        // In some error cases we want to convey more info back to the observer
11396        String origPackage;
11397        String origPermission;
11398    }
11399
11400    /*
11401     * Install a non-existing package.
11402     */
11403    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11404            UserHandle user, String installerPackageName, String volumeUuid,
11405            PackageInstalledInfo res) {
11406        // Remember this for later, in case we need to rollback this install
11407        String pkgName = pkg.packageName;
11408
11409        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
11410        final boolean dataDirExists = PackageManager.getDataDirForUser(volumeUuid, pkgName,
11411                UserHandle.USER_OWNER).exists();
11412        synchronized(mPackages) {
11413            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
11414                // A package with the same name is already installed, though
11415                // it has been renamed to an older name.  The package we
11416                // are trying to install should be installed as an update to
11417                // the existing one, but that has not been requested, so bail.
11418                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11419                        + " without first uninstalling package running as "
11420                        + mSettings.mRenamedPackages.get(pkgName));
11421                return;
11422            }
11423            if (mPackages.containsKey(pkgName)) {
11424                // Don't allow installation over an existing package with the same name.
11425                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11426                        + " without first uninstalling.");
11427                return;
11428            }
11429        }
11430
11431        try {
11432            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
11433                    System.currentTimeMillis(), user);
11434
11435            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
11436            // delete the partially installed application. the data directory will have to be
11437            // restored if it was already existing
11438            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11439                // remove package from internal structures.  Note that we want deletePackageX to
11440                // delete the package data and cache directories that it created in
11441                // scanPackageLocked, unless those directories existed before we even tried to
11442                // install.
11443                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
11444                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
11445                                res.removedInfo, true);
11446            }
11447
11448        } catch (PackageManagerException e) {
11449            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11450        }
11451    }
11452
11453    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
11454        // Can't rotate keys during boot or if sharedUser.
11455        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
11456                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
11457            return false;
11458        }
11459        // app is using upgradeKeySets; make sure all are valid
11460        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11461        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
11462        for (int i = 0; i < upgradeKeySets.length; i++) {
11463            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
11464                Slog.wtf(TAG, "Package "
11465                         + (oldPs.name != null ? oldPs.name : "<null>")
11466                         + " contains upgrade-key-set reference to unknown key-set: "
11467                         + upgradeKeySets[i]
11468                         + " reverting to signatures check.");
11469                return false;
11470            }
11471        }
11472        return true;
11473    }
11474
11475    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
11476        // Upgrade keysets are being used.  Determine if new package has a superset of the
11477        // required keys.
11478        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
11479        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11480        for (int i = 0; i < upgradeKeySets.length; i++) {
11481            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
11482            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
11483                return true;
11484            }
11485        }
11486        return false;
11487    }
11488
11489    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11490            UserHandle user, String installerPackageName, String volumeUuid,
11491            PackageInstalledInfo res) {
11492        final PackageParser.Package oldPackage;
11493        final String pkgName = pkg.packageName;
11494        final int[] allUsers;
11495        final boolean[] perUserInstalled;
11496        final boolean weFroze;
11497
11498        // First find the old package info and check signatures
11499        synchronized(mPackages) {
11500            oldPackage = mPackages.get(pkgName);
11501            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
11502            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11503            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11504                if(!checkUpgradeKeySetLP(ps, pkg)) {
11505                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11506                            "New package not signed by keys specified by upgrade-keysets: "
11507                            + pkgName);
11508                    return;
11509                }
11510            } else {
11511                // default to original signature matching
11512                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
11513                    != PackageManager.SIGNATURE_MATCH) {
11514                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11515                            "New package has a different signature: " + pkgName);
11516                    return;
11517                }
11518            }
11519
11520            // In case of rollback, remember per-user/profile install state
11521            allUsers = sUserManager.getUserIds();
11522            perUserInstalled = new boolean[allUsers.length];
11523            for (int i = 0; i < allUsers.length; i++) {
11524                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11525            }
11526
11527            // Mark the app as frozen to prevent launching during the upgrade
11528            // process, and then kill all running instances
11529            if (!ps.frozen) {
11530                ps.frozen = true;
11531                weFroze = true;
11532            } else {
11533                weFroze = false;
11534            }
11535        }
11536
11537        // Now that we're guarded by frozen state, kill app during upgrade
11538        killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg");
11539
11540        try {
11541            boolean sysPkg = (isSystemApp(oldPackage));
11542            if (sysPkg) {
11543                replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11544                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11545            } else {
11546                replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11547                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11548            }
11549        } finally {
11550            // Regardless of success or failure of upgrade steps above, always
11551            // unfreeze the package if we froze it
11552            if (weFroze) {
11553                unfreezePackage(pkgName);
11554            }
11555        }
11556    }
11557
11558    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
11559            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11560            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11561            String volumeUuid, PackageInstalledInfo res) {
11562        String pkgName = deletedPackage.packageName;
11563        boolean deletedPkg = true;
11564        boolean updatedSettings = false;
11565
11566        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
11567                + deletedPackage);
11568        long origUpdateTime;
11569        if (pkg.mExtras != null) {
11570            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
11571        } else {
11572            origUpdateTime = 0;
11573        }
11574
11575        // First delete the existing package while retaining the data directory
11576        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
11577                res.removedInfo, true)) {
11578            // If the existing package wasn't successfully deleted
11579            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
11580            deletedPkg = false;
11581        } else {
11582            // Successfully deleted the old package; proceed with replace.
11583
11584            // If deleted package lived in a container, give users a chance to
11585            // relinquish resources before killing.
11586            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
11587                if (DEBUG_INSTALL) {
11588                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
11589                }
11590                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
11591                final ArrayList<String> pkgList = new ArrayList<String>(1);
11592                pkgList.add(deletedPackage.applicationInfo.packageName);
11593                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
11594            }
11595
11596            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
11597            try {
11598                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
11599                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
11600                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11601                        perUserInstalled, res, user);
11602                updatedSettings = true;
11603            } catch (PackageManagerException e) {
11604                res.setError("Package couldn't be installed in " + pkg.codePath, e);
11605            }
11606        }
11607
11608        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11609            // remove package from internal structures.  Note that we want deletePackageX to
11610            // delete the package data and cache directories that it created in
11611            // scanPackageLocked, unless those directories existed before we even tried to
11612            // install.
11613            if(updatedSettings) {
11614                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
11615                deletePackageLI(
11616                        pkgName, null, true, allUsers, perUserInstalled,
11617                        PackageManager.DELETE_KEEP_DATA,
11618                                res.removedInfo, true);
11619            }
11620            // Since we failed to install the new package we need to restore the old
11621            // package that we deleted.
11622            if (deletedPkg) {
11623                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
11624                File restoreFile = new File(deletedPackage.codePath);
11625                // Parse old package
11626                boolean oldExternal = isExternal(deletedPackage);
11627                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
11628                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
11629                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11630                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
11631                try {
11632                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
11633                } catch (PackageManagerException e) {
11634                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
11635                            + e.getMessage());
11636                    return;
11637                }
11638                // Restore of old package succeeded. Update permissions.
11639                // writer
11640                synchronized (mPackages) {
11641                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
11642                            UPDATE_PERMISSIONS_ALL);
11643                    // can downgrade to reader
11644                    mSettings.writeLPr();
11645                }
11646                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
11647            }
11648        }
11649    }
11650
11651    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
11652            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11653            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11654            String volumeUuid, PackageInstalledInfo res) {
11655        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
11656                + ", old=" + deletedPackage);
11657        boolean disabledSystem = false;
11658        boolean updatedSettings = false;
11659        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
11660        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
11661                != 0) {
11662            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11663        }
11664        String packageName = deletedPackage.packageName;
11665        if (packageName == null) {
11666            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11667                    "Attempt to delete null packageName.");
11668            return;
11669        }
11670        PackageParser.Package oldPkg;
11671        PackageSetting oldPkgSetting;
11672        // reader
11673        synchronized (mPackages) {
11674            oldPkg = mPackages.get(packageName);
11675            oldPkgSetting = mSettings.mPackages.get(packageName);
11676            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
11677                    (oldPkgSetting == null)) {
11678                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11679                        "Couldn't find package:" + packageName + " information");
11680                return;
11681            }
11682        }
11683
11684        res.removedInfo.uid = oldPkg.applicationInfo.uid;
11685        res.removedInfo.removedPackage = packageName;
11686        // Remove existing system package
11687        removePackageLI(oldPkgSetting, true);
11688        // writer
11689        synchronized (mPackages) {
11690            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
11691            if (!disabledSystem && deletedPackage != null) {
11692                // We didn't need to disable the .apk as a current system package,
11693                // which means we are replacing another update that is already
11694                // installed.  We need to make sure to delete the older one's .apk.
11695                res.removedInfo.args = createInstallArgsForExisting(0,
11696                        deletedPackage.applicationInfo.getCodePath(),
11697                        deletedPackage.applicationInfo.getResourcePath(),
11698                        getAppDexInstructionSets(deletedPackage.applicationInfo));
11699            } else {
11700                res.removedInfo.args = null;
11701            }
11702        }
11703
11704        // Successfully disabled the old package. Now proceed with re-installation
11705        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
11706
11707        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11708        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
11709
11710        PackageParser.Package newPackage = null;
11711        try {
11712            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
11713            if (newPackage.mExtras != null) {
11714                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
11715                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
11716                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
11717
11718                // is the update attempting to change shared user? that isn't going to work...
11719                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
11720                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
11721                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
11722                            + " to " + newPkgSetting.sharedUser);
11723                    updatedSettings = true;
11724                }
11725            }
11726
11727            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11728                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11729                        perUserInstalled, res, user);
11730                updatedSettings = true;
11731            }
11732
11733        } catch (PackageManagerException e) {
11734            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11735        }
11736
11737        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11738            // Re installation failed. Restore old information
11739            // Remove new pkg information
11740            if (newPackage != null) {
11741                removeInstalledPackageLI(newPackage, true);
11742            }
11743            // Add back the old system package
11744            try {
11745                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
11746            } catch (PackageManagerException e) {
11747                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
11748            }
11749            // Restore the old system information in Settings
11750            synchronized (mPackages) {
11751                if (disabledSystem) {
11752                    mSettings.enableSystemPackageLPw(packageName);
11753                }
11754                if (updatedSettings) {
11755                    mSettings.setInstallerPackageName(packageName,
11756                            oldPkgSetting.installerPackageName);
11757                }
11758                mSettings.writeLPr();
11759            }
11760        }
11761    }
11762
11763    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
11764            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
11765            UserHandle user) {
11766        String pkgName = newPackage.packageName;
11767        synchronized (mPackages) {
11768            //write settings. the installStatus will be incomplete at this stage.
11769            //note that the new package setting would have already been
11770            //added to mPackages. It hasn't been persisted yet.
11771            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
11772            mSettings.writeLPr();
11773        }
11774
11775        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
11776
11777        synchronized (mPackages) {
11778            updatePermissionsLPw(newPackage.packageName, newPackage,
11779                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
11780                            ? UPDATE_PERMISSIONS_ALL : 0));
11781            // For system-bundled packages, we assume that installing an upgraded version
11782            // of the package implies that the user actually wants to run that new code,
11783            // so we enable the package.
11784            PackageSetting ps = mSettings.mPackages.get(pkgName);
11785            if (ps != null) {
11786                if (isSystemApp(newPackage)) {
11787                    // NB: implicit assumption that system package upgrades apply to all users
11788                    if (DEBUG_INSTALL) {
11789                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
11790                    }
11791                    if (res.origUsers != null) {
11792                        for (int userHandle : res.origUsers) {
11793                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
11794                                    userHandle, installerPackageName);
11795                        }
11796                    }
11797                    // Also convey the prior install/uninstall state
11798                    if (allUsers != null && perUserInstalled != null) {
11799                        for (int i = 0; i < allUsers.length; i++) {
11800                            if (DEBUG_INSTALL) {
11801                                Slog.d(TAG, "    user " + allUsers[i]
11802                                        + " => " + perUserInstalled[i]);
11803                            }
11804                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
11805                        }
11806                        // these install state changes will be persisted in the
11807                        // upcoming call to mSettings.writeLPr().
11808                    }
11809                }
11810                // It's implied that when a user requests installation, they want the app to be
11811                // installed and enabled.
11812                int userId = user.getIdentifier();
11813                if (userId != UserHandle.USER_ALL) {
11814                    ps.setInstalled(true, userId);
11815                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
11816                }
11817            }
11818            res.name = pkgName;
11819            res.uid = newPackage.applicationInfo.uid;
11820            res.pkg = newPackage;
11821            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
11822            mSettings.setInstallerPackageName(pkgName, installerPackageName);
11823            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11824            //to update install status
11825            mSettings.writeLPr();
11826        }
11827    }
11828
11829    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
11830        final int installFlags = args.installFlags;
11831        final String installerPackageName = args.installerPackageName;
11832        final String volumeUuid = args.volumeUuid;
11833        final File tmpPackageFile = new File(args.getCodePath());
11834        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
11835        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
11836                || (args.volumeUuid != null));
11837        boolean replace = false;
11838        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
11839        if (args.move != null) {
11840            // moving a complete application; perfom an initial scan on the new install location
11841            scanFlags |= SCAN_INITIAL;
11842        }
11843        // Result object to be returned
11844        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11845
11846        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
11847        // Retrieve PackageSettings and parse package
11848        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
11849                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
11850                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11851        PackageParser pp = new PackageParser();
11852        pp.setSeparateProcesses(mSeparateProcesses);
11853        pp.setDisplayMetrics(mMetrics);
11854
11855        final PackageParser.Package pkg;
11856        try {
11857            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
11858        } catch (PackageParserException e) {
11859            res.setError("Failed parse during installPackageLI", e);
11860            return;
11861        }
11862
11863        // Mark that we have an install time CPU ABI override.
11864        pkg.cpuAbiOverride = args.abiOverride;
11865
11866        String pkgName = res.name = pkg.packageName;
11867        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
11868            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
11869                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
11870                return;
11871            }
11872        }
11873
11874        try {
11875            pp.collectCertificates(pkg, parseFlags);
11876            pp.collectManifestDigest(pkg);
11877        } catch (PackageParserException e) {
11878            res.setError("Failed collect during installPackageLI", e);
11879            return;
11880        }
11881
11882        /* If the installer passed in a manifest digest, compare it now. */
11883        if (args.manifestDigest != null) {
11884            if (DEBUG_INSTALL) {
11885                final String parsedManifest = pkg.manifestDigest == null ? "null"
11886                        : pkg.manifestDigest.toString();
11887                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
11888                        + parsedManifest);
11889            }
11890
11891            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
11892                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
11893                return;
11894            }
11895        } else if (DEBUG_INSTALL) {
11896            final String parsedManifest = pkg.manifestDigest == null
11897                    ? "null" : pkg.manifestDigest.toString();
11898            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
11899        }
11900
11901        // Get rid of all references to package scan path via parser.
11902        pp = null;
11903        String oldCodePath = null;
11904        boolean systemApp = false;
11905        synchronized (mPackages) {
11906            // Check if installing already existing package
11907            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
11908                String oldName = mSettings.mRenamedPackages.get(pkgName);
11909                if (pkg.mOriginalPackages != null
11910                        && pkg.mOriginalPackages.contains(oldName)
11911                        && mPackages.containsKey(oldName)) {
11912                    // This package is derived from an original package,
11913                    // and this device has been updating from that original
11914                    // name.  We must continue using the original name, so
11915                    // rename the new package here.
11916                    pkg.setPackageName(oldName);
11917                    pkgName = pkg.packageName;
11918                    replace = true;
11919                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
11920                            + oldName + " pkgName=" + pkgName);
11921                } else if (mPackages.containsKey(pkgName)) {
11922                    // This package, under its official name, already exists
11923                    // on the device; we should replace it.
11924                    replace = true;
11925                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
11926                }
11927
11928                // Prevent apps opting out from runtime permissions
11929                if (replace) {
11930                    PackageParser.Package oldPackage = mPackages.get(pkgName);
11931                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
11932                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
11933                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
11934                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
11935                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
11936                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
11937                                        + " doesn't support runtime permissions but the old"
11938                                        + " target SDK " + oldTargetSdk + " does.");
11939                        return;
11940                    }
11941                }
11942            }
11943
11944            PackageSetting ps = mSettings.mPackages.get(pkgName);
11945            if (ps != null) {
11946                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
11947
11948                // Quick sanity check that we're signed correctly if updating;
11949                // we'll check this again later when scanning, but we want to
11950                // bail early here before tripping over redefined permissions.
11951                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11952                    if (!checkUpgradeKeySetLP(ps, pkg)) {
11953                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
11954                                + pkg.packageName + " upgrade keys do not match the "
11955                                + "previously installed version");
11956                        return;
11957                    }
11958                } else {
11959                    try {
11960                        verifySignaturesLP(ps, pkg);
11961                    } catch (PackageManagerException e) {
11962                        res.setError(e.error, e.getMessage());
11963                        return;
11964                    }
11965                }
11966
11967                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
11968                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
11969                    systemApp = (ps.pkg.applicationInfo.flags &
11970                            ApplicationInfo.FLAG_SYSTEM) != 0;
11971                }
11972                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
11973            }
11974
11975            // Check whether the newly-scanned package wants to define an already-defined perm
11976            int N = pkg.permissions.size();
11977            for (int i = N-1; i >= 0; i--) {
11978                PackageParser.Permission perm = pkg.permissions.get(i);
11979                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
11980                if (bp != null) {
11981                    // If the defining package is signed with our cert, it's okay.  This
11982                    // also includes the "updating the same package" case, of course.
11983                    // "updating same package" could also involve key-rotation.
11984                    final boolean sigsOk;
11985                    if (bp.sourcePackage.equals(pkg.packageName)
11986                            && (bp.packageSetting instanceof PackageSetting)
11987                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
11988                                    scanFlags))) {
11989                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
11990                    } else {
11991                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
11992                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
11993                    }
11994                    if (!sigsOk) {
11995                        // If the owning package is the system itself, we log but allow
11996                        // install to proceed; we fail the install on all other permission
11997                        // redefinitions.
11998                        if (!bp.sourcePackage.equals("android")) {
11999                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12000                                    + pkg.packageName + " attempting to redeclare permission "
12001                                    + perm.info.name + " already owned by " + bp.sourcePackage);
12002                            res.origPermission = perm.info.name;
12003                            res.origPackage = bp.sourcePackage;
12004                            return;
12005                        } else {
12006                            Slog.w(TAG, "Package " + pkg.packageName
12007                                    + " attempting to redeclare system permission "
12008                                    + perm.info.name + "; ignoring new declaration");
12009                            pkg.permissions.remove(i);
12010                        }
12011                    }
12012                }
12013            }
12014
12015        }
12016
12017        if (systemApp && onExternal) {
12018            // Disable updates to system apps on sdcard
12019            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12020                    "Cannot install updates to system apps on sdcard");
12021            return;
12022        }
12023
12024        if (args.move != null) {
12025            // We did an in-place move, so dex is ready to roll
12026            scanFlags |= SCAN_NO_DEX;
12027            scanFlags |= SCAN_MOVE;
12028        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
12029            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
12030            scanFlags |= SCAN_NO_DEX;
12031
12032            try {
12033                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
12034                        true /* extract libs */);
12035            } catch (PackageManagerException pme) {
12036                Slog.e(TAG, "Error deriving application ABI", pme);
12037                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
12038                return;
12039            }
12040
12041            // Run dexopt before old package gets removed, to minimize time when app is unavailable
12042            int result = mPackageDexOptimizer
12043                    .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */,
12044                            false /* defer */, false /* inclDependencies */);
12045            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
12046                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
12047                return;
12048            }
12049        }
12050
12051        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
12052            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
12053            return;
12054        }
12055
12056        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
12057
12058        if (replace) {
12059            replacePackageLI(pkg, parseFlags, scanFlags, args.user,
12060                    installerPackageName, volumeUuid, res);
12061        } else {
12062            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
12063                    args.user, installerPackageName, volumeUuid, res);
12064        }
12065        synchronized (mPackages) {
12066            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12067            if (ps != null) {
12068                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12069            }
12070        }
12071    }
12072
12073    private void startIntentFilterVerifications(int userId, boolean replacing,
12074            PackageParser.Package pkg) {
12075        if (mIntentFilterVerifierComponent == null) {
12076            Slog.w(TAG, "No IntentFilter verification will not be done as "
12077                    + "there is no IntentFilterVerifier available!");
12078            return;
12079        }
12080
12081        final int verifierUid = getPackageUid(
12082                mIntentFilterVerifierComponent.getPackageName(),
12083                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
12084
12085        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
12086        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
12087        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
12088        mHandler.sendMessage(msg);
12089    }
12090
12091    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
12092            PackageParser.Package pkg) {
12093        int size = pkg.activities.size();
12094        if (size == 0) {
12095            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12096                    "No activity, so no need to verify any IntentFilter!");
12097            return;
12098        }
12099
12100        final boolean hasDomainURLs = hasDomainURLs(pkg);
12101        if (!hasDomainURLs) {
12102            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12103                    "No domain URLs, so no need to verify any IntentFilter!");
12104            return;
12105        }
12106
12107        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
12108                + " if any IntentFilter from the " + size
12109                + " Activities needs verification ...");
12110
12111        int count = 0;
12112        final String packageName = pkg.packageName;
12113
12114        synchronized (mPackages) {
12115            // If this is a new install and we see that we've already run verification for this
12116            // package, we have nothing to do: it means the state was restored from backup.
12117            if (!replacing) {
12118                IntentFilterVerificationInfo ivi =
12119                        mSettings.getIntentFilterVerificationLPr(packageName);
12120                if (ivi != null) {
12121                    if (DEBUG_DOMAIN_VERIFICATION) {
12122                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
12123                                + ivi.getStatusString());
12124                    }
12125                    return;
12126                }
12127            }
12128
12129            // If any filters need to be verified, then all need to be.
12130            boolean needToVerify = false;
12131            for (PackageParser.Activity a : pkg.activities) {
12132                for (ActivityIntentInfo filter : a.intents) {
12133                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
12134                        if (DEBUG_DOMAIN_VERIFICATION) {
12135                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
12136                        }
12137                        needToVerify = true;
12138                        break;
12139                    }
12140                }
12141            }
12142
12143            if (needToVerify) {
12144                final int verificationId = mIntentFilterVerificationToken++;
12145                for (PackageParser.Activity a : pkg.activities) {
12146                    for (ActivityIntentInfo filter : a.intents) {
12147                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
12148                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12149                                    "Verification needed for IntentFilter:" + filter.toString());
12150                            mIntentFilterVerifier.addOneIntentFilterVerification(
12151                                    verifierUid, userId, verificationId, filter, packageName);
12152                            count++;
12153                        }
12154                    }
12155                }
12156            }
12157        }
12158
12159        if (count > 0) {
12160            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
12161                    + " IntentFilter verification" + (count > 1 ? "s" : "")
12162                    +  " for userId:" + userId);
12163            mIntentFilterVerifier.startVerifications(userId);
12164        } else {
12165            if (DEBUG_DOMAIN_VERIFICATION) {
12166                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
12167            }
12168        }
12169    }
12170
12171    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
12172        final ComponentName cn  = filter.activity.getComponentName();
12173        final String packageName = cn.getPackageName();
12174
12175        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
12176                packageName);
12177        if (ivi == null) {
12178            return true;
12179        }
12180        int status = ivi.getStatus();
12181        switch (status) {
12182            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
12183            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
12184                return true;
12185
12186            default:
12187                // Nothing to do
12188                return false;
12189        }
12190    }
12191
12192    private static boolean isMultiArch(PackageSetting ps) {
12193        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12194    }
12195
12196    private static boolean isMultiArch(ApplicationInfo info) {
12197        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12198    }
12199
12200    private static boolean isExternal(PackageParser.Package pkg) {
12201        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12202    }
12203
12204    private static boolean isExternal(PackageSetting ps) {
12205        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12206    }
12207
12208    private static boolean isExternal(ApplicationInfo info) {
12209        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12210    }
12211
12212    private static boolean isSystemApp(PackageParser.Package pkg) {
12213        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
12214    }
12215
12216    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
12217        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
12218    }
12219
12220    private static boolean hasDomainURLs(PackageParser.Package pkg) {
12221        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
12222    }
12223
12224    private static boolean isSystemApp(PackageSetting ps) {
12225        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
12226    }
12227
12228    private static boolean isUpdatedSystemApp(PackageSetting ps) {
12229        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
12230    }
12231
12232    private int packageFlagsToInstallFlags(PackageSetting ps) {
12233        int installFlags = 0;
12234        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
12235            // This existing package was an external ASEC install when we have
12236            // the external flag without a UUID
12237            installFlags |= PackageManager.INSTALL_EXTERNAL;
12238        }
12239        if (ps.isForwardLocked()) {
12240            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12241        }
12242        return installFlags;
12243    }
12244
12245    private void deleteTempPackageFiles() {
12246        final FilenameFilter filter = new FilenameFilter() {
12247            public boolean accept(File dir, String name) {
12248                return name.startsWith("vmdl") && name.endsWith(".tmp");
12249            }
12250        };
12251        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
12252            file.delete();
12253        }
12254    }
12255
12256    @Override
12257    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
12258            int flags) {
12259        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
12260                flags);
12261    }
12262
12263    @Override
12264    public void deletePackage(final String packageName,
12265            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
12266        mContext.enforceCallingOrSelfPermission(
12267                android.Manifest.permission.DELETE_PACKAGES, null);
12268        final int uid = Binder.getCallingUid();
12269        if (UserHandle.getUserId(uid) != userId) {
12270            mContext.enforceCallingPermission(
12271                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
12272                    "deletePackage for user " + userId);
12273        }
12274        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
12275            try {
12276                observer.onPackageDeleted(packageName,
12277                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
12278            } catch (RemoteException re) {
12279            }
12280            return;
12281        }
12282
12283        boolean uninstallBlocked = false;
12284        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
12285            int[] users = sUserManager.getUserIds();
12286            for (int i = 0; i < users.length; ++i) {
12287                if (getBlockUninstallForUser(packageName, users[i])) {
12288                    uninstallBlocked = true;
12289                    break;
12290                }
12291            }
12292        } else {
12293            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
12294        }
12295        if (uninstallBlocked) {
12296            try {
12297                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
12298                        null);
12299            } catch (RemoteException re) {
12300            }
12301            return;
12302        }
12303
12304        if (DEBUG_REMOVE) {
12305            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
12306        }
12307        // Queue up an async operation since the package deletion may take a little while.
12308        mHandler.post(new Runnable() {
12309            public void run() {
12310                mHandler.removeCallbacks(this);
12311                final int returnCode = deletePackageX(packageName, userId, flags);
12312                if (observer != null) {
12313                    try {
12314                        observer.onPackageDeleted(packageName, returnCode, null);
12315                    } catch (RemoteException e) {
12316                        Log.i(TAG, "Observer no longer exists.");
12317                    } //end catch
12318                } //end if
12319            } //end run
12320        });
12321    }
12322
12323    private boolean isPackageDeviceAdmin(String packageName, int userId) {
12324        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12325                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12326        try {
12327            if (dpm != null) {
12328                if (dpm.isDeviceOwner(packageName)) {
12329                    return true;
12330                }
12331                int[] users;
12332                if (userId == UserHandle.USER_ALL) {
12333                    users = sUserManager.getUserIds();
12334                } else {
12335                    users = new int[]{userId};
12336                }
12337                for (int i = 0; i < users.length; ++i) {
12338                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
12339                        return true;
12340                    }
12341                }
12342            }
12343        } catch (RemoteException e) {
12344        }
12345        return false;
12346    }
12347
12348    /**
12349     *  This method is an internal method that could be get invoked either
12350     *  to delete an installed package or to clean up a failed installation.
12351     *  After deleting an installed package, a broadcast is sent to notify any
12352     *  listeners that the package has been installed. For cleaning up a failed
12353     *  installation, the broadcast is not necessary since the package's
12354     *  installation wouldn't have sent the initial broadcast either
12355     *  The key steps in deleting a package are
12356     *  deleting the package information in internal structures like mPackages,
12357     *  deleting the packages base directories through installd
12358     *  updating mSettings to reflect current status
12359     *  persisting settings for later use
12360     *  sending a broadcast if necessary
12361     */
12362    private int deletePackageX(String packageName, int userId, int flags) {
12363        final PackageRemovedInfo info = new PackageRemovedInfo();
12364        final boolean res;
12365
12366        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
12367                ? UserHandle.ALL : new UserHandle(userId);
12368
12369        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
12370            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
12371            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
12372        }
12373
12374        boolean removedForAllUsers = false;
12375        boolean systemUpdate = false;
12376
12377        // for the uninstall-updates case and restricted profiles, remember the per-
12378        // userhandle installed state
12379        int[] allUsers;
12380        boolean[] perUserInstalled;
12381        synchronized (mPackages) {
12382            PackageSetting ps = mSettings.mPackages.get(packageName);
12383            allUsers = sUserManager.getUserIds();
12384            perUserInstalled = new boolean[allUsers.length];
12385            for (int i = 0; i < allUsers.length; i++) {
12386                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12387            }
12388        }
12389
12390        synchronized (mInstallLock) {
12391            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
12392            res = deletePackageLI(packageName, removeForUser,
12393                    true, allUsers, perUserInstalled,
12394                    flags | REMOVE_CHATTY, info, true);
12395            systemUpdate = info.isRemovedPackageSystemUpdate;
12396            if (res && !systemUpdate && mPackages.get(packageName) == null) {
12397                removedForAllUsers = true;
12398            }
12399            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
12400                    + " removedForAllUsers=" + removedForAllUsers);
12401        }
12402
12403        if (res) {
12404            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
12405
12406            // If the removed package was a system update, the old system package
12407            // was re-enabled; we need to broadcast this information
12408            if (systemUpdate) {
12409                Bundle extras = new Bundle(1);
12410                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
12411                        ? info.removedAppId : info.uid);
12412                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12413
12414                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
12415                        extras, null, null, null);
12416                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
12417                        extras, null, null, null);
12418                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
12419                        null, packageName, null, null);
12420            }
12421        }
12422        // Force a gc here.
12423        Runtime.getRuntime().gc();
12424        // Delete the resources here after sending the broadcast to let
12425        // other processes clean up before deleting resources.
12426        if (info.args != null) {
12427            synchronized (mInstallLock) {
12428                info.args.doPostDeleteLI(true);
12429            }
12430        }
12431
12432        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
12433    }
12434
12435    class PackageRemovedInfo {
12436        String removedPackage;
12437        int uid = -1;
12438        int removedAppId = -1;
12439        int[] removedUsers = null;
12440        boolean isRemovedPackageSystemUpdate = false;
12441        // Clean up resources deleted packages.
12442        InstallArgs args = null;
12443
12444        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
12445            Bundle extras = new Bundle(1);
12446            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
12447            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
12448            if (replacing) {
12449                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12450            }
12451            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
12452            if (removedPackage != null) {
12453                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
12454                        extras, null, null, removedUsers);
12455                if (fullRemove && !replacing) {
12456                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
12457                            extras, null, null, removedUsers);
12458                }
12459            }
12460            if (removedAppId >= 0) {
12461                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
12462                        removedUsers);
12463            }
12464        }
12465    }
12466
12467    /*
12468     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
12469     * flag is not set, the data directory is removed as well.
12470     * make sure this flag is set for partially installed apps. If not its meaningless to
12471     * delete a partially installed application.
12472     */
12473    private void removePackageDataLI(PackageSetting ps,
12474            int[] allUserHandles, boolean[] perUserInstalled,
12475            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
12476        String packageName = ps.name;
12477        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
12478        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
12479        // Retrieve object to delete permissions for shared user later on
12480        final PackageSetting deletedPs;
12481        // reader
12482        synchronized (mPackages) {
12483            deletedPs = mSettings.mPackages.get(packageName);
12484            if (outInfo != null) {
12485                outInfo.removedPackage = packageName;
12486                outInfo.removedUsers = deletedPs != null
12487                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
12488                        : null;
12489            }
12490        }
12491        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12492            removeDataDirsLI(ps.volumeUuid, packageName);
12493            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
12494        }
12495        // writer
12496        synchronized (mPackages) {
12497            if (deletedPs != null) {
12498                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12499                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
12500                    clearDefaultBrowserIfNeeded(packageName);
12501                    if (outInfo != null) {
12502                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
12503                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
12504                    }
12505                    updatePermissionsLPw(deletedPs.name, null, 0);
12506                    if (deletedPs.sharedUser != null) {
12507                        // Remove permissions associated with package. Since runtime
12508                        // permissions are per user we have to kill the removed package
12509                        // or packages running under the shared user of the removed
12510                        // package if revoking the permissions requested only by the removed
12511                        // package is successful and this causes a change in gids.
12512                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12513                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
12514                                    userId);
12515                            if (userIdToKill == UserHandle.USER_ALL
12516                                    || userIdToKill >= UserHandle.USER_OWNER) {
12517                                // If gids changed for this user, kill all affected packages.
12518                                mHandler.post(new Runnable() {
12519                                    @Override
12520                                    public void run() {
12521                                        // This has to happen with no lock held.
12522                                        killSettingPackagesForUser(deletedPs, userIdToKill,
12523                                                KILL_APP_REASON_GIDS_CHANGED);
12524                                    }
12525                                });
12526                            break;
12527                            }
12528                        }
12529                    }
12530                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
12531                }
12532                // make sure to preserve per-user disabled state if this removal was just
12533                // a downgrade of a system app to the factory package
12534                if (allUserHandles != null && perUserInstalled != null) {
12535                    if (DEBUG_REMOVE) {
12536                        Slog.d(TAG, "Propagating install state across downgrade");
12537                    }
12538                    for (int i = 0; i < allUserHandles.length; i++) {
12539                        if (DEBUG_REMOVE) {
12540                            Slog.d(TAG, "    user " + allUserHandles[i]
12541                                    + " => " + perUserInstalled[i]);
12542                        }
12543                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12544                    }
12545                }
12546            }
12547            // can downgrade to reader
12548            if (writeSettings) {
12549                // Save settings now
12550                mSettings.writeLPr();
12551            }
12552        }
12553        if (outInfo != null) {
12554            // A user ID was deleted here. Go through all users and remove it
12555            // from KeyStore.
12556            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
12557        }
12558    }
12559
12560    static boolean locationIsPrivileged(File path) {
12561        try {
12562            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
12563                    .getCanonicalPath();
12564            return path.getCanonicalPath().startsWith(privilegedAppDir);
12565        } catch (IOException e) {
12566            Slog.e(TAG, "Unable to access code path " + path);
12567        }
12568        return false;
12569    }
12570
12571    /*
12572     * Tries to delete system package.
12573     */
12574    private boolean deleteSystemPackageLI(PackageSetting newPs,
12575            int[] allUserHandles, boolean[] perUserInstalled,
12576            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
12577        final boolean applyUserRestrictions
12578                = (allUserHandles != null) && (perUserInstalled != null);
12579        PackageSetting disabledPs = null;
12580        // Confirm if the system package has been updated
12581        // An updated system app can be deleted. This will also have to restore
12582        // the system pkg from system partition
12583        // reader
12584        synchronized (mPackages) {
12585            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
12586        }
12587        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
12588                + " disabledPs=" + disabledPs);
12589        if (disabledPs == null) {
12590            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
12591            return false;
12592        } else if (DEBUG_REMOVE) {
12593            Slog.d(TAG, "Deleting system pkg from data partition");
12594        }
12595        if (DEBUG_REMOVE) {
12596            if (applyUserRestrictions) {
12597                Slog.d(TAG, "Remembering install states:");
12598                for (int i = 0; i < allUserHandles.length; i++) {
12599                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
12600                }
12601            }
12602        }
12603        // Delete the updated package
12604        outInfo.isRemovedPackageSystemUpdate = true;
12605        if (disabledPs.versionCode < newPs.versionCode) {
12606            // Delete data for downgrades
12607            flags &= ~PackageManager.DELETE_KEEP_DATA;
12608        } else {
12609            // Preserve data by setting flag
12610            flags |= PackageManager.DELETE_KEEP_DATA;
12611        }
12612        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
12613                allUserHandles, perUserInstalled, outInfo, writeSettings);
12614        if (!ret) {
12615            return false;
12616        }
12617        // writer
12618        synchronized (mPackages) {
12619            // Reinstate the old system package
12620            mSettings.enableSystemPackageLPw(newPs.name);
12621            // Remove any native libraries from the upgraded package.
12622            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
12623        }
12624        // Install the system package
12625        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
12626        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
12627        if (locationIsPrivileged(disabledPs.codePath)) {
12628            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12629        }
12630
12631        final PackageParser.Package newPkg;
12632        try {
12633            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
12634        } catch (PackageManagerException e) {
12635            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
12636            return false;
12637        }
12638
12639        // writer
12640        synchronized (mPackages) {
12641            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
12642            updatePermissionsLPw(newPkg.packageName, newPkg,
12643                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
12644            if (applyUserRestrictions) {
12645                if (DEBUG_REMOVE) {
12646                    Slog.d(TAG, "Propagating install state across reinstall");
12647                }
12648                for (int i = 0; i < allUserHandles.length; i++) {
12649                    if (DEBUG_REMOVE) {
12650                        Slog.d(TAG, "    user " + allUserHandles[i]
12651                                + " => " + perUserInstalled[i]);
12652                    }
12653                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12654                }
12655                // Regardless of writeSettings we need to ensure that this restriction
12656                // state propagation is persisted
12657                mSettings.writeAllUsersPackageRestrictionsLPr();
12658            }
12659            // can downgrade to reader here
12660            if (writeSettings) {
12661                mSettings.writeLPr();
12662            }
12663        }
12664        return true;
12665    }
12666
12667    private boolean deleteInstalledPackageLI(PackageSetting ps,
12668            boolean deleteCodeAndResources, int flags,
12669            int[] allUserHandles, boolean[] perUserInstalled,
12670            PackageRemovedInfo outInfo, boolean writeSettings) {
12671        if (outInfo != null) {
12672            outInfo.uid = ps.appId;
12673        }
12674
12675        // Delete package data from internal structures and also remove data if flag is set
12676        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
12677
12678        // Delete application code and resources
12679        if (deleteCodeAndResources && (outInfo != null)) {
12680            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
12681                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
12682            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
12683        }
12684        return true;
12685    }
12686
12687    @Override
12688    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
12689            int userId) {
12690        mContext.enforceCallingOrSelfPermission(
12691                android.Manifest.permission.DELETE_PACKAGES, null);
12692        synchronized (mPackages) {
12693            PackageSetting ps = mSettings.mPackages.get(packageName);
12694            if (ps == null) {
12695                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
12696                return false;
12697            }
12698            if (!ps.getInstalled(userId)) {
12699                // Can't block uninstall for an app that is not installed or enabled.
12700                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
12701                return false;
12702            }
12703            ps.setBlockUninstall(blockUninstall, userId);
12704            mSettings.writePackageRestrictionsLPr(userId);
12705        }
12706        return true;
12707    }
12708
12709    @Override
12710    public boolean getBlockUninstallForUser(String packageName, int userId) {
12711        synchronized (mPackages) {
12712            PackageSetting ps = mSettings.mPackages.get(packageName);
12713            if (ps == null) {
12714                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
12715                return false;
12716            }
12717            return ps.getBlockUninstall(userId);
12718        }
12719    }
12720
12721    /*
12722     * This method handles package deletion in general
12723     */
12724    private boolean deletePackageLI(String packageName, UserHandle user,
12725            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
12726            int flags, PackageRemovedInfo outInfo,
12727            boolean writeSettings) {
12728        if (packageName == null) {
12729            Slog.w(TAG, "Attempt to delete null packageName.");
12730            return false;
12731        }
12732        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
12733        PackageSetting ps;
12734        boolean dataOnly = false;
12735        int removeUser = -1;
12736        int appId = -1;
12737        synchronized (mPackages) {
12738            ps = mSettings.mPackages.get(packageName);
12739            if (ps == null) {
12740                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12741                return false;
12742            }
12743            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
12744                    && user.getIdentifier() != UserHandle.USER_ALL) {
12745                // The caller is asking that the package only be deleted for a single
12746                // user.  To do this, we just mark its uninstalled state and delete
12747                // its data.  If this is a system app, we only allow this to happen if
12748                // they have set the special DELETE_SYSTEM_APP which requests different
12749                // semantics than normal for uninstalling system apps.
12750                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
12751                ps.setUserState(user.getIdentifier(),
12752                        COMPONENT_ENABLED_STATE_DEFAULT,
12753                        false, //installed
12754                        true,  //stopped
12755                        true,  //notLaunched
12756                        false, //hidden
12757                        null, null, null,
12758                        false, // blockUninstall
12759                        INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
12760                if (!isSystemApp(ps)) {
12761                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
12762                        // Other user still have this package installed, so all
12763                        // we need to do is clear this user's data and save that
12764                        // it is uninstalled.
12765                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
12766                        removeUser = user.getIdentifier();
12767                        appId = ps.appId;
12768                        scheduleWritePackageRestrictionsLocked(removeUser);
12769                    } else {
12770                        // We need to set it back to 'installed' so the uninstall
12771                        // broadcasts will be sent correctly.
12772                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
12773                        ps.setInstalled(true, user.getIdentifier());
12774                    }
12775                } else {
12776                    // This is a system app, so we assume that the
12777                    // other users still have this package installed, so all
12778                    // we need to do is clear this user's data and save that
12779                    // it is uninstalled.
12780                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
12781                    removeUser = user.getIdentifier();
12782                    appId = ps.appId;
12783                    scheduleWritePackageRestrictionsLocked(removeUser);
12784                }
12785            }
12786        }
12787
12788        if (removeUser >= 0) {
12789            // From above, we determined that we are deleting this only
12790            // for a single user.  Continue the work here.
12791            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
12792            if (outInfo != null) {
12793                outInfo.removedPackage = packageName;
12794                outInfo.removedAppId = appId;
12795                outInfo.removedUsers = new int[] {removeUser};
12796            }
12797            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
12798            removeKeystoreDataIfNeeded(removeUser, appId);
12799            schedulePackageCleaning(packageName, removeUser, false);
12800            synchronized (mPackages) {
12801                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
12802                    scheduleWritePackageRestrictionsLocked(removeUser);
12803                }
12804                revokeRuntimePermissionsAndClearAllFlagsLocked(ps.getPermissionsState(),
12805                        removeUser);
12806            }
12807            return true;
12808        }
12809
12810        if (dataOnly) {
12811            // Delete application data first
12812            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
12813            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
12814            return true;
12815        }
12816
12817        boolean ret = false;
12818        if (isSystemApp(ps)) {
12819            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
12820            // When an updated system application is deleted we delete the existing resources as well and
12821            // fall back to existing code in system partition
12822            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
12823                    flags, outInfo, writeSettings);
12824        } else {
12825            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
12826            // Kill application pre-emptively especially for apps on sd.
12827            killApplication(packageName, ps.appId, "uninstall pkg");
12828            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
12829                    allUserHandles, perUserInstalled,
12830                    outInfo, writeSettings);
12831        }
12832
12833        return ret;
12834    }
12835
12836    private final class ClearStorageConnection implements ServiceConnection {
12837        IMediaContainerService mContainerService;
12838
12839        @Override
12840        public void onServiceConnected(ComponentName name, IBinder service) {
12841            synchronized (this) {
12842                mContainerService = IMediaContainerService.Stub.asInterface(service);
12843                notifyAll();
12844            }
12845        }
12846
12847        @Override
12848        public void onServiceDisconnected(ComponentName name) {
12849        }
12850    }
12851
12852    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
12853        final boolean mounted;
12854        if (Environment.isExternalStorageEmulated()) {
12855            mounted = true;
12856        } else {
12857            final String status = Environment.getExternalStorageState();
12858
12859            mounted = status.equals(Environment.MEDIA_MOUNTED)
12860                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
12861        }
12862
12863        if (!mounted) {
12864            return;
12865        }
12866
12867        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
12868        int[] users;
12869        if (userId == UserHandle.USER_ALL) {
12870            users = sUserManager.getUserIds();
12871        } else {
12872            users = new int[] { userId };
12873        }
12874        final ClearStorageConnection conn = new ClearStorageConnection();
12875        if (mContext.bindServiceAsUser(
12876                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
12877            try {
12878                for (int curUser : users) {
12879                    long timeout = SystemClock.uptimeMillis() + 5000;
12880                    synchronized (conn) {
12881                        long now = SystemClock.uptimeMillis();
12882                        while (conn.mContainerService == null && now < timeout) {
12883                            try {
12884                                conn.wait(timeout - now);
12885                            } catch (InterruptedException e) {
12886                            }
12887                        }
12888                    }
12889                    if (conn.mContainerService == null) {
12890                        return;
12891                    }
12892
12893                    final UserEnvironment userEnv = new UserEnvironment(curUser);
12894                    clearDirectory(conn.mContainerService,
12895                            userEnv.buildExternalStorageAppCacheDirs(packageName));
12896                    if (allData) {
12897                        clearDirectory(conn.mContainerService,
12898                                userEnv.buildExternalStorageAppDataDirs(packageName));
12899                        clearDirectory(conn.mContainerService,
12900                                userEnv.buildExternalStorageAppMediaDirs(packageName));
12901                    }
12902                }
12903            } finally {
12904                mContext.unbindService(conn);
12905            }
12906        }
12907    }
12908
12909    @Override
12910    public void clearApplicationUserData(final String packageName,
12911            final IPackageDataObserver observer, final int userId) {
12912        mContext.enforceCallingOrSelfPermission(
12913                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
12914        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
12915        // Queue up an async operation since the package deletion may take a little while.
12916        mHandler.post(new Runnable() {
12917            public void run() {
12918                mHandler.removeCallbacks(this);
12919                final boolean succeeded;
12920                synchronized (mInstallLock) {
12921                    succeeded = clearApplicationUserDataLI(packageName, userId);
12922                }
12923                clearExternalStorageDataSync(packageName, userId, true);
12924                if (succeeded) {
12925                    // invoke DeviceStorageMonitor's update method to clear any notifications
12926                    DeviceStorageMonitorInternal
12927                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
12928                    if (dsm != null) {
12929                        dsm.checkMemory();
12930                    }
12931                }
12932                if(observer != null) {
12933                    try {
12934                        observer.onRemoveCompleted(packageName, succeeded);
12935                    } catch (RemoteException e) {
12936                        Log.i(TAG, "Observer no longer exists.");
12937                    }
12938                } //end if observer
12939            } //end run
12940        });
12941    }
12942
12943    private boolean clearApplicationUserDataLI(String packageName, int userId) {
12944        if (packageName == null) {
12945            Slog.w(TAG, "Attempt to delete null packageName.");
12946            return false;
12947        }
12948
12949        // Try finding details about the requested package
12950        PackageParser.Package pkg;
12951        synchronized (mPackages) {
12952            pkg = mPackages.get(packageName);
12953            if (pkg == null) {
12954                final PackageSetting ps = mSettings.mPackages.get(packageName);
12955                if (ps != null) {
12956                    pkg = ps.pkg;
12957                }
12958            }
12959
12960            if (pkg == null) {
12961                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12962                return false;
12963            }
12964
12965            PackageSetting ps = (PackageSetting) pkg.mExtras;
12966            PermissionsState permissionsState = ps.getPermissionsState();
12967            revokeRuntimePermissionsAndClearUserSetFlagsLocked(permissionsState, userId);
12968        }
12969
12970        // Always delete data directories for package, even if we found no other
12971        // record of app. This helps users recover from UID mismatches without
12972        // resorting to a full data wipe.
12973        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
12974        if (retCode < 0) {
12975            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
12976            return false;
12977        }
12978
12979        final int appId = pkg.applicationInfo.uid;
12980        removeKeystoreDataIfNeeded(userId, appId);
12981
12982        // Create a native library symlink only if we have native libraries
12983        // and if the native libraries are 32 bit libraries. We do not provide
12984        // this symlink for 64 bit libraries.
12985        if (pkg.applicationInfo.primaryCpuAbi != null &&
12986                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
12987            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
12988            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
12989                    nativeLibPath, userId) < 0) {
12990                Slog.w(TAG, "Failed linking native library dir");
12991                return false;
12992            }
12993        }
12994
12995        return true;
12996    }
12997
12998
12999    /**
13000     * Revokes granted runtime permissions and clears resettable flags
13001     * which are flags that can be set by a user interaction.
13002     *
13003     * @param permissionsState The permission state to reset.
13004     * @param userId The device user for which to do a reset.
13005     */
13006    private void revokeRuntimePermissionsAndClearUserSetFlagsLocked(
13007            PermissionsState permissionsState, int userId) {
13008        final int userSetFlags = PackageManager.FLAG_PERMISSION_USER_SET
13009                | PackageManager.FLAG_PERMISSION_USER_FIXED
13010                | PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13011
13012        revokeRuntimePermissionsAndClearFlagsLocked(permissionsState, userId, userSetFlags);
13013    }
13014
13015    /**
13016     * Revokes granted runtime permissions and clears all flags.
13017     *
13018     * @param permissionsState The permission state to reset.
13019     * @param userId The device user for which to do a reset.
13020     */
13021    private void revokeRuntimePermissionsAndClearAllFlagsLocked(
13022            PermissionsState permissionsState, int userId) {
13023        revokeRuntimePermissionsAndClearFlagsLocked(permissionsState, userId,
13024                PackageManager.MASK_PERMISSION_FLAGS);
13025    }
13026
13027    /**
13028     * Revokes granted runtime permissions and clears certain flags.
13029     *
13030     * @param permissionsState The permission state to reset.
13031     * @param userId The device user for which to do a reset.
13032     * @param flags The flags that is going to be reset.
13033     */
13034    private void revokeRuntimePermissionsAndClearFlagsLocked(
13035            PermissionsState permissionsState, final int userId, int flags) {
13036        boolean needsWrite = false;
13037
13038        for (PermissionState state : permissionsState.getRuntimePermissionStates(userId)) {
13039            BasePermission bp = mSettings.mPermissions.get(state.getName());
13040            if (bp != null) {
13041                permissionsState.revokeRuntimePermission(bp, userId);
13042                permissionsState.updatePermissionFlags(bp, userId, flags, 0);
13043                needsWrite = true;
13044            }
13045        }
13046
13047        // Ensure default permissions are never cleared.
13048        mHandler.post(new Runnable() {
13049            @Override
13050            public void run() {
13051                mDefaultPermissionPolicy.grantDefaultPermissions(userId);
13052            }
13053        });
13054
13055        if (needsWrite) {
13056            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
13057        }
13058    }
13059
13060    /**
13061     * Remove entries from the keystore daemon. Will only remove it if the
13062     * {@code appId} is valid.
13063     */
13064    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
13065        if (appId < 0) {
13066            return;
13067        }
13068
13069        final KeyStore keyStore = KeyStore.getInstance();
13070        if (keyStore != null) {
13071            if (userId == UserHandle.USER_ALL) {
13072                for (final int individual : sUserManager.getUserIds()) {
13073                    keyStore.clearUid(UserHandle.getUid(individual, appId));
13074                }
13075            } else {
13076                keyStore.clearUid(UserHandle.getUid(userId, appId));
13077            }
13078        } else {
13079            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
13080        }
13081    }
13082
13083    @Override
13084    public void deleteApplicationCacheFiles(final String packageName,
13085            final IPackageDataObserver observer) {
13086        mContext.enforceCallingOrSelfPermission(
13087                android.Manifest.permission.DELETE_CACHE_FILES, null);
13088        // Queue up an async operation since the package deletion may take a little while.
13089        final int userId = UserHandle.getCallingUserId();
13090        mHandler.post(new Runnable() {
13091            public void run() {
13092                mHandler.removeCallbacks(this);
13093                final boolean succeded;
13094                synchronized (mInstallLock) {
13095                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
13096                }
13097                clearExternalStorageDataSync(packageName, userId, false);
13098                if (observer != null) {
13099                    try {
13100                        observer.onRemoveCompleted(packageName, succeded);
13101                    } catch (RemoteException e) {
13102                        Log.i(TAG, "Observer no longer exists.");
13103                    }
13104                } //end if observer
13105            } //end run
13106        });
13107    }
13108
13109    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
13110        if (packageName == null) {
13111            Slog.w(TAG, "Attempt to delete null packageName.");
13112            return false;
13113        }
13114        PackageParser.Package p;
13115        synchronized (mPackages) {
13116            p = mPackages.get(packageName);
13117        }
13118        if (p == null) {
13119            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13120            return false;
13121        }
13122        final ApplicationInfo applicationInfo = p.applicationInfo;
13123        if (applicationInfo == null) {
13124            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13125            return false;
13126        }
13127        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
13128        if (retCode < 0) {
13129            Slog.w(TAG, "Couldn't remove cache files for package: "
13130                       + packageName + " u" + userId);
13131            return false;
13132        }
13133        return true;
13134    }
13135
13136    @Override
13137    public void getPackageSizeInfo(final String packageName, int userHandle,
13138            final IPackageStatsObserver observer) {
13139        mContext.enforceCallingOrSelfPermission(
13140                android.Manifest.permission.GET_PACKAGE_SIZE, null);
13141        if (packageName == null) {
13142            throw new IllegalArgumentException("Attempt to get size of null packageName");
13143        }
13144
13145        PackageStats stats = new PackageStats(packageName, userHandle);
13146
13147        /*
13148         * Queue up an async operation since the package measurement may take a
13149         * little while.
13150         */
13151        Message msg = mHandler.obtainMessage(INIT_COPY);
13152        msg.obj = new MeasureParams(stats, observer);
13153        mHandler.sendMessage(msg);
13154    }
13155
13156    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
13157            PackageStats pStats) {
13158        if (packageName == null) {
13159            Slog.w(TAG, "Attempt to get size of null packageName.");
13160            return false;
13161        }
13162        PackageParser.Package p;
13163        boolean dataOnly = false;
13164        String libDirRoot = null;
13165        String asecPath = null;
13166        PackageSetting ps = null;
13167        synchronized (mPackages) {
13168            p = mPackages.get(packageName);
13169            ps = mSettings.mPackages.get(packageName);
13170            if(p == null) {
13171                dataOnly = true;
13172                if((ps == null) || (ps.pkg == null)) {
13173                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13174                    return false;
13175                }
13176                p = ps.pkg;
13177            }
13178            if (ps != null) {
13179                libDirRoot = ps.legacyNativeLibraryPathString;
13180            }
13181            if (p != null && (isExternal(p) || p.isForwardLocked())) {
13182                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
13183                if (secureContainerId != null) {
13184                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
13185                }
13186            }
13187        }
13188        String publicSrcDir = null;
13189        if(!dataOnly) {
13190            final ApplicationInfo applicationInfo = p.applicationInfo;
13191            if (applicationInfo == null) {
13192                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13193                return false;
13194            }
13195            if (p.isForwardLocked()) {
13196                publicSrcDir = applicationInfo.getBaseResourcePath();
13197            }
13198        }
13199        // TODO: extend to measure size of split APKs
13200        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
13201        // not just the first level.
13202        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
13203        // just the primary.
13204        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
13205        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath,
13206                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
13207        if (res < 0) {
13208            return false;
13209        }
13210
13211        // Fix-up for forward-locked applications in ASEC containers.
13212        if (!isExternal(p)) {
13213            pStats.codeSize += pStats.externalCodeSize;
13214            pStats.externalCodeSize = 0L;
13215        }
13216
13217        return true;
13218    }
13219
13220
13221    @Override
13222    public void addPackageToPreferred(String packageName) {
13223        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
13224    }
13225
13226    @Override
13227    public void removePackageFromPreferred(String packageName) {
13228        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
13229    }
13230
13231    @Override
13232    public List<PackageInfo> getPreferredPackages(int flags) {
13233        return new ArrayList<PackageInfo>();
13234    }
13235
13236    private int getUidTargetSdkVersionLockedLPr(int uid) {
13237        Object obj = mSettings.getUserIdLPr(uid);
13238        if (obj instanceof SharedUserSetting) {
13239            final SharedUserSetting sus = (SharedUserSetting) obj;
13240            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
13241            final Iterator<PackageSetting> it = sus.packages.iterator();
13242            while (it.hasNext()) {
13243                final PackageSetting ps = it.next();
13244                if (ps.pkg != null) {
13245                    int v = ps.pkg.applicationInfo.targetSdkVersion;
13246                    if (v < vers) vers = v;
13247                }
13248            }
13249            return vers;
13250        } else if (obj instanceof PackageSetting) {
13251            final PackageSetting ps = (PackageSetting) obj;
13252            if (ps.pkg != null) {
13253                return ps.pkg.applicationInfo.targetSdkVersion;
13254            }
13255        }
13256        return Build.VERSION_CODES.CUR_DEVELOPMENT;
13257    }
13258
13259    @Override
13260    public void addPreferredActivity(IntentFilter filter, int match,
13261            ComponentName[] set, ComponentName activity, int userId) {
13262        addPreferredActivityInternal(filter, match, set, activity, true, userId,
13263                "Adding preferred");
13264    }
13265
13266    private void addPreferredActivityInternal(IntentFilter filter, int match,
13267            ComponentName[] set, ComponentName activity, boolean always, int userId,
13268            String opname) {
13269        // writer
13270        int callingUid = Binder.getCallingUid();
13271        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
13272        if (filter.countActions() == 0) {
13273            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13274            return;
13275        }
13276        synchronized (mPackages) {
13277            if (mContext.checkCallingOrSelfPermission(
13278                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13279                    != PackageManager.PERMISSION_GRANTED) {
13280                if (getUidTargetSdkVersionLockedLPr(callingUid)
13281                        < Build.VERSION_CODES.FROYO) {
13282                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
13283                            + callingUid);
13284                    return;
13285                }
13286                mContext.enforceCallingOrSelfPermission(
13287                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13288            }
13289
13290            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
13291            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
13292                    + userId + ":");
13293            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13294            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
13295            scheduleWritePackageRestrictionsLocked(userId);
13296        }
13297    }
13298
13299    @Override
13300    public void replacePreferredActivity(IntentFilter filter, int match,
13301            ComponentName[] set, ComponentName activity, int userId) {
13302        if (filter.countActions() != 1) {
13303            throw new IllegalArgumentException(
13304                    "replacePreferredActivity expects filter to have only 1 action.");
13305        }
13306        if (filter.countDataAuthorities() != 0
13307                || filter.countDataPaths() != 0
13308                || filter.countDataSchemes() > 1
13309                || filter.countDataTypes() != 0) {
13310            throw new IllegalArgumentException(
13311                    "replacePreferredActivity expects filter to have no data authorities, " +
13312                    "paths, or types; and at most one scheme.");
13313        }
13314
13315        final int callingUid = Binder.getCallingUid();
13316        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
13317        synchronized (mPackages) {
13318            if (mContext.checkCallingOrSelfPermission(
13319                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13320                    != PackageManager.PERMISSION_GRANTED) {
13321                if (getUidTargetSdkVersionLockedLPr(callingUid)
13322                        < Build.VERSION_CODES.FROYO) {
13323                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
13324                            + Binder.getCallingUid());
13325                    return;
13326                }
13327                mContext.enforceCallingOrSelfPermission(
13328                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13329            }
13330
13331            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13332            if (pir != null) {
13333                // Get all of the existing entries that exactly match this filter.
13334                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
13335                if (existing != null && existing.size() == 1) {
13336                    PreferredActivity cur = existing.get(0);
13337                    if (DEBUG_PREFERRED) {
13338                        Slog.i(TAG, "Checking replace of preferred:");
13339                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13340                        if (!cur.mPref.mAlways) {
13341                            Slog.i(TAG, "  -- CUR; not mAlways!");
13342                        } else {
13343                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
13344                            Slog.i(TAG, "  -- CUR: mSet="
13345                                    + Arrays.toString(cur.mPref.mSetComponents));
13346                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
13347                            Slog.i(TAG, "  -- NEW: mMatch="
13348                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
13349                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
13350                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
13351                        }
13352                    }
13353                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
13354                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
13355                            && cur.mPref.sameSet(set)) {
13356                        // Setting the preferred activity to what it happens to be already
13357                        if (DEBUG_PREFERRED) {
13358                            Slog.i(TAG, "Replacing with same preferred activity "
13359                                    + cur.mPref.mShortComponent + " for user "
13360                                    + userId + ":");
13361                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13362                        }
13363                        return;
13364                    }
13365                }
13366
13367                if (existing != null) {
13368                    if (DEBUG_PREFERRED) {
13369                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
13370                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13371                    }
13372                    for (int i = 0; i < existing.size(); i++) {
13373                        PreferredActivity pa = existing.get(i);
13374                        if (DEBUG_PREFERRED) {
13375                            Slog.i(TAG, "Removing existing preferred activity "
13376                                    + pa.mPref.mComponent + ":");
13377                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
13378                        }
13379                        pir.removeFilter(pa);
13380                    }
13381                }
13382            }
13383            addPreferredActivityInternal(filter, match, set, activity, true, userId,
13384                    "Replacing preferred");
13385        }
13386    }
13387
13388    @Override
13389    public void clearPackagePreferredActivities(String packageName) {
13390        final int uid = Binder.getCallingUid();
13391        // writer
13392        synchronized (mPackages) {
13393            PackageParser.Package pkg = mPackages.get(packageName);
13394            if (pkg == null || pkg.applicationInfo.uid != uid) {
13395                if (mContext.checkCallingOrSelfPermission(
13396                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13397                        != PackageManager.PERMISSION_GRANTED) {
13398                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
13399                            < Build.VERSION_CODES.FROYO) {
13400                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
13401                                + Binder.getCallingUid());
13402                        return;
13403                    }
13404                    mContext.enforceCallingOrSelfPermission(
13405                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13406                }
13407            }
13408
13409            int user = UserHandle.getCallingUserId();
13410            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
13411                scheduleWritePackageRestrictionsLocked(user);
13412            }
13413        }
13414    }
13415
13416    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13417    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
13418        ArrayList<PreferredActivity> removed = null;
13419        boolean changed = false;
13420        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13421            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
13422            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13423            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
13424                continue;
13425            }
13426            Iterator<PreferredActivity> it = pir.filterIterator();
13427            while (it.hasNext()) {
13428                PreferredActivity pa = it.next();
13429                // Mark entry for removal only if it matches the package name
13430                // and the entry is of type "always".
13431                if (packageName == null ||
13432                        (pa.mPref.mComponent.getPackageName().equals(packageName)
13433                                && pa.mPref.mAlways)) {
13434                    if (removed == null) {
13435                        removed = new ArrayList<PreferredActivity>();
13436                    }
13437                    removed.add(pa);
13438                }
13439            }
13440            if (removed != null) {
13441                for (int j=0; j<removed.size(); j++) {
13442                    PreferredActivity pa = removed.get(j);
13443                    pir.removeFilter(pa);
13444                }
13445                changed = true;
13446            }
13447        }
13448        return changed;
13449    }
13450
13451    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13452    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
13453        if (userId == UserHandle.USER_ALL) {
13454            if (mSettings.removeIntentFilterVerificationLPw(packageName,
13455                    sUserManager.getUserIds())) {
13456                for (int oneUserId : sUserManager.getUserIds()) {
13457                    scheduleWritePackageRestrictionsLocked(oneUserId);
13458                }
13459            }
13460        } else {
13461            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
13462                scheduleWritePackageRestrictionsLocked(userId);
13463            }
13464        }
13465    }
13466
13467
13468    void clearDefaultBrowserIfNeeded(String packageName) {
13469        for (int oneUserId : sUserManager.getUserIds()) {
13470            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
13471            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
13472            if (packageName.equals(defaultBrowserPackageName)) {
13473                setDefaultBrowserPackageName(null, oneUserId);
13474            }
13475        }
13476    }
13477
13478    @Override
13479    public void resetPreferredActivities(int userId) {
13480        mContext.enforceCallingOrSelfPermission(
13481                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13482        // writer
13483        synchronized (mPackages) {
13484            clearPackagePreferredActivitiesLPw(null, userId);
13485            mSettings.applyDefaultPreferredAppsLPw(this, userId);
13486            applyFactoryDefaultBrowserLPw(userId);
13487
13488            scheduleWritePackageRestrictionsLocked(userId);
13489        }
13490    }
13491
13492    @Override
13493    public int getPreferredActivities(List<IntentFilter> outFilters,
13494            List<ComponentName> outActivities, String packageName) {
13495
13496        int num = 0;
13497        final int userId = UserHandle.getCallingUserId();
13498        // reader
13499        synchronized (mPackages) {
13500            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13501            if (pir != null) {
13502                final Iterator<PreferredActivity> it = pir.filterIterator();
13503                while (it.hasNext()) {
13504                    final PreferredActivity pa = it.next();
13505                    if (packageName == null
13506                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
13507                                    && pa.mPref.mAlways)) {
13508                        if (outFilters != null) {
13509                            outFilters.add(new IntentFilter(pa));
13510                        }
13511                        if (outActivities != null) {
13512                            outActivities.add(pa.mPref.mComponent);
13513                        }
13514                    }
13515                }
13516            }
13517        }
13518
13519        return num;
13520    }
13521
13522    @Override
13523    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
13524            int userId) {
13525        int callingUid = Binder.getCallingUid();
13526        if (callingUid != Process.SYSTEM_UID) {
13527            throw new SecurityException(
13528                    "addPersistentPreferredActivity can only be run by the system");
13529        }
13530        if (filter.countActions() == 0) {
13531            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13532            return;
13533        }
13534        synchronized (mPackages) {
13535            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
13536                    " :");
13537            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13538            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
13539                    new PersistentPreferredActivity(filter, activity));
13540            scheduleWritePackageRestrictionsLocked(userId);
13541        }
13542    }
13543
13544    @Override
13545    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
13546        int callingUid = Binder.getCallingUid();
13547        if (callingUid != Process.SYSTEM_UID) {
13548            throw new SecurityException(
13549                    "clearPackagePersistentPreferredActivities can only be run by the system");
13550        }
13551        ArrayList<PersistentPreferredActivity> removed = null;
13552        boolean changed = false;
13553        synchronized (mPackages) {
13554            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
13555                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
13556                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
13557                        .valueAt(i);
13558                if (userId != thisUserId) {
13559                    continue;
13560                }
13561                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
13562                while (it.hasNext()) {
13563                    PersistentPreferredActivity ppa = it.next();
13564                    // Mark entry for removal only if it matches the package name.
13565                    if (ppa.mComponent.getPackageName().equals(packageName)) {
13566                        if (removed == null) {
13567                            removed = new ArrayList<PersistentPreferredActivity>();
13568                        }
13569                        removed.add(ppa);
13570                    }
13571                }
13572                if (removed != null) {
13573                    for (int j=0; j<removed.size(); j++) {
13574                        PersistentPreferredActivity ppa = removed.get(j);
13575                        ppir.removeFilter(ppa);
13576                    }
13577                    changed = true;
13578                }
13579            }
13580
13581            if (changed) {
13582                scheduleWritePackageRestrictionsLocked(userId);
13583            }
13584        }
13585    }
13586
13587    /**
13588     * Common machinery for picking apart a restored XML blob and passing
13589     * it to a caller-supplied functor to be applied to the running system.
13590     */
13591    private void restoreFromXml(XmlPullParser parser, int userId,
13592            String expectedStartTag, BlobXmlRestorer functor)
13593            throws IOException, XmlPullParserException {
13594        int type;
13595        while ((type = parser.next()) != XmlPullParser.START_TAG
13596                && type != XmlPullParser.END_DOCUMENT) {
13597        }
13598        if (type != XmlPullParser.START_TAG) {
13599            // oops didn't find a start tag?!
13600            if (DEBUG_BACKUP) {
13601                Slog.e(TAG, "Didn't find start tag during restore");
13602            }
13603            return;
13604        }
13605
13606        // this is supposed to be TAG_PREFERRED_BACKUP
13607        if (!expectedStartTag.equals(parser.getName())) {
13608            if (DEBUG_BACKUP) {
13609                Slog.e(TAG, "Found unexpected tag " + parser.getName());
13610            }
13611            return;
13612        }
13613
13614        // skip interfering stuff, then we're aligned with the backing implementation
13615        while ((type = parser.next()) == XmlPullParser.TEXT) { }
13616        functor.apply(parser, userId);
13617    }
13618
13619    private interface BlobXmlRestorer {
13620        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
13621    }
13622
13623    /**
13624     * Non-Binder method, support for the backup/restore mechanism: write the
13625     * full set of preferred activities in its canonical XML format.  Returns the
13626     * XML output as a byte array, or null if there is none.
13627     */
13628    @Override
13629    public byte[] getPreferredActivityBackup(int userId) {
13630        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13631            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
13632        }
13633
13634        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13635        try {
13636            final XmlSerializer serializer = new FastXmlSerializer();
13637            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13638            serializer.startDocument(null, true);
13639            serializer.startTag(null, TAG_PREFERRED_BACKUP);
13640
13641            synchronized (mPackages) {
13642                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
13643            }
13644
13645            serializer.endTag(null, TAG_PREFERRED_BACKUP);
13646            serializer.endDocument();
13647            serializer.flush();
13648        } catch (Exception e) {
13649            if (DEBUG_BACKUP) {
13650                Slog.e(TAG, "Unable to write preferred activities for backup", e);
13651            }
13652            return null;
13653        }
13654
13655        return dataStream.toByteArray();
13656    }
13657
13658    @Override
13659    public void restorePreferredActivities(byte[] backup, int userId) {
13660        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13661            throw new SecurityException("Only the system may call restorePreferredActivities()");
13662        }
13663
13664        try {
13665            final XmlPullParser parser = Xml.newPullParser();
13666            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13667            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
13668                    new BlobXmlRestorer() {
13669                        @Override
13670                        public void apply(XmlPullParser parser, int userId)
13671                                throws XmlPullParserException, IOException {
13672                            synchronized (mPackages) {
13673                                mSettings.readPreferredActivitiesLPw(parser, userId);
13674                            }
13675                        }
13676                    } );
13677        } catch (Exception e) {
13678            if (DEBUG_BACKUP) {
13679                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
13680            }
13681        }
13682    }
13683
13684    /**
13685     * Non-Binder method, support for the backup/restore mechanism: write the
13686     * default browser (etc) settings in its canonical XML format.  Returns the default
13687     * browser XML representation as a byte array, or null if there is none.
13688     */
13689    @Override
13690    public byte[] getDefaultAppsBackup(int userId) {
13691        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13692            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
13693        }
13694
13695        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13696        try {
13697            final XmlSerializer serializer = new FastXmlSerializer();
13698            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13699            serializer.startDocument(null, true);
13700            serializer.startTag(null, TAG_DEFAULT_APPS);
13701
13702            synchronized (mPackages) {
13703                mSettings.writeDefaultAppsLPr(serializer, userId);
13704            }
13705
13706            serializer.endTag(null, TAG_DEFAULT_APPS);
13707            serializer.endDocument();
13708            serializer.flush();
13709        } catch (Exception e) {
13710            if (DEBUG_BACKUP) {
13711                Slog.e(TAG, "Unable to write default apps for backup", e);
13712            }
13713            return null;
13714        }
13715
13716        return dataStream.toByteArray();
13717    }
13718
13719    @Override
13720    public void restoreDefaultApps(byte[] backup, int userId) {
13721        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13722            throw new SecurityException("Only the system may call restoreDefaultApps()");
13723        }
13724
13725        try {
13726            final XmlPullParser parser = Xml.newPullParser();
13727            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13728            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
13729                    new BlobXmlRestorer() {
13730                        @Override
13731                        public void apply(XmlPullParser parser, int userId)
13732                                throws XmlPullParserException, IOException {
13733                            synchronized (mPackages) {
13734                                mSettings.readDefaultAppsLPw(parser, userId);
13735                            }
13736                        }
13737                    } );
13738        } catch (Exception e) {
13739            if (DEBUG_BACKUP) {
13740                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
13741            }
13742        }
13743    }
13744
13745    @Override
13746    public byte[] getIntentFilterVerificationBackup(int userId) {
13747        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13748            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
13749        }
13750
13751        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13752        try {
13753            final XmlSerializer serializer = new FastXmlSerializer();
13754            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13755            serializer.startDocument(null, true);
13756            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
13757
13758            synchronized (mPackages) {
13759                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
13760            }
13761
13762            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
13763            serializer.endDocument();
13764            serializer.flush();
13765        } catch (Exception e) {
13766            if (DEBUG_BACKUP) {
13767                Slog.e(TAG, "Unable to write default apps for backup", e);
13768            }
13769            return null;
13770        }
13771
13772        return dataStream.toByteArray();
13773    }
13774
13775    @Override
13776    public void restoreIntentFilterVerification(byte[] backup, int userId) {
13777        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13778            throw new SecurityException("Only the system may call restorePreferredActivities()");
13779        }
13780
13781        try {
13782            final XmlPullParser parser = Xml.newPullParser();
13783            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13784            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
13785                    new BlobXmlRestorer() {
13786                        @Override
13787                        public void apply(XmlPullParser parser, int userId)
13788                                throws XmlPullParserException, IOException {
13789                            synchronized (mPackages) {
13790                                mSettings.readAllDomainVerificationsLPr(parser, userId);
13791                                mSettings.writeLPr();
13792                            }
13793                        }
13794                    } );
13795        } catch (Exception e) {
13796            if (DEBUG_BACKUP) {
13797                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
13798            }
13799        }
13800    }
13801
13802    @Override
13803    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
13804            int sourceUserId, int targetUserId, int flags) {
13805        mContext.enforceCallingOrSelfPermission(
13806                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
13807        int callingUid = Binder.getCallingUid();
13808        enforceOwnerRights(ownerPackage, callingUid);
13809        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
13810        if (intentFilter.countActions() == 0) {
13811            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
13812            return;
13813        }
13814        synchronized (mPackages) {
13815            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
13816                    ownerPackage, targetUserId, flags);
13817            CrossProfileIntentResolver resolver =
13818                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
13819            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
13820            // We have all those whose filter is equal. Now checking if the rest is equal as well.
13821            if (existing != null) {
13822                int size = existing.size();
13823                for (int i = 0; i < size; i++) {
13824                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
13825                        return;
13826                    }
13827                }
13828            }
13829            resolver.addFilter(newFilter);
13830            scheduleWritePackageRestrictionsLocked(sourceUserId);
13831        }
13832    }
13833
13834    @Override
13835    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
13836        mContext.enforceCallingOrSelfPermission(
13837                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
13838        int callingUid = Binder.getCallingUid();
13839        enforceOwnerRights(ownerPackage, callingUid);
13840        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
13841        synchronized (mPackages) {
13842            CrossProfileIntentResolver resolver =
13843                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
13844            ArraySet<CrossProfileIntentFilter> set =
13845                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
13846            for (CrossProfileIntentFilter filter : set) {
13847                if (filter.getOwnerPackage().equals(ownerPackage)) {
13848                    resolver.removeFilter(filter);
13849                }
13850            }
13851            scheduleWritePackageRestrictionsLocked(sourceUserId);
13852        }
13853    }
13854
13855    // Enforcing that callingUid is owning pkg on userId
13856    private void enforceOwnerRights(String pkg, int callingUid) {
13857        // The system owns everything.
13858        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
13859            return;
13860        }
13861        int callingUserId = UserHandle.getUserId(callingUid);
13862        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
13863        if (pi == null) {
13864            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
13865                    + callingUserId);
13866        }
13867        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
13868            throw new SecurityException("Calling uid " + callingUid
13869                    + " does not own package " + pkg);
13870        }
13871    }
13872
13873    @Override
13874    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
13875        Intent intent = new Intent(Intent.ACTION_MAIN);
13876        intent.addCategory(Intent.CATEGORY_HOME);
13877
13878        final int callingUserId = UserHandle.getCallingUserId();
13879        List<ResolveInfo> list = queryIntentActivities(intent, null,
13880                PackageManager.GET_META_DATA, callingUserId);
13881        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
13882                true, false, false, callingUserId);
13883
13884        allHomeCandidates.clear();
13885        if (list != null) {
13886            for (ResolveInfo ri : list) {
13887                allHomeCandidates.add(ri);
13888            }
13889        }
13890        return (preferred == null || preferred.activityInfo == null)
13891                ? null
13892                : new ComponentName(preferred.activityInfo.packageName,
13893                        preferred.activityInfo.name);
13894    }
13895
13896    @Override
13897    public void setApplicationEnabledSetting(String appPackageName,
13898            int newState, int flags, int userId, String callingPackage) {
13899        if (!sUserManager.exists(userId)) return;
13900        if (callingPackage == null) {
13901            callingPackage = Integer.toString(Binder.getCallingUid());
13902        }
13903        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
13904    }
13905
13906    @Override
13907    public void setComponentEnabledSetting(ComponentName componentName,
13908            int newState, int flags, int userId) {
13909        if (!sUserManager.exists(userId)) return;
13910        setEnabledSetting(componentName.getPackageName(),
13911                componentName.getClassName(), newState, flags, userId, null);
13912    }
13913
13914    private void setEnabledSetting(final String packageName, String className, int newState,
13915            final int flags, int userId, String callingPackage) {
13916        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
13917              || newState == COMPONENT_ENABLED_STATE_ENABLED
13918              || newState == COMPONENT_ENABLED_STATE_DISABLED
13919              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
13920              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
13921            throw new IllegalArgumentException("Invalid new component state: "
13922                    + newState);
13923        }
13924        PackageSetting pkgSetting;
13925        final int uid = Binder.getCallingUid();
13926        final int permission = mContext.checkCallingOrSelfPermission(
13927                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
13928        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
13929        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
13930        boolean sendNow = false;
13931        boolean isApp = (className == null);
13932        String componentName = isApp ? packageName : className;
13933        int packageUid = -1;
13934        ArrayList<String> components;
13935
13936        // writer
13937        synchronized (mPackages) {
13938            pkgSetting = mSettings.mPackages.get(packageName);
13939            if (pkgSetting == null) {
13940                if (className == null) {
13941                    throw new IllegalArgumentException(
13942                            "Unknown package: " + packageName);
13943                }
13944                throw new IllegalArgumentException(
13945                        "Unknown component: " + packageName
13946                        + "/" + className);
13947            }
13948            // Allow root and verify that userId is not being specified by a different user
13949            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
13950                throw new SecurityException(
13951                        "Permission Denial: attempt to change component state from pid="
13952                        + Binder.getCallingPid()
13953                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
13954            }
13955            if (className == null) {
13956                // We're dealing with an application/package level state change
13957                if (pkgSetting.getEnabled(userId) == newState) {
13958                    // Nothing to do
13959                    return;
13960                }
13961                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
13962                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
13963                    // Don't care about who enables an app.
13964                    callingPackage = null;
13965                }
13966                pkgSetting.setEnabled(newState, userId, callingPackage);
13967                // pkgSetting.pkg.mSetEnabled = newState;
13968            } else {
13969                // We're dealing with a component level state change
13970                // First, verify that this is a valid class name.
13971                PackageParser.Package pkg = pkgSetting.pkg;
13972                if (pkg == null || !pkg.hasComponentClassName(className)) {
13973                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
13974                        throw new IllegalArgumentException("Component class " + className
13975                                + " does not exist in " + packageName);
13976                    } else {
13977                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
13978                                + className + " does not exist in " + packageName);
13979                    }
13980                }
13981                switch (newState) {
13982                case COMPONENT_ENABLED_STATE_ENABLED:
13983                    if (!pkgSetting.enableComponentLPw(className, userId)) {
13984                        return;
13985                    }
13986                    break;
13987                case COMPONENT_ENABLED_STATE_DISABLED:
13988                    if (!pkgSetting.disableComponentLPw(className, userId)) {
13989                        return;
13990                    }
13991                    break;
13992                case COMPONENT_ENABLED_STATE_DEFAULT:
13993                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
13994                        return;
13995                    }
13996                    break;
13997                default:
13998                    Slog.e(TAG, "Invalid new component state: " + newState);
13999                    return;
14000                }
14001            }
14002            scheduleWritePackageRestrictionsLocked(userId);
14003            components = mPendingBroadcasts.get(userId, packageName);
14004            final boolean newPackage = components == null;
14005            if (newPackage) {
14006                components = new ArrayList<String>();
14007            }
14008            if (!components.contains(componentName)) {
14009                components.add(componentName);
14010            }
14011            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
14012                sendNow = true;
14013                // Purge entry from pending broadcast list if another one exists already
14014                // since we are sending one right away.
14015                mPendingBroadcasts.remove(userId, packageName);
14016            } else {
14017                if (newPackage) {
14018                    mPendingBroadcasts.put(userId, packageName, components);
14019                }
14020                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
14021                    // Schedule a message
14022                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
14023                }
14024            }
14025        }
14026
14027        long callingId = Binder.clearCallingIdentity();
14028        try {
14029            if (sendNow) {
14030                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
14031                sendPackageChangedBroadcast(packageName,
14032                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
14033            }
14034        } finally {
14035            Binder.restoreCallingIdentity(callingId);
14036        }
14037    }
14038
14039    private void sendPackageChangedBroadcast(String packageName,
14040            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
14041        if (DEBUG_INSTALL)
14042            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
14043                    + componentNames);
14044        Bundle extras = new Bundle(4);
14045        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
14046        String nameList[] = new String[componentNames.size()];
14047        componentNames.toArray(nameList);
14048        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
14049        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
14050        extras.putInt(Intent.EXTRA_UID, packageUid);
14051        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
14052                new int[] {UserHandle.getUserId(packageUid)});
14053    }
14054
14055    @Override
14056    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
14057        if (!sUserManager.exists(userId)) return;
14058        final int uid = Binder.getCallingUid();
14059        final int permission = mContext.checkCallingOrSelfPermission(
14060                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14061        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14062        enforceCrossUserPermission(uid, userId, true, true, "stop package");
14063        // writer
14064        synchronized (mPackages) {
14065            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
14066                    allowedByPermission, uid, userId)) {
14067                scheduleWritePackageRestrictionsLocked(userId);
14068            }
14069        }
14070    }
14071
14072    @Override
14073    public String getInstallerPackageName(String packageName) {
14074        // reader
14075        synchronized (mPackages) {
14076            return mSettings.getInstallerPackageNameLPr(packageName);
14077        }
14078    }
14079
14080    @Override
14081    public int getApplicationEnabledSetting(String packageName, int userId) {
14082        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14083        int uid = Binder.getCallingUid();
14084        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
14085        // reader
14086        synchronized (mPackages) {
14087            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
14088        }
14089    }
14090
14091    @Override
14092    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
14093        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14094        int uid = Binder.getCallingUid();
14095        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
14096        // reader
14097        synchronized (mPackages) {
14098            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
14099        }
14100    }
14101
14102    @Override
14103    public void enterSafeMode() {
14104        enforceSystemOrRoot("Only the system can request entering safe mode");
14105
14106        if (!mSystemReady) {
14107            mSafeMode = true;
14108        }
14109    }
14110
14111    @Override
14112    public void systemReady() {
14113        mSystemReady = true;
14114
14115        // Read the compatibilty setting when the system is ready.
14116        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
14117                mContext.getContentResolver(),
14118                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
14119        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
14120        if (DEBUG_SETTINGS) {
14121            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
14122        }
14123
14124        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
14125
14126        synchronized (mPackages) {
14127            // Verify that all of the preferred activity components actually
14128            // exist.  It is possible for applications to be updated and at
14129            // that point remove a previously declared activity component that
14130            // had been set as a preferred activity.  We try to clean this up
14131            // the next time we encounter that preferred activity, but it is
14132            // possible for the user flow to never be able to return to that
14133            // situation so here we do a sanity check to make sure we haven't
14134            // left any junk around.
14135            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
14136            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14137                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14138                removed.clear();
14139                for (PreferredActivity pa : pir.filterSet()) {
14140                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
14141                        removed.add(pa);
14142                    }
14143                }
14144                if (removed.size() > 0) {
14145                    for (int r=0; r<removed.size(); r++) {
14146                        PreferredActivity pa = removed.get(r);
14147                        Slog.w(TAG, "Removing dangling preferred activity: "
14148                                + pa.mPref.mComponent);
14149                        pir.removeFilter(pa);
14150                    }
14151                    mSettings.writePackageRestrictionsLPr(
14152                            mSettings.mPreferredActivities.keyAt(i));
14153                }
14154            }
14155
14156            for (int userId : UserManagerService.getInstance().getUserIds()) {
14157                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
14158                    grantPermissionsUserIds = ArrayUtils.appendInt(
14159                            grantPermissionsUserIds, userId);
14160                }
14161            }
14162        }
14163        sUserManager.systemReady();
14164
14165        // If we upgraded grant all default permissions before kicking off.
14166        for (int userId : grantPermissionsUserIds) {
14167            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
14168        }
14169
14170        // Kick off any messages waiting for system ready
14171        if (mPostSystemReadyMessages != null) {
14172            for (Message msg : mPostSystemReadyMessages) {
14173                msg.sendToTarget();
14174            }
14175            mPostSystemReadyMessages = null;
14176        }
14177
14178        // Watch for external volumes that come and go over time
14179        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14180        storage.registerListener(mStorageListener);
14181
14182        mInstallerService.systemReady();
14183        mPackageDexOptimizer.systemReady();
14184    }
14185
14186    @Override
14187    public boolean isSafeMode() {
14188        return mSafeMode;
14189    }
14190
14191    @Override
14192    public boolean hasSystemUidErrors() {
14193        return mHasSystemUidErrors;
14194    }
14195
14196    static String arrayToString(int[] array) {
14197        StringBuffer buf = new StringBuffer(128);
14198        buf.append('[');
14199        if (array != null) {
14200            for (int i=0; i<array.length; i++) {
14201                if (i > 0) buf.append(", ");
14202                buf.append(array[i]);
14203            }
14204        }
14205        buf.append(']');
14206        return buf.toString();
14207    }
14208
14209    static class DumpState {
14210        public static final int DUMP_LIBS = 1 << 0;
14211        public static final int DUMP_FEATURES = 1 << 1;
14212        public static final int DUMP_RESOLVERS = 1 << 2;
14213        public static final int DUMP_PERMISSIONS = 1 << 3;
14214        public static final int DUMP_PACKAGES = 1 << 4;
14215        public static final int DUMP_SHARED_USERS = 1 << 5;
14216        public static final int DUMP_MESSAGES = 1 << 6;
14217        public static final int DUMP_PROVIDERS = 1 << 7;
14218        public static final int DUMP_VERIFIERS = 1 << 8;
14219        public static final int DUMP_PREFERRED = 1 << 9;
14220        public static final int DUMP_PREFERRED_XML = 1 << 10;
14221        public static final int DUMP_KEYSETS = 1 << 11;
14222        public static final int DUMP_VERSION = 1 << 12;
14223        public static final int DUMP_INSTALLS = 1 << 13;
14224        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
14225        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
14226
14227        public static final int OPTION_SHOW_FILTERS = 1 << 0;
14228
14229        private int mTypes;
14230
14231        private int mOptions;
14232
14233        private boolean mTitlePrinted;
14234
14235        private SharedUserSetting mSharedUser;
14236
14237        public boolean isDumping(int type) {
14238            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
14239                return true;
14240            }
14241
14242            return (mTypes & type) != 0;
14243        }
14244
14245        public void setDump(int type) {
14246            mTypes |= type;
14247        }
14248
14249        public boolean isOptionEnabled(int option) {
14250            return (mOptions & option) != 0;
14251        }
14252
14253        public void setOptionEnabled(int option) {
14254            mOptions |= option;
14255        }
14256
14257        public boolean onTitlePrinted() {
14258            final boolean printed = mTitlePrinted;
14259            mTitlePrinted = true;
14260            return printed;
14261        }
14262
14263        public boolean getTitlePrinted() {
14264            return mTitlePrinted;
14265        }
14266
14267        public void setTitlePrinted(boolean enabled) {
14268            mTitlePrinted = enabled;
14269        }
14270
14271        public SharedUserSetting getSharedUser() {
14272            return mSharedUser;
14273        }
14274
14275        public void setSharedUser(SharedUserSetting user) {
14276            mSharedUser = user;
14277        }
14278    }
14279
14280    @Override
14281    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
14282        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
14283                != PackageManager.PERMISSION_GRANTED) {
14284            pw.println("Permission Denial: can't dump ActivityManager from from pid="
14285                    + Binder.getCallingPid()
14286                    + ", uid=" + Binder.getCallingUid()
14287                    + " without permission "
14288                    + android.Manifest.permission.DUMP);
14289            return;
14290        }
14291
14292        DumpState dumpState = new DumpState();
14293        boolean fullPreferred = false;
14294        boolean checkin = false;
14295
14296        String packageName = null;
14297        ArraySet<String> permissionNames = null;
14298
14299        int opti = 0;
14300        while (opti < args.length) {
14301            String opt = args[opti];
14302            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
14303                break;
14304            }
14305            opti++;
14306
14307            if ("-a".equals(opt)) {
14308                // Right now we only know how to print all.
14309            } else if ("-h".equals(opt)) {
14310                pw.println("Package manager dump options:");
14311                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
14312                pw.println("    --checkin: dump for a checkin");
14313                pw.println("    -f: print details of intent filters");
14314                pw.println("    -h: print this help");
14315                pw.println("  cmd may be one of:");
14316                pw.println("    l[ibraries]: list known shared libraries");
14317                pw.println("    f[ibraries]: list device features");
14318                pw.println("    k[eysets]: print known keysets");
14319                pw.println("    r[esolvers]: dump intent resolvers");
14320                pw.println("    perm[issions]: dump permissions");
14321                pw.println("    permission [name ...]: dump declaration and use of given permission");
14322                pw.println("    pref[erred]: print preferred package settings");
14323                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
14324                pw.println("    prov[iders]: dump content providers");
14325                pw.println("    p[ackages]: dump installed packages");
14326                pw.println("    s[hared-users]: dump shared user IDs");
14327                pw.println("    m[essages]: print collected runtime messages");
14328                pw.println("    v[erifiers]: print package verifier info");
14329                pw.println("    version: print database version info");
14330                pw.println("    write: write current settings now");
14331                pw.println("    <package.name>: info about given package");
14332                pw.println("    installs: details about install sessions");
14333                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
14334                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
14335                return;
14336            } else if ("--checkin".equals(opt)) {
14337                checkin = true;
14338            } else if ("-f".equals(opt)) {
14339                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14340            } else {
14341                pw.println("Unknown argument: " + opt + "; use -h for help");
14342            }
14343        }
14344
14345        // Is the caller requesting to dump a particular piece of data?
14346        if (opti < args.length) {
14347            String cmd = args[opti];
14348            opti++;
14349            // Is this a package name?
14350            if ("android".equals(cmd) || cmd.contains(".")) {
14351                packageName = cmd;
14352                // When dumping a single package, we always dump all of its
14353                // filter information since the amount of data will be reasonable.
14354                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14355            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
14356                dumpState.setDump(DumpState.DUMP_LIBS);
14357            } else if ("f".equals(cmd) || "features".equals(cmd)) {
14358                dumpState.setDump(DumpState.DUMP_FEATURES);
14359            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
14360                dumpState.setDump(DumpState.DUMP_RESOLVERS);
14361            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
14362                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
14363            } else if ("permission".equals(cmd)) {
14364                if (opti >= args.length) {
14365                    pw.println("Error: permission requires permission name");
14366                    return;
14367                }
14368                permissionNames = new ArraySet<>();
14369                while (opti < args.length) {
14370                    permissionNames.add(args[opti]);
14371                    opti++;
14372                }
14373                dumpState.setDump(DumpState.DUMP_PERMISSIONS
14374                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
14375            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
14376                dumpState.setDump(DumpState.DUMP_PREFERRED);
14377            } else if ("preferred-xml".equals(cmd)) {
14378                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
14379                if (opti < args.length && "--full".equals(args[opti])) {
14380                    fullPreferred = true;
14381                    opti++;
14382                }
14383            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
14384                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
14385            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
14386                dumpState.setDump(DumpState.DUMP_PACKAGES);
14387            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
14388                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
14389            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
14390                dumpState.setDump(DumpState.DUMP_PROVIDERS);
14391            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
14392                dumpState.setDump(DumpState.DUMP_MESSAGES);
14393            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
14394                dumpState.setDump(DumpState.DUMP_VERIFIERS);
14395            } else if ("i".equals(cmd) || "ifv".equals(cmd)
14396                    || "intent-filter-verifiers".equals(cmd)) {
14397                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
14398            } else if ("version".equals(cmd)) {
14399                dumpState.setDump(DumpState.DUMP_VERSION);
14400            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
14401                dumpState.setDump(DumpState.DUMP_KEYSETS);
14402            } else if ("installs".equals(cmd)) {
14403                dumpState.setDump(DumpState.DUMP_INSTALLS);
14404            } else if ("write".equals(cmd)) {
14405                synchronized (mPackages) {
14406                    mSettings.writeLPr();
14407                    pw.println("Settings written.");
14408                    return;
14409                }
14410            }
14411        }
14412
14413        if (checkin) {
14414            pw.println("vers,1");
14415        }
14416
14417        // reader
14418        synchronized (mPackages) {
14419            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
14420                if (!checkin) {
14421                    if (dumpState.onTitlePrinted())
14422                        pw.println();
14423                    pw.println("Database versions:");
14424                    pw.print("  SDK Version:");
14425                    pw.print(" internal=");
14426                    pw.print(mSettings.mInternalSdkPlatform);
14427                    pw.print(" external=");
14428                    pw.println(mSettings.mExternalSdkPlatform);
14429                    pw.print("  DB Version:");
14430                    pw.print(" internal=");
14431                    pw.print(mSettings.mInternalDatabaseVersion);
14432                    pw.print(" external=");
14433                    pw.println(mSettings.mExternalDatabaseVersion);
14434                }
14435            }
14436
14437            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
14438                if (!checkin) {
14439                    if (dumpState.onTitlePrinted())
14440                        pw.println();
14441                    pw.println("Verifiers:");
14442                    pw.print("  Required: ");
14443                    pw.print(mRequiredVerifierPackage);
14444                    pw.print(" (uid=");
14445                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
14446                    pw.println(")");
14447                } else if (mRequiredVerifierPackage != null) {
14448                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
14449                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
14450                }
14451            }
14452
14453            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
14454                    packageName == null) {
14455                if (mIntentFilterVerifierComponent != null) {
14456                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
14457                    if (!checkin) {
14458                        if (dumpState.onTitlePrinted())
14459                            pw.println();
14460                        pw.println("Intent Filter Verifier:");
14461                        pw.print("  Using: ");
14462                        pw.print(verifierPackageName);
14463                        pw.print(" (uid=");
14464                        pw.print(getPackageUid(verifierPackageName, 0));
14465                        pw.println(")");
14466                    } else if (verifierPackageName != null) {
14467                        pw.print("ifv,"); pw.print(verifierPackageName);
14468                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
14469                    }
14470                } else {
14471                    pw.println();
14472                    pw.println("No Intent Filter Verifier available!");
14473                }
14474            }
14475
14476            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
14477                boolean printedHeader = false;
14478                final Iterator<String> it = mSharedLibraries.keySet().iterator();
14479                while (it.hasNext()) {
14480                    String name = it.next();
14481                    SharedLibraryEntry ent = mSharedLibraries.get(name);
14482                    if (!checkin) {
14483                        if (!printedHeader) {
14484                            if (dumpState.onTitlePrinted())
14485                                pw.println();
14486                            pw.println("Libraries:");
14487                            printedHeader = true;
14488                        }
14489                        pw.print("  ");
14490                    } else {
14491                        pw.print("lib,");
14492                    }
14493                    pw.print(name);
14494                    if (!checkin) {
14495                        pw.print(" -> ");
14496                    }
14497                    if (ent.path != null) {
14498                        if (!checkin) {
14499                            pw.print("(jar) ");
14500                            pw.print(ent.path);
14501                        } else {
14502                            pw.print(",jar,");
14503                            pw.print(ent.path);
14504                        }
14505                    } else {
14506                        if (!checkin) {
14507                            pw.print("(apk) ");
14508                            pw.print(ent.apk);
14509                        } else {
14510                            pw.print(",apk,");
14511                            pw.print(ent.apk);
14512                        }
14513                    }
14514                    pw.println();
14515                }
14516            }
14517
14518            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
14519                if (dumpState.onTitlePrinted())
14520                    pw.println();
14521                if (!checkin) {
14522                    pw.println("Features:");
14523                }
14524                Iterator<String> it = mAvailableFeatures.keySet().iterator();
14525                while (it.hasNext()) {
14526                    String name = it.next();
14527                    if (!checkin) {
14528                        pw.print("  ");
14529                    } else {
14530                        pw.print("feat,");
14531                    }
14532                    pw.println(name);
14533                }
14534            }
14535
14536            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
14537                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
14538                        : "Activity Resolver Table:", "  ", packageName,
14539                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14540                    dumpState.setTitlePrinted(true);
14541                }
14542                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
14543                        : "Receiver Resolver Table:", "  ", packageName,
14544                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14545                    dumpState.setTitlePrinted(true);
14546                }
14547                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
14548                        : "Service Resolver Table:", "  ", packageName,
14549                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14550                    dumpState.setTitlePrinted(true);
14551                }
14552                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
14553                        : "Provider Resolver Table:", "  ", packageName,
14554                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14555                    dumpState.setTitlePrinted(true);
14556                }
14557            }
14558
14559            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
14560                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14561                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14562                    int user = mSettings.mPreferredActivities.keyAt(i);
14563                    if (pir.dump(pw,
14564                            dumpState.getTitlePrinted()
14565                                ? "\nPreferred Activities User " + user + ":"
14566                                : "Preferred Activities User " + user + ":", "  ",
14567                            packageName, true, false)) {
14568                        dumpState.setTitlePrinted(true);
14569                    }
14570                }
14571            }
14572
14573            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
14574                pw.flush();
14575                FileOutputStream fout = new FileOutputStream(fd);
14576                BufferedOutputStream str = new BufferedOutputStream(fout);
14577                XmlSerializer serializer = new FastXmlSerializer();
14578                try {
14579                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
14580                    serializer.startDocument(null, true);
14581                    serializer.setFeature(
14582                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
14583                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
14584                    serializer.endDocument();
14585                    serializer.flush();
14586                } catch (IllegalArgumentException e) {
14587                    pw.println("Failed writing: " + e);
14588                } catch (IllegalStateException e) {
14589                    pw.println("Failed writing: " + e);
14590                } catch (IOException e) {
14591                    pw.println("Failed writing: " + e);
14592                }
14593            }
14594
14595            if (!checkin
14596                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
14597                    && packageName == null) {
14598                pw.println();
14599                int count = mSettings.mPackages.size();
14600                if (count == 0) {
14601                    pw.println("No domain preferred apps!");
14602                    pw.println();
14603                } else {
14604                    final String prefix = "  ";
14605                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
14606                    if (allPackageSettings.size() == 0) {
14607                        pw.println("No domain preferred apps!");
14608                        pw.println();
14609                    } else {
14610                        pw.println("Domain preferred apps status:");
14611                        pw.println();
14612                        count = 0;
14613                        for (PackageSetting ps : allPackageSettings) {
14614                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
14615                            if (ivi == null || ivi.getPackageName() == null) continue;
14616                            pw.println(prefix + "Package Name: " + ivi.getPackageName());
14617                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
14618                            pw.println(prefix + "Status: " + ivi.getStatusString());
14619                            pw.println();
14620                            count++;
14621                        }
14622                        if (count == 0) {
14623                            pw.println(prefix + "No domain preferred app status!");
14624                            pw.println();
14625                        }
14626                        for (int userId : sUserManager.getUserIds()) {
14627                            pw.println("Domain preferred apps for User " + userId + ":");
14628                            pw.println();
14629                            count = 0;
14630                            for (PackageSetting ps : allPackageSettings) {
14631                                IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
14632                                if (ivi == null || ivi.getPackageName() == null) {
14633                                    continue;
14634                                }
14635                                final int status = ps.getDomainVerificationStatusForUser(userId);
14636                                if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
14637                                    continue;
14638                                }
14639                                pw.println(prefix + "Package Name: " + ivi.getPackageName());
14640                                pw.println(prefix + "Domains: " + ivi.getDomainsString());
14641                                String statusStr = IntentFilterVerificationInfo.
14642                                        getStatusStringFromValue(status);
14643                                pw.println(prefix + "Status: " + statusStr);
14644                                pw.println();
14645                                count++;
14646                            }
14647                            if (count == 0) {
14648                                pw.println(prefix + "No domain preferred apps!");
14649                                pw.println();
14650                            }
14651                        }
14652                    }
14653                }
14654            }
14655
14656            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
14657                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
14658                if (packageName == null && permissionNames == null) {
14659                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
14660                        if (iperm == 0) {
14661                            if (dumpState.onTitlePrinted())
14662                                pw.println();
14663                            pw.println("AppOp Permissions:");
14664                        }
14665                        pw.print("  AppOp Permission ");
14666                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
14667                        pw.println(":");
14668                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
14669                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
14670                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
14671                        }
14672                    }
14673                }
14674            }
14675
14676            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
14677                boolean printedSomething = false;
14678                for (PackageParser.Provider p : mProviders.mProviders.values()) {
14679                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14680                        continue;
14681                    }
14682                    if (!printedSomething) {
14683                        if (dumpState.onTitlePrinted())
14684                            pw.println();
14685                        pw.println("Registered ContentProviders:");
14686                        printedSomething = true;
14687                    }
14688                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
14689                    pw.print("    "); pw.println(p.toString());
14690                }
14691                printedSomething = false;
14692                for (Map.Entry<String, PackageParser.Provider> entry :
14693                        mProvidersByAuthority.entrySet()) {
14694                    PackageParser.Provider p = entry.getValue();
14695                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14696                        continue;
14697                    }
14698                    if (!printedSomething) {
14699                        if (dumpState.onTitlePrinted())
14700                            pw.println();
14701                        pw.println("ContentProvider Authorities:");
14702                        printedSomething = true;
14703                    }
14704                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
14705                    pw.print("    "); pw.println(p.toString());
14706                    if (p.info != null && p.info.applicationInfo != null) {
14707                        final String appInfo = p.info.applicationInfo.toString();
14708                        pw.print("      applicationInfo="); pw.println(appInfo);
14709                    }
14710                }
14711            }
14712
14713            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
14714                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
14715            }
14716
14717            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
14718                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
14719            }
14720
14721            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
14722                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
14723            }
14724
14725            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
14726                // XXX should handle packageName != null by dumping only install data that
14727                // the given package is involved with.
14728                if (dumpState.onTitlePrinted()) pw.println();
14729                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
14730            }
14731
14732            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
14733                if (dumpState.onTitlePrinted()) pw.println();
14734                mSettings.dumpReadMessagesLPr(pw, dumpState);
14735
14736                pw.println();
14737                pw.println("Package warning messages:");
14738                BufferedReader in = null;
14739                String line = null;
14740                try {
14741                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
14742                    while ((line = in.readLine()) != null) {
14743                        if (line.contains("ignored: updated version")) continue;
14744                        pw.println(line);
14745                    }
14746                } catch (IOException ignored) {
14747                } finally {
14748                    IoUtils.closeQuietly(in);
14749                }
14750            }
14751
14752            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
14753                BufferedReader in = null;
14754                String line = null;
14755                try {
14756                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
14757                    while ((line = in.readLine()) != null) {
14758                        if (line.contains("ignored: updated version")) continue;
14759                        pw.print("msg,");
14760                        pw.println(line);
14761                    }
14762                } catch (IOException ignored) {
14763                } finally {
14764                    IoUtils.closeQuietly(in);
14765                }
14766            }
14767        }
14768    }
14769
14770    // ------- apps on sdcard specific code -------
14771    static final boolean DEBUG_SD_INSTALL = false;
14772
14773    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
14774
14775    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
14776
14777    private boolean mMediaMounted = false;
14778
14779    static String getEncryptKey() {
14780        try {
14781            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
14782                    SD_ENCRYPTION_KEYSTORE_NAME);
14783            if (sdEncKey == null) {
14784                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
14785                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
14786                if (sdEncKey == null) {
14787                    Slog.e(TAG, "Failed to create encryption keys");
14788                    return null;
14789                }
14790            }
14791            return sdEncKey;
14792        } catch (NoSuchAlgorithmException nsae) {
14793            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
14794            return null;
14795        } catch (IOException ioe) {
14796            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
14797            return null;
14798        }
14799    }
14800
14801    /*
14802     * Update media status on PackageManager.
14803     */
14804    @Override
14805    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
14806        int callingUid = Binder.getCallingUid();
14807        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
14808            throw new SecurityException("Media status can only be updated by the system");
14809        }
14810        // reader; this apparently protects mMediaMounted, but should probably
14811        // be a different lock in that case.
14812        synchronized (mPackages) {
14813            Log.i(TAG, "Updating external media status from "
14814                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
14815                    + (mediaStatus ? "mounted" : "unmounted"));
14816            if (DEBUG_SD_INSTALL)
14817                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
14818                        + ", mMediaMounted=" + mMediaMounted);
14819            if (mediaStatus == mMediaMounted) {
14820                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
14821                        : 0, -1);
14822                mHandler.sendMessage(msg);
14823                return;
14824            }
14825            mMediaMounted = mediaStatus;
14826        }
14827        // Queue up an async operation since the package installation may take a
14828        // little while.
14829        mHandler.post(new Runnable() {
14830            public void run() {
14831                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
14832            }
14833        });
14834    }
14835
14836    /**
14837     * Called by MountService when the initial ASECs to scan are available.
14838     * Should block until all the ASEC containers are finished being scanned.
14839     */
14840    public void scanAvailableAsecs() {
14841        updateExternalMediaStatusInner(true, false, false);
14842        if (mShouldRestoreconData) {
14843            SELinuxMMAC.setRestoreconDone();
14844            mShouldRestoreconData = false;
14845        }
14846    }
14847
14848    /*
14849     * Collect information of applications on external media, map them against
14850     * existing containers and update information based on current mount status.
14851     * Please note that we always have to report status if reportStatus has been
14852     * set to true especially when unloading packages.
14853     */
14854    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
14855            boolean externalStorage) {
14856        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
14857        int[] uidArr = EmptyArray.INT;
14858
14859        final String[] list = PackageHelper.getSecureContainerList();
14860        if (ArrayUtils.isEmpty(list)) {
14861            Log.i(TAG, "No secure containers found");
14862        } else {
14863            // Process list of secure containers and categorize them
14864            // as active or stale based on their package internal state.
14865
14866            // reader
14867            synchronized (mPackages) {
14868                for (String cid : list) {
14869                    // Leave stages untouched for now; installer service owns them
14870                    if (PackageInstallerService.isStageName(cid)) continue;
14871
14872                    if (DEBUG_SD_INSTALL)
14873                        Log.i(TAG, "Processing container " + cid);
14874                    String pkgName = getAsecPackageName(cid);
14875                    if (pkgName == null) {
14876                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
14877                        continue;
14878                    }
14879                    if (DEBUG_SD_INSTALL)
14880                        Log.i(TAG, "Looking for pkg : " + pkgName);
14881
14882                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
14883                    if (ps == null) {
14884                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
14885                        continue;
14886                    }
14887
14888                    /*
14889                     * Skip packages that are not external if we're unmounting
14890                     * external storage.
14891                     */
14892                    if (externalStorage && !isMounted && !isExternal(ps)) {
14893                        continue;
14894                    }
14895
14896                    final AsecInstallArgs args = new AsecInstallArgs(cid,
14897                            getAppDexInstructionSets(ps), ps.isForwardLocked());
14898                    // The package status is changed only if the code path
14899                    // matches between settings and the container id.
14900                    if (ps.codePathString != null
14901                            && ps.codePathString.startsWith(args.getCodePath())) {
14902                        if (DEBUG_SD_INSTALL) {
14903                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
14904                                    + " at code path: " + ps.codePathString);
14905                        }
14906
14907                        // We do have a valid package installed on sdcard
14908                        processCids.put(args, ps.codePathString);
14909                        final int uid = ps.appId;
14910                        if (uid != -1) {
14911                            uidArr = ArrayUtils.appendInt(uidArr, uid);
14912                        }
14913                    } else {
14914                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
14915                                + ps.codePathString);
14916                    }
14917                }
14918            }
14919
14920            Arrays.sort(uidArr);
14921        }
14922
14923        // Process packages with valid entries.
14924        if (isMounted) {
14925            if (DEBUG_SD_INSTALL)
14926                Log.i(TAG, "Loading packages");
14927            loadMediaPackages(processCids, uidArr);
14928            startCleaningPackages();
14929            mInstallerService.onSecureContainersAvailable();
14930        } else {
14931            if (DEBUG_SD_INSTALL)
14932                Log.i(TAG, "Unloading packages");
14933            unloadMediaPackages(processCids, uidArr, reportStatus);
14934        }
14935    }
14936
14937    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14938            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
14939        final int size = infos.size();
14940        final String[] packageNames = new String[size];
14941        final int[] packageUids = new int[size];
14942        for (int i = 0; i < size; i++) {
14943            final ApplicationInfo info = infos.get(i);
14944            packageNames[i] = info.packageName;
14945            packageUids[i] = info.uid;
14946        }
14947        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
14948                finishedReceiver);
14949    }
14950
14951    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14952            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
14953        sendResourcesChangedBroadcast(mediaStatus, replacing,
14954                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
14955    }
14956
14957    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14958            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
14959        int size = pkgList.length;
14960        if (size > 0) {
14961            // Send broadcasts here
14962            Bundle extras = new Bundle();
14963            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14964            if (uidArr != null) {
14965                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
14966            }
14967            if (replacing) {
14968                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
14969            }
14970            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
14971                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
14972            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
14973        }
14974    }
14975
14976   /*
14977     * Look at potentially valid container ids from processCids If package
14978     * information doesn't match the one on record or package scanning fails,
14979     * the cid is added to list of removeCids. We currently don't delete stale
14980     * containers.
14981     */
14982    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
14983        ArrayList<String> pkgList = new ArrayList<String>();
14984        Set<AsecInstallArgs> keys = processCids.keySet();
14985
14986        for (AsecInstallArgs args : keys) {
14987            String codePath = processCids.get(args);
14988            if (DEBUG_SD_INSTALL)
14989                Log.i(TAG, "Loading container : " + args.cid);
14990            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14991            try {
14992                // Make sure there are no container errors first.
14993                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
14994                    Slog.e(TAG, "Failed to mount cid : " + args.cid
14995                            + " when installing from sdcard");
14996                    continue;
14997                }
14998                // Check code path here.
14999                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
15000                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
15001                            + " does not match one in settings " + codePath);
15002                    continue;
15003                }
15004                // Parse package
15005                int parseFlags = mDefParseFlags;
15006                if (args.isExternalAsec()) {
15007                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
15008                }
15009                if (args.isFwdLocked()) {
15010                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
15011                }
15012
15013                synchronized (mInstallLock) {
15014                    PackageParser.Package pkg = null;
15015                    try {
15016                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
15017                    } catch (PackageManagerException e) {
15018                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
15019                    }
15020                    // Scan the package
15021                    if (pkg != null) {
15022                        /*
15023                         * TODO why is the lock being held? doPostInstall is
15024                         * called in other places without the lock. This needs
15025                         * to be straightened out.
15026                         */
15027                        // writer
15028                        synchronized (mPackages) {
15029                            retCode = PackageManager.INSTALL_SUCCEEDED;
15030                            pkgList.add(pkg.packageName);
15031                            // Post process args
15032                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
15033                                    pkg.applicationInfo.uid);
15034                        }
15035                    } else {
15036                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
15037                    }
15038                }
15039
15040            } finally {
15041                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
15042                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
15043                }
15044            }
15045        }
15046        // writer
15047        synchronized (mPackages) {
15048            // If the platform SDK has changed since the last time we booted,
15049            // we need to re-grant app permission to catch any new ones that
15050            // appear. This is really a hack, and means that apps can in some
15051            // cases get permissions that the user didn't initially explicitly
15052            // allow... it would be nice to have some better way to handle
15053            // this situation.
15054            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
15055            if (regrantPermissions)
15056                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
15057                        + mSdkVersion + "; regranting permissions for external storage");
15058            mSettings.mExternalSdkPlatform = mSdkVersion;
15059
15060            // Make sure group IDs have been assigned, and any permission
15061            // changes in other apps are accounted for
15062            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
15063                    | (regrantPermissions
15064                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
15065                            : 0));
15066
15067            mSettings.updateExternalDatabaseVersion();
15068
15069            // can downgrade to reader
15070            // Persist settings
15071            mSettings.writeLPr();
15072        }
15073        // Send a broadcast to let everyone know we are done processing
15074        if (pkgList.size() > 0) {
15075            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
15076        }
15077    }
15078
15079   /*
15080     * Utility method to unload a list of specified containers
15081     */
15082    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
15083        // Just unmount all valid containers.
15084        for (AsecInstallArgs arg : cidArgs) {
15085            synchronized (mInstallLock) {
15086                arg.doPostDeleteLI(false);
15087           }
15088       }
15089   }
15090
15091    /*
15092     * Unload packages mounted on external media. This involves deleting package
15093     * data from internal structures, sending broadcasts about diabled packages,
15094     * gc'ing to free up references, unmounting all secure containers
15095     * corresponding to packages on external media, and posting a
15096     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
15097     * that we always have to post this message if status has been requested no
15098     * matter what.
15099     */
15100    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
15101            final boolean reportStatus) {
15102        if (DEBUG_SD_INSTALL)
15103            Log.i(TAG, "unloading media packages");
15104        ArrayList<String> pkgList = new ArrayList<String>();
15105        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
15106        final Set<AsecInstallArgs> keys = processCids.keySet();
15107        for (AsecInstallArgs args : keys) {
15108            String pkgName = args.getPackageName();
15109            if (DEBUG_SD_INSTALL)
15110                Log.i(TAG, "Trying to unload pkg : " + pkgName);
15111            // Delete package internally
15112            PackageRemovedInfo outInfo = new PackageRemovedInfo();
15113            synchronized (mInstallLock) {
15114                boolean res = deletePackageLI(pkgName, null, false, null, null,
15115                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
15116                if (res) {
15117                    pkgList.add(pkgName);
15118                } else {
15119                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
15120                    failedList.add(args);
15121                }
15122            }
15123        }
15124
15125        // reader
15126        synchronized (mPackages) {
15127            // We didn't update the settings after removing each package;
15128            // write them now for all packages.
15129            mSettings.writeLPr();
15130        }
15131
15132        // We have to absolutely send UPDATED_MEDIA_STATUS only
15133        // after confirming that all the receivers processed the ordered
15134        // broadcast when packages get disabled, force a gc to clean things up.
15135        // and unload all the containers.
15136        if (pkgList.size() > 0) {
15137            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
15138                    new IIntentReceiver.Stub() {
15139                public void performReceive(Intent intent, int resultCode, String data,
15140                        Bundle extras, boolean ordered, boolean sticky,
15141                        int sendingUser) throws RemoteException {
15142                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
15143                            reportStatus ? 1 : 0, 1, keys);
15144                    mHandler.sendMessage(msg);
15145                }
15146            });
15147        } else {
15148            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
15149                    keys);
15150            mHandler.sendMessage(msg);
15151        }
15152    }
15153
15154    private void loadPrivatePackages(VolumeInfo vol) {
15155        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
15156        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
15157        synchronized (mInstallLock) {
15158        synchronized (mPackages) {
15159            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15160            for (PackageSetting ps : packages) {
15161                final PackageParser.Package pkg;
15162                try {
15163                    pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null);
15164                    loaded.add(pkg.applicationInfo);
15165                } catch (PackageManagerException e) {
15166                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
15167                }
15168            }
15169
15170            // TODO: regrant any permissions that changed based since original install
15171
15172            mSettings.writeLPr();
15173        }
15174        }
15175
15176        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
15177        sendResourcesChangedBroadcast(true, false, loaded, null);
15178    }
15179
15180    private void unloadPrivatePackages(VolumeInfo vol) {
15181        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
15182        synchronized (mInstallLock) {
15183        synchronized (mPackages) {
15184            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15185            for (PackageSetting ps : packages) {
15186                if (ps.pkg == null) continue;
15187
15188                final ApplicationInfo info = ps.pkg.applicationInfo;
15189                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
15190                if (deletePackageLI(ps.name, null, false, null, null,
15191                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
15192                    unloaded.add(info);
15193                } else {
15194                    Slog.w(TAG, "Failed to unload " + ps.codePath);
15195                }
15196            }
15197
15198            mSettings.writeLPr();
15199        }
15200        }
15201
15202        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
15203        sendResourcesChangedBroadcast(false, false, unloaded, null);
15204    }
15205
15206    private void unfreezePackage(String packageName) {
15207        synchronized (mPackages) {
15208            final PackageSetting ps = mSettings.mPackages.get(packageName);
15209            if (ps != null) {
15210                ps.frozen = false;
15211            }
15212        }
15213    }
15214
15215    @Override
15216    public int movePackage(final String packageName, final String volumeUuid) {
15217        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15218
15219        final int moveId = mNextMoveId.getAndIncrement();
15220        try {
15221            movePackageInternal(packageName, volumeUuid, moveId);
15222        } catch (PackageManagerException e) {
15223            Slog.w(TAG, "Failed to move " + packageName, e);
15224            mMoveCallbacks.notifyStatusChanged(moveId,
15225                    PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15226        }
15227        return moveId;
15228    }
15229
15230    private void movePackageInternal(final String packageName, final String volumeUuid,
15231            final int moveId) throws PackageManagerException {
15232        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
15233        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15234        final PackageManager pm = mContext.getPackageManager();
15235
15236        final boolean currentAsec;
15237        final String currentVolumeUuid;
15238        final File codeFile;
15239        final String installerPackageName;
15240        final String packageAbiOverride;
15241        final int appId;
15242        final String seinfo;
15243        final String label;
15244
15245        // reader
15246        synchronized (mPackages) {
15247            final PackageParser.Package pkg = mPackages.get(packageName);
15248            final PackageSetting ps = mSettings.mPackages.get(packageName);
15249            if (pkg == null || ps == null) {
15250                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
15251            }
15252
15253            if (pkg.applicationInfo.isSystemApp()) {
15254                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
15255                        "Cannot move system application");
15256            }
15257
15258            if (Objects.equals(ps.volumeUuid, volumeUuid)) {
15259                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15260                        "Package already moved to " + volumeUuid);
15261            }
15262
15263            final File probe = new File(pkg.codePath);
15264            final File probeOat = new File(probe, "oat");
15265            if (!probe.isDirectory() || !probeOat.isDirectory()) {
15266                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15267                        "Move only supported for modern cluster style installs");
15268            }
15269
15270            if (ps.frozen) {
15271                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
15272                        "Failed to move already frozen package");
15273            }
15274            ps.frozen = true;
15275
15276            currentAsec = pkg.applicationInfo.isForwardLocked()
15277                    || pkg.applicationInfo.isExternalAsec();
15278            currentVolumeUuid = ps.volumeUuid;
15279            codeFile = new File(pkg.codePath);
15280            installerPackageName = ps.installerPackageName;
15281            packageAbiOverride = ps.cpuAbiOverrideString;
15282            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
15283            seinfo = pkg.applicationInfo.seinfo;
15284            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
15285        }
15286
15287        // Now that we're guarded by frozen state, kill app during move
15288        killApplication(packageName, appId, "move pkg");
15289
15290        final Bundle extras = new Bundle();
15291        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
15292        extras.putString(Intent.EXTRA_TITLE, label);
15293        mMoveCallbacks.notifyCreated(moveId, extras);
15294
15295        int installFlags;
15296        final boolean moveCompleteApp;
15297        final File measurePath;
15298
15299        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
15300            installFlags = INSTALL_INTERNAL;
15301            moveCompleteApp = !currentAsec;
15302            measurePath = Environment.getDataAppDirectory(volumeUuid);
15303        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
15304            installFlags = INSTALL_EXTERNAL;
15305            moveCompleteApp = false;
15306            measurePath = storage.getPrimaryPhysicalVolume().getPath();
15307        } else {
15308            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
15309            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
15310                    || !volume.isMountedWritable()) {
15311                unfreezePackage(packageName);
15312                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15313                        "Move location not mounted private volume");
15314            }
15315
15316            Preconditions.checkState(!currentAsec);
15317
15318            installFlags = INSTALL_INTERNAL;
15319            moveCompleteApp = true;
15320            measurePath = Environment.getDataAppDirectory(volumeUuid);
15321        }
15322
15323        final PackageStats stats = new PackageStats(null, -1);
15324        synchronized (mInstaller) {
15325            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
15326                unfreezePackage(packageName);
15327                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15328                        "Failed to measure package size");
15329            }
15330        }
15331
15332        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
15333                + stats.dataSize);
15334
15335        final long startFreeBytes = measurePath.getFreeSpace();
15336        final long sizeBytes;
15337        if (moveCompleteApp) {
15338            sizeBytes = stats.codeSize + stats.dataSize;
15339        } else {
15340            sizeBytes = stats.codeSize;
15341        }
15342
15343        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
15344            unfreezePackage(packageName);
15345            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15346                    "Not enough free space to move");
15347        }
15348
15349        mMoveCallbacks.notifyStatusChanged(moveId, 10);
15350
15351        final CountDownLatch installedLatch = new CountDownLatch(1);
15352        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
15353            @Override
15354            public void onUserActionRequired(Intent intent) throws RemoteException {
15355                throw new IllegalStateException();
15356            }
15357
15358            @Override
15359            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
15360                    Bundle extras) throws RemoteException {
15361                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
15362                        + PackageManager.installStatusToString(returnCode, msg));
15363
15364                installedLatch.countDown();
15365
15366                // Regardless of success or failure of the move operation,
15367                // always unfreeze the package
15368                unfreezePackage(packageName);
15369
15370                final int status = PackageManager.installStatusToPublicStatus(returnCode);
15371                switch (status) {
15372                    case PackageInstaller.STATUS_SUCCESS:
15373                        mMoveCallbacks.notifyStatusChanged(moveId,
15374                                PackageManager.MOVE_SUCCEEDED);
15375                        break;
15376                    case PackageInstaller.STATUS_FAILURE_STORAGE:
15377                        mMoveCallbacks.notifyStatusChanged(moveId,
15378                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
15379                        break;
15380                    default:
15381                        mMoveCallbacks.notifyStatusChanged(moveId,
15382                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15383                        break;
15384                }
15385            }
15386        };
15387
15388        final MoveInfo move;
15389        if (moveCompleteApp) {
15390            // Kick off a thread to report progress estimates
15391            new Thread() {
15392                @Override
15393                public void run() {
15394                    while (true) {
15395                        try {
15396                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
15397                                break;
15398                            }
15399                        } catch (InterruptedException ignored) {
15400                        }
15401
15402                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
15403                        final int progress = 10 + (int) MathUtils.constrain(
15404                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
15405                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
15406                    }
15407                }
15408            }.start();
15409
15410            final String dataAppName = codeFile.getName();
15411            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
15412                    dataAppName, appId, seinfo);
15413        } else {
15414            move = null;
15415        }
15416
15417        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
15418
15419        final Message msg = mHandler.obtainMessage(INIT_COPY);
15420        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
15421        msg.obj = new InstallParams(origin, move, installObserver, installFlags,
15422                installerPackageName, volumeUuid, null, user, packageAbiOverride);
15423        mHandler.sendMessage(msg);
15424    }
15425
15426    @Override
15427    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
15428        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15429
15430        final int realMoveId = mNextMoveId.getAndIncrement();
15431        final Bundle extras = new Bundle();
15432        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
15433        mMoveCallbacks.notifyCreated(realMoveId, extras);
15434
15435        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
15436            @Override
15437            public void onCreated(int moveId, Bundle extras) {
15438                // Ignored
15439            }
15440
15441            @Override
15442            public void onStatusChanged(int moveId, int status, long estMillis) {
15443                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
15444            }
15445        };
15446
15447        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15448        storage.setPrimaryStorageUuid(volumeUuid, callback);
15449        return realMoveId;
15450    }
15451
15452    @Override
15453    public int getMoveStatus(int moveId) {
15454        mContext.enforceCallingOrSelfPermission(
15455                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15456        return mMoveCallbacks.mLastStatus.get(moveId);
15457    }
15458
15459    @Override
15460    public void registerMoveCallback(IPackageMoveObserver callback) {
15461        mContext.enforceCallingOrSelfPermission(
15462                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15463        mMoveCallbacks.register(callback);
15464    }
15465
15466    @Override
15467    public void unregisterMoveCallback(IPackageMoveObserver callback) {
15468        mContext.enforceCallingOrSelfPermission(
15469                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15470        mMoveCallbacks.unregister(callback);
15471    }
15472
15473    @Override
15474    public boolean setInstallLocation(int loc) {
15475        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
15476                null);
15477        if (getInstallLocation() == loc) {
15478            return true;
15479        }
15480        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
15481                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
15482            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
15483                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
15484            return true;
15485        }
15486        return false;
15487   }
15488
15489    @Override
15490    public int getInstallLocation() {
15491        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15492                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
15493                PackageHelper.APP_INSTALL_AUTO);
15494    }
15495
15496    /** Called by UserManagerService */
15497    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
15498        mDirtyUsers.remove(userHandle);
15499        mSettings.removeUserLPw(userHandle);
15500        mPendingBroadcasts.remove(userHandle);
15501        if (mInstaller != null) {
15502            // Technically, we shouldn't be doing this with the package lock
15503            // held.  However, this is very rare, and there is already so much
15504            // other disk I/O going on, that we'll let it slide for now.
15505            final StorageManager storage = StorageManager.from(mContext);
15506            final List<VolumeInfo> vols = storage.getVolumes();
15507            for (VolumeInfo vol : vols) {
15508                if (vol.getType() == VolumeInfo.TYPE_PRIVATE && vol.isMountedWritable()) {
15509                    final String volumeUuid = vol.getFsUuid();
15510                    if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
15511                    mInstaller.removeUserDataDirs(volumeUuid, userHandle);
15512                }
15513            }
15514        }
15515        mUserNeedsBadging.delete(userHandle);
15516        removeUnusedPackagesLILPw(userManager, userHandle);
15517    }
15518
15519    /**
15520     * We're removing userHandle and would like to remove any downloaded packages
15521     * that are no longer in use by any other user.
15522     * @param userHandle the user being removed
15523     */
15524    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
15525        final boolean DEBUG_CLEAN_APKS = false;
15526        int [] users = userManager.getUserIdsLPr();
15527        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
15528        while (psit.hasNext()) {
15529            PackageSetting ps = psit.next();
15530            if (ps.pkg == null) {
15531                continue;
15532            }
15533            final String packageName = ps.pkg.packageName;
15534            // Skip over if system app
15535            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15536                continue;
15537            }
15538            if (DEBUG_CLEAN_APKS) {
15539                Slog.i(TAG, "Checking package " + packageName);
15540            }
15541            boolean keep = false;
15542            for (int i = 0; i < users.length; i++) {
15543                if (users[i] != userHandle && ps.getInstalled(users[i])) {
15544                    keep = true;
15545                    if (DEBUG_CLEAN_APKS) {
15546                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
15547                                + users[i]);
15548                    }
15549                    break;
15550                }
15551            }
15552            if (!keep) {
15553                if (DEBUG_CLEAN_APKS) {
15554                    Slog.i(TAG, "  Removing package " + packageName);
15555                }
15556                mHandler.post(new Runnable() {
15557                    public void run() {
15558                        deletePackageX(packageName, userHandle, 0);
15559                    } //end run
15560                });
15561            }
15562        }
15563    }
15564
15565    /** Called by UserManagerService */
15566    void createNewUserLILPw(int userHandle, File path) {
15567        if (mInstaller != null) {
15568            mInstaller.createUserConfig(userHandle);
15569            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
15570            applyFactoryDefaultBrowserLPw(userHandle);
15571        }
15572    }
15573
15574    void newUserCreatedLILPw(final int userHandle) {
15575        // We cannot grant the default permissions with a lock held as
15576        // we query providers from other components for default handlers
15577        // such as enabled IMEs, etc.
15578        mHandler.post(new Runnable() {
15579            @Override
15580            public void run() {
15581                mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
15582            }
15583        });
15584    }
15585
15586    @Override
15587    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
15588        mContext.enforceCallingOrSelfPermission(
15589                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15590                "Only package verification agents can read the verifier device identity");
15591
15592        synchronized (mPackages) {
15593            return mSettings.getVerifierDeviceIdentityLPw();
15594        }
15595    }
15596
15597    @Override
15598    public void setPermissionEnforced(String permission, boolean enforced) {
15599        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
15600        if (READ_EXTERNAL_STORAGE.equals(permission)) {
15601            synchronized (mPackages) {
15602                if (mSettings.mReadExternalStorageEnforced == null
15603                        || mSettings.mReadExternalStorageEnforced != enforced) {
15604                    mSettings.mReadExternalStorageEnforced = enforced;
15605                    mSettings.writeLPr();
15606                }
15607            }
15608            // kill any non-foreground processes so we restart them and
15609            // grant/revoke the GID.
15610            final IActivityManager am = ActivityManagerNative.getDefault();
15611            if (am != null) {
15612                final long token = Binder.clearCallingIdentity();
15613                try {
15614                    am.killProcessesBelowForeground("setPermissionEnforcement");
15615                } catch (RemoteException e) {
15616                } finally {
15617                    Binder.restoreCallingIdentity(token);
15618                }
15619            }
15620        } else {
15621            throw new IllegalArgumentException("No selective enforcement for " + permission);
15622        }
15623    }
15624
15625    @Override
15626    @Deprecated
15627    public boolean isPermissionEnforced(String permission) {
15628        return true;
15629    }
15630
15631    @Override
15632    public boolean isStorageLow() {
15633        final long token = Binder.clearCallingIdentity();
15634        try {
15635            final DeviceStorageMonitorInternal
15636                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
15637            if (dsm != null) {
15638                return dsm.isMemoryLow();
15639            } else {
15640                return false;
15641            }
15642        } finally {
15643            Binder.restoreCallingIdentity(token);
15644        }
15645    }
15646
15647    @Override
15648    public IPackageInstaller getPackageInstaller() {
15649        return mInstallerService;
15650    }
15651
15652    private boolean userNeedsBadging(int userId) {
15653        int index = mUserNeedsBadging.indexOfKey(userId);
15654        if (index < 0) {
15655            final UserInfo userInfo;
15656            final long token = Binder.clearCallingIdentity();
15657            try {
15658                userInfo = sUserManager.getUserInfo(userId);
15659            } finally {
15660                Binder.restoreCallingIdentity(token);
15661            }
15662            final boolean b;
15663            if (userInfo != null && userInfo.isManagedProfile()) {
15664                b = true;
15665            } else {
15666                b = false;
15667            }
15668            mUserNeedsBadging.put(userId, b);
15669            return b;
15670        }
15671        return mUserNeedsBadging.valueAt(index);
15672    }
15673
15674    @Override
15675    public KeySet getKeySetByAlias(String packageName, String alias) {
15676        if (packageName == null || alias == null) {
15677            return null;
15678        }
15679        synchronized(mPackages) {
15680            final PackageParser.Package pkg = mPackages.get(packageName);
15681            if (pkg == null) {
15682                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15683                throw new IllegalArgumentException("Unknown package: " + packageName);
15684            }
15685            KeySetManagerService ksms = mSettings.mKeySetManagerService;
15686            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
15687        }
15688    }
15689
15690    @Override
15691    public KeySet getSigningKeySet(String packageName) {
15692        if (packageName == null) {
15693            return null;
15694        }
15695        synchronized(mPackages) {
15696            final PackageParser.Package pkg = mPackages.get(packageName);
15697            if (pkg == null) {
15698                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15699                throw new IllegalArgumentException("Unknown package: " + packageName);
15700            }
15701            if (pkg.applicationInfo.uid != Binder.getCallingUid()
15702                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
15703                throw new SecurityException("May not access signing KeySet of other apps.");
15704            }
15705            KeySetManagerService ksms = mSettings.mKeySetManagerService;
15706            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
15707        }
15708    }
15709
15710    @Override
15711    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
15712        if (packageName == null || ks == null) {
15713            return false;
15714        }
15715        synchronized(mPackages) {
15716            final PackageParser.Package pkg = mPackages.get(packageName);
15717            if (pkg == null) {
15718                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15719                throw new IllegalArgumentException("Unknown package: " + packageName);
15720            }
15721            IBinder ksh = ks.getToken();
15722            if (ksh instanceof KeySetHandle) {
15723                KeySetManagerService ksms = mSettings.mKeySetManagerService;
15724                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
15725            }
15726            return false;
15727        }
15728    }
15729
15730    @Override
15731    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
15732        if (packageName == null || ks == null) {
15733            return false;
15734        }
15735        synchronized(mPackages) {
15736            final PackageParser.Package pkg = mPackages.get(packageName);
15737            if (pkg == null) {
15738                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15739                throw new IllegalArgumentException("Unknown package: " + packageName);
15740            }
15741            IBinder ksh = ks.getToken();
15742            if (ksh instanceof KeySetHandle) {
15743                KeySetManagerService ksms = mSettings.mKeySetManagerService;
15744                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
15745            }
15746            return false;
15747        }
15748    }
15749
15750    public void getUsageStatsIfNoPackageUsageInfo() {
15751        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
15752            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
15753            if (usm == null) {
15754                throw new IllegalStateException("UsageStatsManager must be initialized");
15755            }
15756            long now = System.currentTimeMillis();
15757            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
15758            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
15759                String packageName = entry.getKey();
15760                PackageParser.Package pkg = mPackages.get(packageName);
15761                if (pkg == null) {
15762                    continue;
15763                }
15764                UsageStats usage = entry.getValue();
15765                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
15766                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
15767            }
15768        }
15769    }
15770
15771    /**
15772     * Check and throw if the given before/after packages would be considered a
15773     * downgrade.
15774     */
15775    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
15776            throws PackageManagerException {
15777        if (after.versionCode < before.mVersionCode) {
15778            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15779                    "Update version code " + after.versionCode + " is older than current "
15780                    + before.mVersionCode);
15781        } else if (after.versionCode == before.mVersionCode) {
15782            if (after.baseRevisionCode < before.baseRevisionCode) {
15783                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15784                        "Update base revision code " + after.baseRevisionCode
15785                        + " is older than current " + before.baseRevisionCode);
15786            }
15787
15788            if (!ArrayUtils.isEmpty(after.splitNames)) {
15789                for (int i = 0; i < after.splitNames.length; i++) {
15790                    final String splitName = after.splitNames[i];
15791                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
15792                    if (j != -1) {
15793                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
15794                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15795                                    "Update split " + splitName + " revision code "
15796                                    + after.splitRevisionCodes[i] + " is older than current "
15797                                    + before.splitRevisionCodes[j]);
15798                        }
15799                    }
15800                }
15801            }
15802        }
15803    }
15804
15805    private static class MoveCallbacks extends Handler {
15806        private static final int MSG_CREATED = 1;
15807        private static final int MSG_STATUS_CHANGED = 2;
15808
15809        private final RemoteCallbackList<IPackageMoveObserver>
15810                mCallbacks = new RemoteCallbackList<>();
15811
15812        private final SparseIntArray mLastStatus = new SparseIntArray();
15813
15814        public MoveCallbacks(Looper looper) {
15815            super(looper);
15816        }
15817
15818        public void register(IPackageMoveObserver callback) {
15819            mCallbacks.register(callback);
15820        }
15821
15822        public void unregister(IPackageMoveObserver callback) {
15823            mCallbacks.unregister(callback);
15824        }
15825
15826        @Override
15827        public void handleMessage(Message msg) {
15828            final SomeArgs args = (SomeArgs) msg.obj;
15829            final int n = mCallbacks.beginBroadcast();
15830            for (int i = 0; i < n; i++) {
15831                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
15832                try {
15833                    invokeCallback(callback, msg.what, args);
15834                } catch (RemoteException ignored) {
15835                }
15836            }
15837            mCallbacks.finishBroadcast();
15838            args.recycle();
15839        }
15840
15841        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
15842                throws RemoteException {
15843            switch (what) {
15844                case MSG_CREATED: {
15845                    callback.onCreated(args.argi1, (Bundle) args.arg2);
15846                    break;
15847                }
15848                case MSG_STATUS_CHANGED: {
15849                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
15850                    break;
15851                }
15852            }
15853        }
15854
15855        private void notifyCreated(int moveId, Bundle extras) {
15856            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
15857
15858            final SomeArgs args = SomeArgs.obtain();
15859            args.argi1 = moveId;
15860            args.arg2 = extras;
15861            obtainMessage(MSG_CREATED, args).sendToTarget();
15862        }
15863
15864        private void notifyStatusChanged(int moveId, int status) {
15865            notifyStatusChanged(moveId, status, -1);
15866        }
15867
15868        private void notifyStatusChanged(int moveId, int status, long estMillis) {
15869            Slog.v(TAG, "Move " + moveId + " status " + status);
15870
15871            final SomeArgs args = SomeArgs.obtain();
15872            args.argi1 = moveId;
15873            args.argi2 = status;
15874            args.arg3 = estMillis;
15875            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
15876
15877            synchronized (mLastStatus) {
15878                mLastStatus.put(moveId, status);
15879            }
15880        }
15881    }
15882
15883    private final class OnPermissionChangeListeners extends Handler {
15884        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
15885
15886        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
15887                new RemoteCallbackList<>();
15888
15889        public OnPermissionChangeListeners(Looper looper) {
15890            super(looper);
15891        }
15892
15893        @Override
15894        public void handleMessage(Message msg) {
15895            switch (msg.what) {
15896                case MSG_ON_PERMISSIONS_CHANGED: {
15897                    final int uid = msg.arg1;
15898                    handleOnPermissionsChanged(uid);
15899                } break;
15900            }
15901        }
15902
15903        public void addListenerLocked(IOnPermissionsChangeListener listener) {
15904            mPermissionListeners.register(listener);
15905
15906        }
15907
15908        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
15909            mPermissionListeners.unregister(listener);
15910        }
15911
15912        public void onPermissionsChanged(int uid) {
15913            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
15914                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
15915            }
15916        }
15917
15918        private void handleOnPermissionsChanged(int uid) {
15919            final int count = mPermissionListeners.beginBroadcast();
15920            try {
15921                for (int i = 0; i < count; i++) {
15922                    IOnPermissionsChangeListener callback = mPermissionListeners
15923                            .getBroadcastItem(i);
15924                    try {
15925                        callback.onPermissionsChanged(uid);
15926                    } catch (RemoteException e) {
15927                        Log.e(TAG, "Permission listener is dead", e);
15928                    }
15929                }
15930            } finally {
15931                mPermissionListeners.finishBroadcast();
15932            }
15933        }
15934    }
15935
15936    private class PackageManagerInternalImpl extends PackageManagerInternal {
15937        @Override
15938        public void setLocationPackagesProvider(PackagesProvider provider) {
15939            synchronized (mPackages) {
15940                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
15941            }
15942        }
15943
15944        @Override
15945        public void setImePackagesProvider(PackagesProvider provider) {
15946            synchronized (mPackages) {
15947                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
15948            }
15949        }
15950
15951        @Override
15952        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
15953            synchronized (mPackages) {
15954                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
15955            }
15956        }
15957
15958        @Override
15959        public void setSmsAppPackagesProvider(PackagesProvider provider) {
15960            synchronized (mPackages) {
15961                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
15962            }
15963        }
15964
15965        @Override
15966        public void setDialerAppPackagesProvider(PackagesProvider provider) {
15967            synchronized (mPackages) {
15968                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
15969            }
15970        }
15971
15972        @Override
15973        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
15974            synchronized (mPackages) {
15975                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderrLPw(provider);
15976            }
15977        }
15978
15979        @Override
15980        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
15981            synchronized (mPackages) {
15982                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
15983                        packageName, userId);
15984            }
15985        }
15986
15987        @Override
15988        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
15989            synchronized (mPackages) {
15990                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
15991                        packageName, userId);
15992            }
15993        }
15994    }
15995
15996    @Override
15997    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
15998        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
15999        synchronized (mPackages) {
16000            final long identity = Binder.clearCallingIdentity();
16001            try {
16002                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
16003                        packageNames, userId);
16004            } finally {
16005                Binder.restoreCallingIdentity(identity);
16006            }
16007        }
16008    }
16009
16010    private static void enforceSystemOrPhoneCaller(String tag) {
16011        int callingUid = Binder.getCallingUid();
16012        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
16013            throw new SecurityException(
16014                    "Cannot call " + tag + " from UID " + callingUid);
16015        }
16016    }
16017}
16018