PackageManagerService.java revision 54b6b3c82bfae75b5562b4ed86441392e3265aaa
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.GRANT_REVOKE_PERMISSIONS;
20import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
21import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
26import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
27import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
28import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
29import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT;
30import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
31import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
32import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
33import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
34import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
35import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
36import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
37import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
38import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
39import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
40import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
41import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED;
42import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
44import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
45import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
46import static android.content.pm.PackageManager.INSTALL_INTERNAL;
47import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
48import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
49import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
50import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
51import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
52import static android.content.pm.PackageManager.MATCH_ALL;
53import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
54import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
55import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
56import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
57import static android.content.pm.PackageParser.isApkFile;
58import static android.os.Process.PACKAGE_INFO_GID;
59import static android.os.Process.SYSTEM_UID;
60import static android.system.OsConstants.O_CREAT;
61import static android.system.OsConstants.O_RDWR;
62import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
63import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER;
64import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
65import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
66import static com.android.internal.util.ArrayUtils.appendInt;
67import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
68import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
69import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
70import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
71import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
72
73import android.Manifest;
74import android.app.ActivityManager;
75import android.app.ActivityManagerNative;
76import android.app.AppGlobals;
77import android.app.IActivityManager;
78import android.app.admin.IDevicePolicyManager;
79import android.app.backup.IBackupManager;
80import android.app.usage.UsageStats;
81import android.app.usage.UsageStatsManager;
82import android.content.BroadcastReceiver;
83import android.content.ComponentName;
84import android.content.Context;
85import android.content.IIntentReceiver;
86import android.content.Intent;
87import android.content.IntentFilter;
88import android.content.IntentSender;
89import android.content.IntentSender.SendIntentException;
90import android.content.ServiceConnection;
91import android.content.pm.ActivityInfo;
92import android.content.pm.ApplicationInfo;
93import android.content.pm.FeatureInfo;
94import android.content.pm.IOnPermissionsChangeListener;
95import android.content.pm.IPackageDataObserver;
96import android.content.pm.IPackageDeleteObserver;
97import android.content.pm.IPackageDeleteObserver2;
98import android.content.pm.IPackageInstallObserver2;
99import android.content.pm.IPackageInstaller;
100import android.content.pm.IPackageManager;
101import android.content.pm.IPackageMoveObserver;
102import android.content.pm.IPackageStatsObserver;
103import android.content.pm.IPackagesProvider;
104import android.content.pm.InstrumentationInfo;
105import android.content.pm.IntentFilterVerificationInfo;
106import android.content.pm.KeySet;
107import android.content.pm.ManifestDigest;
108import android.content.pm.PackageCleanItem;
109import android.content.pm.PackageInfo;
110import android.content.pm.PackageInfoLite;
111import android.content.pm.PackageInstaller;
112import android.content.pm.PackageManager;
113import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
114import android.content.pm.PackageManagerInternal;
115import android.content.pm.PackageParser;
116import android.content.pm.PackageParser.ActivityIntentInfo;
117import android.content.pm.PackageParser.PackageLite;
118import android.content.pm.PackageParser.PackageParserException;
119import android.content.pm.PackageStats;
120import android.content.pm.PackageUserState;
121import android.content.pm.ParceledListSlice;
122import android.content.pm.PermissionGroupInfo;
123import android.content.pm.PermissionInfo;
124import android.content.pm.ProviderInfo;
125import android.content.pm.ResolveInfo;
126import android.content.pm.ServiceInfo;
127import android.content.pm.Signature;
128import android.content.pm.UserInfo;
129import android.content.pm.VerificationParams;
130import android.content.pm.VerifierDeviceIdentity;
131import android.content.pm.VerifierInfo;
132import android.content.res.Resources;
133import android.hardware.display.DisplayManager;
134import android.net.Uri;
135import android.os.Binder;
136import android.os.Build;
137import android.os.Bundle;
138import android.os.Debug;
139import android.os.Environment;
140import android.os.Environment.UserEnvironment;
141import android.os.FileUtils;
142import android.os.Handler;
143import android.os.IBinder;
144import android.os.Looper;
145import android.os.Message;
146import android.os.Parcel;
147import android.os.ParcelFileDescriptor;
148import android.os.Process;
149import android.os.RemoteCallbackList;
150import android.os.RemoteException;
151import android.os.SELinux;
152import android.os.ServiceManager;
153import android.os.SystemClock;
154import android.os.SystemProperties;
155import android.os.UserHandle;
156import android.os.UserManager;
157import android.os.storage.IMountService;
158import android.os.storage.StorageEventListener;
159import android.os.storage.StorageManager;
160import android.os.storage.VolumeInfo;
161import android.os.storage.VolumeRecord;
162import android.security.KeyStore;
163import android.security.SystemKeyStore;
164import android.system.ErrnoException;
165import android.system.Os;
166import android.system.StructStat;
167import android.text.TextUtils;
168import android.text.format.DateUtils;
169import android.util.ArrayMap;
170import android.util.ArraySet;
171import android.util.AtomicFile;
172import android.util.DisplayMetrics;
173import android.util.EventLog;
174import android.util.ExceptionUtils;
175import android.util.Log;
176import android.util.LogPrinter;
177import android.util.MathUtils;
178import android.util.PrintStreamPrinter;
179import android.util.Slog;
180import android.util.SparseArray;
181import android.util.SparseBooleanArray;
182import android.util.SparseIntArray;
183import android.util.Xml;
184import android.view.Display;
185
186import dalvik.system.DexFile;
187import dalvik.system.VMRuntime;
188
189import libcore.io.IoUtils;
190import libcore.util.EmptyArray;
191
192import com.android.internal.R;
193import com.android.internal.app.IMediaContainerService;
194import com.android.internal.app.ResolverActivity;
195import com.android.internal.content.NativeLibraryHelper;
196import com.android.internal.content.PackageHelper;
197import com.android.internal.os.IParcelFileDescriptorFactory;
198import com.android.internal.os.SomeArgs;
199import com.android.internal.util.ArrayUtils;
200import com.android.internal.util.FastPrintWriter;
201import com.android.internal.util.FastXmlSerializer;
202import com.android.internal.util.IndentingPrintWriter;
203import com.android.internal.util.Preconditions;
204import com.android.server.EventLogTags;
205import com.android.server.FgThread;
206import com.android.server.IntentResolver;
207import com.android.server.LocalServices;
208import com.android.server.ServiceThread;
209import com.android.server.SystemConfig;
210import com.android.server.Watchdog;
211import com.android.server.pm.Settings.DatabaseVersion;
212import com.android.server.pm.PermissionsState.PermissionState;
213import com.android.server.storage.DeviceStorageMonitorInternal;
214
215import org.xmlpull.v1.XmlPullParser;
216import org.xmlpull.v1.XmlPullParserException;
217import org.xmlpull.v1.XmlSerializer;
218
219import java.io.BufferedInputStream;
220import java.io.BufferedOutputStream;
221import java.io.BufferedReader;
222import java.io.ByteArrayInputStream;
223import java.io.ByteArrayOutputStream;
224import java.io.File;
225import java.io.FileDescriptor;
226import java.io.FileNotFoundException;
227import java.io.FileOutputStream;
228import java.io.FileReader;
229import java.io.FilenameFilter;
230import java.io.IOException;
231import java.io.InputStream;
232import java.io.PrintWriter;
233import java.nio.charset.StandardCharsets;
234import java.security.NoSuchAlgorithmException;
235import java.security.PublicKey;
236import java.security.cert.CertificateEncodingException;
237import java.security.cert.CertificateException;
238import java.text.SimpleDateFormat;
239import java.util.ArrayList;
240import java.util.Arrays;
241import java.util.Collection;
242import java.util.Collections;
243import java.util.Comparator;
244import java.util.Date;
245import java.util.Iterator;
246import java.util.List;
247import java.util.Map;
248import java.util.Objects;
249import java.util.Set;
250import java.util.concurrent.CountDownLatch;
251import java.util.concurrent.TimeUnit;
252import java.util.concurrent.atomic.AtomicBoolean;
253import java.util.concurrent.atomic.AtomicInteger;
254import java.util.concurrent.atomic.AtomicLong;
255
256/**
257 * Keep track of all those .apks everywhere.
258 *
259 * This is very central to the platform's security; please run the unit
260 * tests whenever making modifications here:
261 *
262runtest -c android.content.pm.PackageManagerTests frameworks-core
263 *
264 * {@hide}
265 */
266public class PackageManagerService extends IPackageManager.Stub {
267    static final String TAG = "PackageManager";
268    static final boolean DEBUG_SETTINGS = false;
269    static final boolean DEBUG_PREFERRED = false;
270    static final boolean DEBUG_UPGRADE = false;
271    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
272    private static final boolean DEBUG_BACKUP = true;
273    private static final boolean DEBUG_INSTALL = false;
274    private static final boolean DEBUG_REMOVE = false;
275    private static final boolean DEBUG_BROADCASTS = false;
276    private static final boolean DEBUG_SHOW_INFO = false;
277    private static final boolean DEBUG_PACKAGE_INFO = false;
278    private static final boolean DEBUG_INTENT_MATCHING = false;
279    private static final boolean DEBUG_PACKAGE_SCANNING = false;
280    private static final boolean DEBUG_VERIFY = false;
281    private static final boolean DEBUG_DEXOPT = false;
282    private static final boolean DEBUG_ABI_SELECTION = false;
283
284    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = Build.IS_DEBUGGABLE;
285
286    private static final int RADIO_UID = Process.PHONE_UID;
287    private static final int LOG_UID = Process.LOG_UID;
288    private static final int NFC_UID = Process.NFC_UID;
289    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
290    private static final int SHELL_UID = Process.SHELL_UID;
291
292    // Cap the size of permission trees that 3rd party apps can define
293    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
294
295    // Suffix used during package installation when copying/moving
296    // package apks to install directory.
297    private static final String INSTALL_PACKAGE_SUFFIX = "-";
298
299    static final int SCAN_NO_DEX = 1<<1;
300    static final int SCAN_FORCE_DEX = 1<<2;
301    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
302    static final int SCAN_NEW_INSTALL = 1<<4;
303    static final int SCAN_NO_PATHS = 1<<5;
304    static final int SCAN_UPDATE_TIME = 1<<6;
305    static final int SCAN_DEFER_DEX = 1<<7;
306    static final int SCAN_BOOTING = 1<<8;
307    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
308    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
309    static final int SCAN_REQUIRE_KNOWN = 1<<12;
310    static final int SCAN_MOVE = 1<<13;
311    static final int SCAN_INITIAL = 1<<14;
312
313    static final int REMOVE_CHATTY = 1<<16;
314
315    private static final int[] EMPTY_INT_ARRAY = new int[0];
316
317    /**
318     * Timeout (in milliseconds) after which the watchdog should declare that
319     * our handler thread is wedged.  The usual default for such things is one
320     * minute but we sometimes do very lengthy I/O operations on this thread,
321     * such as installing multi-gigabyte applications, so ours needs to be longer.
322     */
323    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
324
325    /**
326     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
327     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
328     * settings entry if available, otherwise we use the hardcoded default.  If it's been
329     * more than this long since the last fstrim, we force one during the boot sequence.
330     *
331     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
332     * one gets run at the next available charging+idle time.  This final mandatory
333     * no-fstrim check kicks in only of the other scheduling criteria is never met.
334     */
335    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
336
337    /**
338     * Whether verification is enabled by default.
339     */
340    private static final boolean DEFAULT_VERIFY_ENABLE = true;
341
342    /**
343     * The default maximum time to wait for the verification agent to return in
344     * milliseconds.
345     */
346    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
347
348    /**
349     * The default response for package verification timeout.
350     *
351     * This can be either PackageManager.VERIFICATION_ALLOW or
352     * PackageManager.VERIFICATION_REJECT.
353     */
354    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
355
356    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
357
358    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
359            DEFAULT_CONTAINER_PACKAGE,
360            "com.android.defcontainer.DefaultContainerService");
361
362    private static final String KILL_APP_REASON_GIDS_CHANGED =
363            "permission grant or revoke changed gids";
364
365    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
366            "permissions revoked";
367
368    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
369
370    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
371
372    /** Permission grant: not grant the permission. */
373    private static final int GRANT_DENIED = 1;
374
375    /** Permission grant: grant the permission as an install permission. */
376    private static final int GRANT_INSTALL = 2;
377
378    /** Permission grant: grant the permission as an install permission for a legacy app. */
379    private static final int GRANT_INSTALL_LEGACY = 3;
380
381    /** Permission grant: grant the permission as a runtime one. */
382    private static final int GRANT_RUNTIME = 4;
383
384    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
385    private static final int GRANT_UPGRADE = 5;
386
387    final ServiceThread mHandlerThread;
388
389    final PackageHandler mHandler;
390
391    /**
392     * Messages for {@link #mHandler} that need to wait for system ready before
393     * being dispatched.
394     */
395    private ArrayList<Message> mPostSystemReadyMessages;
396
397    final int mSdkVersion = Build.VERSION.SDK_INT;
398
399    final Context mContext;
400    final boolean mFactoryTest;
401    final boolean mOnlyCore;
402    final boolean mLazyDexOpt;
403    final long mDexOptLRUThresholdInMills;
404    final DisplayMetrics mMetrics;
405    final int mDefParseFlags;
406    final String[] mSeparateProcesses;
407    final boolean mIsUpgrade;
408
409    // This is where all application persistent data goes.
410    final File mAppDataDir;
411
412    // This is where all application persistent data goes for secondary users.
413    final File mUserAppDataDir;
414
415    /** The location for ASEC container files on internal storage. */
416    final String mAsecInternalPath;
417
418    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
419    // LOCK HELD.  Can be called with mInstallLock held.
420    final Installer mInstaller;
421
422    /** Directory where installed third-party apps stored */
423    final File mAppInstallDir;
424
425    /**
426     * Directory to which applications installed internally have their
427     * 32 bit native libraries copied.
428     */
429    private File mAppLib32InstallDir;
430
431    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
432    // apps.
433    final File mDrmAppPrivateInstallDir;
434
435    // ----------------------------------------------------------------
436
437    // Lock for state used when installing and doing other long running
438    // operations.  Methods that must be called with this lock held have
439    // the suffix "LI".
440    final Object mInstallLock = new Object();
441
442    // ----------------------------------------------------------------
443
444    // Keys are String (package name), values are Package.  This also serves
445    // as the lock for the global state.  Methods that must be called with
446    // this lock held have the prefix "LP".
447    final ArrayMap<String, PackageParser.Package> mPackages =
448            new ArrayMap<String, PackageParser.Package>();
449
450    // Tracks available target package names -> overlay package paths.
451    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
452        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
453
454    final Settings mSettings;
455    boolean mRestoredSettings;
456
457    // System configuration read by SystemConfig.
458    final int[] mGlobalGids;
459    final SparseArray<ArraySet<String>> mSystemPermissions;
460    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
461
462    // If mac_permissions.xml was found for seinfo labeling.
463    boolean mFoundPolicyFile;
464
465    // If a recursive restorecon of /data/data/<pkg> is needed.
466    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
467
468    public static final class SharedLibraryEntry {
469        public final String path;
470        public final String apk;
471
472        SharedLibraryEntry(String _path, String _apk) {
473            path = _path;
474            apk = _apk;
475        }
476    }
477
478    // Currently known shared libraries.
479    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
480            new ArrayMap<String, SharedLibraryEntry>();
481
482    // All available activities, for your resolving pleasure.
483    final ActivityIntentResolver mActivities =
484            new ActivityIntentResolver();
485
486    // All available receivers, for your resolving pleasure.
487    final ActivityIntentResolver mReceivers =
488            new ActivityIntentResolver();
489
490    // All available services, for your resolving pleasure.
491    final ServiceIntentResolver mServices = new ServiceIntentResolver();
492
493    // All available providers, for your resolving pleasure.
494    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
495
496    // Mapping from provider base names (first directory in content URI codePath)
497    // to the provider information.
498    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
499            new ArrayMap<String, PackageParser.Provider>();
500
501    // Mapping from instrumentation class names to info about them.
502    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
503            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
504
505    // Mapping from permission names to info about them.
506    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
507            new ArrayMap<String, PackageParser.PermissionGroup>();
508
509    // Packages whose data we have transfered into another package, thus
510    // should no longer exist.
511    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
512
513    // Broadcast actions that are only available to the system.
514    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
515
516    /** List of packages waiting for verification. */
517    final SparseArray<PackageVerificationState> mPendingVerification
518            = new SparseArray<PackageVerificationState>();
519
520    /** Set of packages associated with each app op permission. */
521    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
522
523    final PackageInstallerService mInstallerService;
524
525    private final PackageDexOptimizer mPackageDexOptimizer;
526
527    private AtomicInteger mNextMoveId = new AtomicInteger();
528    private final MoveCallbacks mMoveCallbacks;
529
530    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
531
532    // Cache of users who need badging.
533    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
534
535    /** Token for keys in mPendingVerification. */
536    private int mPendingVerificationToken = 0;
537
538    volatile boolean mSystemReady;
539    volatile boolean mSafeMode;
540    volatile boolean mHasSystemUidErrors;
541
542    ApplicationInfo mAndroidApplication;
543    final ActivityInfo mResolveActivity = new ActivityInfo();
544    final ResolveInfo mResolveInfo = new ResolveInfo();
545    ComponentName mResolveComponentName;
546    PackageParser.Package mPlatformPackage;
547    ComponentName mCustomResolverComponentName;
548
549    boolean mResolverReplaced = false;
550
551    private final ComponentName mIntentFilterVerifierComponent;
552    private int mIntentFilterVerificationToken = 0;
553
554    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
555            = new SparseArray<IntentFilterVerificationState>();
556
557    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
558            new DefaultPermissionGrantPolicy(this);
559
560    private static class IFVerificationParams {
561        PackageParser.Package pkg;
562        boolean replacing;
563        int userId;
564        int verifierUid;
565
566        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
567                int _userId, int _verifierUid) {
568            pkg = _pkg;
569            replacing = _replacing;
570            userId = _userId;
571            replacing = _replacing;
572            verifierUid = _verifierUid;
573        }
574    }
575
576    private interface IntentFilterVerifier<T extends IntentFilter> {
577        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
578                                               T filter, String packageName);
579        void startVerifications(int userId);
580        void receiveVerificationResponse(int verificationId);
581    }
582
583    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
584        private Context mContext;
585        private ComponentName mIntentFilterVerifierComponent;
586        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
587
588        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
589            mContext = context;
590            mIntentFilterVerifierComponent = verifierComponent;
591        }
592
593        private String getDefaultScheme() {
594            return IntentFilter.SCHEME_HTTPS;
595        }
596
597        @Override
598        public void startVerifications(int userId) {
599            // Launch verifications requests
600            int count = mCurrentIntentFilterVerifications.size();
601            for (int n=0; n<count; n++) {
602                int verificationId = mCurrentIntentFilterVerifications.get(n);
603                final IntentFilterVerificationState ivs =
604                        mIntentFilterVerificationStates.get(verificationId);
605
606                String packageName = ivs.getPackageName();
607
608                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
609                final int filterCount = filters.size();
610                ArraySet<String> domainsSet = new ArraySet<>();
611                for (int m=0; m<filterCount; m++) {
612                    PackageParser.ActivityIntentInfo filter = filters.get(m);
613                    domainsSet.addAll(filter.getHostsList());
614                }
615                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
616                synchronized (mPackages) {
617                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
618                            packageName, domainsList) != null) {
619                        scheduleWriteSettingsLocked();
620                    }
621                }
622                sendVerificationRequest(userId, verificationId, ivs);
623            }
624            mCurrentIntentFilterVerifications.clear();
625        }
626
627        private void sendVerificationRequest(int userId, int verificationId,
628                IntentFilterVerificationState ivs) {
629
630            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
631            verificationIntent.putExtra(
632                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
633                    verificationId);
634            verificationIntent.putExtra(
635                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
636                    getDefaultScheme());
637            verificationIntent.putExtra(
638                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
639                    ivs.getHostsString());
640            verificationIntent.putExtra(
641                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
642                    ivs.getPackageName());
643            verificationIntent.setComponent(mIntentFilterVerifierComponent);
644            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
645
646            UserHandle user = new UserHandle(userId);
647            mContext.sendBroadcastAsUser(verificationIntent, user);
648            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
649                    "Sending IntentFilter verification broadcast");
650        }
651
652        public void receiveVerificationResponse(int verificationId) {
653            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
654
655            final boolean verified = ivs.isVerified();
656
657            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
658            final int count = filters.size();
659            if (DEBUG_DOMAIN_VERIFICATION) {
660                Slog.i(TAG, "Received verification response " + verificationId
661                        + " for " + count + " filters, verified=" + verified);
662            }
663            for (int n=0; n<count; n++) {
664                PackageParser.ActivityIntentInfo filter = filters.get(n);
665                filter.setVerified(verified);
666
667                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
668                        + " verified with result:" + verified + " and hosts:"
669                        + ivs.getHostsString());
670            }
671
672            mIntentFilterVerificationStates.remove(verificationId);
673
674            final String packageName = ivs.getPackageName();
675            IntentFilterVerificationInfo ivi = null;
676
677            synchronized (mPackages) {
678                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
679            }
680            if (ivi == null) {
681                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
682                        + verificationId + " packageName:" + packageName);
683                return;
684            }
685            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
686                    "Updating IntentFilterVerificationInfo for verificationId:" + verificationId);
687
688            synchronized (mPackages) {
689                if (verified) {
690                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
691                } else {
692                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
693                }
694                scheduleWriteSettingsLocked();
695
696                final int userId = ivs.getUserId();
697                if (userId != UserHandle.USER_ALL) {
698                    final int userStatus =
699                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
700
701                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
702                    boolean needUpdate = false;
703
704                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
705                    // already been set by the User thru the Disambiguation dialog
706                    switch (userStatus) {
707                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
708                            if (verified) {
709                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
710                            } else {
711                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
712                            }
713                            needUpdate = true;
714                            break;
715
716                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
717                            if (verified) {
718                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
719                                needUpdate = true;
720                            }
721                            break;
722
723                        default:
724                            // Nothing to do
725                    }
726
727                    if (needUpdate) {
728                        mSettings.updateIntentFilterVerificationStatusLPw(
729                                packageName, updatedStatus, userId);
730                        scheduleWritePackageRestrictionsLocked(userId);
731                    }
732                }
733            }
734        }
735
736        @Override
737        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
738                    ActivityIntentInfo filter, String packageName) {
739            if (!hasValidDomains(filter)) {
740                return false;
741            }
742            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
743            if (ivs == null) {
744                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
745                        packageName);
746            }
747            if (DEBUG_DOMAIN_VERIFICATION) {
748                Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter);
749            }
750            ivs.addFilter(filter);
751            return true;
752        }
753
754        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
755                int userId, int verificationId, String packageName) {
756            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
757                    verifierUid, userId, packageName);
758            ivs.setPendingState();
759            synchronized (mPackages) {
760                mIntentFilterVerificationStates.append(verificationId, ivs);
761                mCurrentIntentFilterVerifications.add(verificationId);
762            }
763            return ivs;
764        }
765    }
766
767    private static boolean hasValidDomains(ActivityIntentInfo filter) {
768        boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
769                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS);
770        if (!hasHTTPorHTTPS) {
771            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
772                    "IntentFilter does not contain any HTTP or HTTPS data scheme");
773            return false;
774        }
775        return true;
776    }
777
778    private IntentFilterVerifier mIntentFilterVerifier;
779
780    // Set of pending broadcasts for aggregating enable/disable of components.
781    static class PendingPackageBroadcasts {
782        // for each user id, a map of <package name -> components within that package>
783        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
784
785        public PendingPackageBroadcasts() {
786            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
787        }
788
789        public ArrayList<String> get(int userId, String packageName) {
790            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
791            return packages.get(packageName);
792        }
793
794        public void put(int userId, String packageName, ArrayList<String> components) {
795            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
796            packages.put(packageName, components);
797        }
798
799        public void remove(int userId, String packageName) {
800            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
801            if (packages != null) {
802                packages.remove(packageName);
803            }
804        }
805
806        public void remove(int userId) {
807            mUidMap.remove(userId);
808        }
809
810        public int userIdCount() {
811            return mUidMap.size();
812        }
813
814        public int userIdAt(int n) {
815            return mUidMap.keyAt(n);
816        }
817
818        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
819            return mUidMap.get(userId);
820        }
821
822        public int size() {
823            // total number of pending broadcast entries across all userIds
824            int num = 0;
825            for (int i = 0; i< mUidMap.size(); i++) {
826                num += mUidMap.valueAt(i).size();
827            }
828            return num;
829        }
830
831        public void clear() {
832            mUidMap.clear();
833        }
834
835        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
836            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
837            if (map == null) {
838                map = new ArrayMap<String, ArrayList<String>>();
839                mUidMap.put(userId, map);
840            }
841            return map;
842        }
843    }
844    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
845
846    // Service Connection to remote media container service to copy
847    // package uri's from external media onto secure containers
848    // or internal storage.
849    private IMediaContainerService mContainerService = null;
850
851    static final int SEND_PENDING_BROADCAST = 1;
852    static final int MCS_BOUND = 3;
853    static final int END_COPY = 4;
854    static final int INIT_COPY = 5;
855    static final int MCS_UNBIND = 6;
856    static final int START_CLEANING_PACKAGE = 7;
857    static final int FIND_INSTALL_LOC = 8;
858    static final int POST_INSTALL = 9;
859    static final int MCS_RECONNECT = 10;
860    static final int MCS_GIVE_UP = 11;
861    static final int UPDATED_MEDIA_STATUS = 12;
862    static final int WRITE_SETTINGS = 13;
863    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
864    static final int PACKAGE_VERIFIED = 15;
865    static final int CHECK_PENDING_VERIFICATION = 16;
866    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
867    static final int INTENT_FILTER_VERIFIED = 18;
868
869    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
870
871    // Delay time in millisecs
872    static final int BROADCAST_DELAY = 10 * 1000;
873
874    static UserManagerService sUserManager;
875
876    // Stores a list of users whose package restrictions file needs to be updated
877    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
878
879    final private DefaultContainerConnection mDefContainerConn =
880            new DefaultContainerConnection();
881    class DefaultContainerConnection implements ServiceConnection {
882        public void onServiceConnected(ComponentName name, IBinder service) {
883            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
884            IMediaContainerService imcs =
885                IMediaContainerService.Stub.asInterface(service);
886            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
887        }
888
889        public void onServiceDisconnected(ComponentName name) {
890            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
891        }
892    }
893
894    // Recordkeeping of restore-after-install operations that are currently in flight
895    // between the Package Manager and the Backup Manager
896    class PostInstallData {
897        public InstallArgs args;
898        public PackageInstalledInfo res;
899
900        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
901            args = _a;
902            res = _r;
903        }
904    }
905
906    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
907    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
908
909    // XML tags for backup/restore of various bits of state
910    private static final String TAG_PREFERRED_BACKUP = "pa";
911    private static final String TAG_DEFAULT_APPS = "da";
912    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
913
914    private final String mRequiredVerifierPackage;
915
916    private final PackageUsage mPackageUsage = new PackageUsage();
917
918    private class PackageUsage {
919        private static final int WRITE_INTERVAL
920            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
921
922        private final Object mFileLock = new Object();
923        private final AtomicLong mLastWritten = new AtomicLong(0);
924        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
925
926        private boolean mIsHistoricalPackageUsageAvailable = true;
927
928        boolean isHistoricalPackageUsageAvailable() {
929            return mIsHistoricalPackageUsageAvailable;
930        }
931
932        void write(boolean force) {
933            if (force) {
934                writeInternal();
935                return;
936            }
937            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
938                && !DEBUG_DEXOPT) {
939                return;
940            }
941            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
942                new Thread("PackageUsage_DiskWriter") {
943                    @Override
944                    public void run() {
945                        try {
946                            writeInternal();
947                        } finally {
948                            mBackgroundWriteRunning.set(false);
949                        }
950                    }
951                }.start();
952            }
953        }
954
955        private void writeInternal() {
956            synchronized (mPackages) {
957                synchronized (mFileLock) {
958                    AtomicFile file = getFile();
959                    FileOutputStream f = null;
960                    try {
961                        f = file.startWrite();
962                        BufferedOutputStream out = new BufferedOutputStream(f);
963                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
964                        StringBuilder sb = new StringBuilder();
965                        for (PackageParser.Package pkg : mPackages.values()) {
966                            if (pkg.mLastPackageUsageTimeInMills == 0) {
967                                continue;
968                            }
969                            sb.setLength(0);
970                            sb.append(pkg.packageName);
971                            sb.append(' ');
972                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
973                            sb.append('\n');
974                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
975                        }
976                        out.flush();
977                        file.finishWrite(f);
978                    } catch (IOException e) {
979                        if (f != null) {
980                            file.failWrite(f);
981                        }
982                        Log.e(TAG, "Failed to write package usage times", e);
983                    }
984                }
985            }
986            mLastWritten.set(SystemClock.elapsedRealtime());
987        }
988
989        void readLP() {
990            synchronized (mFileLock) {
991                AtomicFile file = getFile();
992                BufferedInputStream in = null;
993                try {
994                    in = new BufferedInputStream(file.openRead());
995                    StringBuffer sb = new StringBuffer();
996                    while (true) {
997                        String packageName = readToken(in, sb, ' ');
998                        if (packageName == null) {
999                            break;
1000                        }
1001                        String timeInMillisString = readToken(in, sb, '\n');
1002                        if (timeInMillisString == null) {
1003                            throw new IOException("Failed to find last usage time for package "
1004                                                  + packageName);
1005                        }
1006                        PackageParser.Package pkg = mPackages.get(packageName);
1007                        if (pkg == null) {
1008                            continue;
1009                        }
1010                        long timeInMillis;
1011                        try {
1012                            timeInMillis = Long.parseLong(timeInMillisString.toString());
1013                        } catch (NumberFormatException e) {
1014                            throw new IOException("Failed to parse " + timeInMillisString
1015                                                  + " as a long.", e);
1016                        }
1017                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1018                    }
1019                } catch (FileNotFoundException expected) {
1020                    mIsHistoricalPackageUsageAvailable = false;
1021                } catch (IOException e) {
1022                    Log.w(TAG, "Failed to read package usage times", e);
1023                } finally {
1024                    IoUtils.closeQuietly(in);
1025                }
1026            }
1027            mLastWritten.set(SystemClock.elapsedRealtime());
1028        }
1029
1030        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1031                throws IOException {
1032            sb.setLength(0);
1033            while (true) {
1034                int ch = in.read();
1035                if (ch == -1) {
1036                    if (sb.length() == 0) {
1037                        return null;
1038                    }
1039                    throw new IOException("Unexpected EOF");
1040                }
1041                if (ch == endOfToken) {
1042                    return sb.toString();
1043                }
1044                sb.append((char)ch);
1045            }
1046        }
1047
1048        private AtomicFile getFile() {
1049            File dataDir = Environment.getDataDirectory();
1050            File systemDir = new File(dataDir, "system");
1051            File fname = new File(systemDir, "package-usage.list");
1052            return new AtomicFile(fname);
1053        }
1054    }
1055
1056    class PackageHandler extends Handler {
1057        private boolean mBound = false;
1058        final ArrayList<HandlerParams> mPendingInstalls =
1059            new ArrayList<HandlerParams>();
1060
1061        private boolean connectToService() {
1062            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1063                    " DefaultContainerService");
1064            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1065            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1066            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1067                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
1068                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1069                mBound = true;
1070                return true;
1071            }
1072            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1073            return false;
1074        }
1075
1076        private void disconnectService() {
1077            mContainerService = null;
1078            mBound = false;
1079            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1080            mContext.unbindService(mDefContainerConn);
1081            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1082        }
1083
1084        PackageHandler(Looper looper) {
1085            super(looper);
1086        }
1087
1088        public void handleMessage(Message msg) {
1089            try {
1090                doHandleMessage(msg);
1091            } finally {
1092                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1093            }
1094        }
1095
1096        void doHandleMessage(Message msg) {
1097            switch (msg.what) {
1098                case INIT_COPY: {
1099                    HandlerParams params = (HandlerParams) msg.obj;
1100                    int idx = mPendingInstalls.size();
1101                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1102                    // If a bind was already initiated we dont really
1103                    // need to do anything. The pending install
1104                    // will be processed later on.
1105                    if (!mBound) {
1106                        // If this is the only one pending we might
1107                        // have to bind to the service again.
1108                        if (!connectToService()) {
1109                            Slog.e(TAG, "Failed to bind to media container service");
1110                            params.serviceError();
1111                            return;
1112                        } else {
1113                            // Once we bind to the service, the first
1114                            // pending request will be processed.
1115                            mPendingInstalls.add(idx, params);
1116                        }
1117                    } else {
1118                        mPendingInstalls.add(idx, params);
1119                        // Already bound to the service. Just make
1120                        // sure we trigger off processing the first request.
1121                        if (idx == 0) {
1122                            mHandler.sendEmptyMessage(MCS_BOUND);
1123                        }
1124                    }
1125                    break;
1126                }
1127                case MCS_BOUND: {
1128                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1129                    if (msg.obj != null) {
1130                        mContainerService = (IMediaContainerService) msg.obj;
1131                    }
1132                    if (mContainerService == null) {
1133                        if (!mBound) {
1134                            // Something seriously wrong since we are not bound and we are not
1135                            // waiting for connection. Bail out.
1136                            Slog.e(TAG, "Cannot bind to media container service");
1137                            for (HandlerParams params : mPendingInstalls) {
1138                                // Indicate service bind error
1139                                params.serviceError();
1140                            }
1141                            mPendingInstalls.clear();
1142                        } else {
1143                            Slog.w(TAG, "Waiting to connect to media container service");
1144                        }
1145                    } else if (mPendingInstalls.size() > 0) {
1146                        HandlerParams params = mPendingInstalls.get(0);
1147                        if (params != null) {
1148                            if (params.startCopy()) {
1149                                // We are done...  look for more work or to
1150                                // go idle.
1151                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1152                                        "Checking for more work or unbind...");
1153                                // Delete pending install
1154                                if (mPendingInstalls.size() > 0) {
1155                                    mPendingInstalls.remove(0);
1156                                }
1157                                if (mPendingInstalls.size() == 0) {
1158                                    if (mBound) {
1159                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1160                                                "Posting delayed MCS_UNBIND");
1161                                        removeMessages(MCS_UNBIND);
1162                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1163                                        // Unbind after a little delay, to avoid
1164                                        // continual thrashing.
1165                                        sendMessageDelayed(ubmsg, 10000);
1166                                    }
1167                                } else {
1168                                    // There are more pending requests in queue.
1169                                    // Just post MCS_BOUND message to trigger processing
1170                                    // of next pending install.
1171                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1172                                            "Posting MCS_BOUND for next work");
1173                                    mHandler.sendEmptyMessage(MCS_BOUND);
1174                                }
1175                            }
1176                        }
1177                    } else {
1178                        // Should never happen ideally.
1179                        Slog.w(TAG, "Empty queue");
1180                    }
1181                    break;
1182                }
1183                case MCS_RECONNECT: {
1184                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1185                    if (mPendingInstalls.size() > 0) {
1186                        if (mBound) {
1187                            disconnectService();
1188                        }
1189                        if (!connectToService()) {
1190                            Slog.e(TAG, "Failed to bind to media container service");
1191                            for (HandlerParams params : mPendingInstalls) {
1192                                // Indicate service bind error
1193                                params.serviceError();
1194                            }
1195                            mPendingInstalls.clear();
1196                        }
1197                    }
1198                    break;
1199                }
1200                case MCS_UNBIND: {
1201                    // If there is no actual work left, then time to unbind.
1202                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1203
1204                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1205                        if (mBound) {
1206                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1207
1208                            disconnectService();
1209                        }
1210                    } else if (mPendingInstalls.size() > 0) {
1211                        // There are more pending requests in queue.
1212                        // Just post MCS_BOUND message to trigger processing
1213                        // of next pending install.
1214                        mHandler.sendEmptyMessage(MCS_BOUND);
1215                    }
1216
1217                    break;
1218                }
1219                case MCS_GIVE_UP: {
1220                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1221                    mPendingInstalls.remove(0);
1222                    break;
1223                }
1224                case SEND_PENDING_BROADCAST: {
1225                    String packages[];
1226                    ArrayList<String> components[];
1227                    int size = 0;
1228                    int uids[];
1229                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1230                    synchronized (mPackages) {
1231                        if (mPendingBroadcasts == null) {
1232                            return;
1233                        }
1234                        size = mPendingBroadcasts.size();
1235                        if (size <= 0) {
1236                            // Nothing to be done. Just return
1237                            return;
1238                        }
1239                        packages = new String[size];
1240                        components = new ArrayList[size];
1241                        uids = new int[size];
1242                        int i = 0;  // filling out the above arrays
1243
1244                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1245                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1246                            Iterator<Map.Entry<String, ArrayList<String>>> it
1247                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1248                                            .entrySet().iterator();
1249                            while (it.hasNext() && i < size) {
1250                                Map.Entry<String, ArrayList<String>> ent = it.next();
1251                                packages[i] = ent.getKey();
1252                                components[i] = ent.getValue();
1253                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1254                                uids[i] = (ps != null)
1255                                        ? UserHandle.getUid(packageUserId, ps.appId)
1256                                        : -1;
1257                                i++;
1258                            }
1259                        }
1260                        size = i;
1261                        mPendingBroadcasts.clear();
1262                    }
1263                    // Send broadcasts
1264                    for (int i = 0; i < size; i++) {
1265                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1266                    }
1267                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1268                    break;
1269                }
1270                case START_CLEANING_PACKAGE: {
1271                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1272                    final String packageName = (String)msg.obj;
1273                    final int userId = msg.arg1;
1274                    final boolean andCode = msg.arg2 != 0;
1275                    synchronized (mPackages) {
1276                        if (userId == UserHandle.USER_ALL) {
1277                            int[] users = sUserManager.getUserIds();
1278                            for (int user : users) {
1279                                mSettings.addPackageToCleanLPw(
1280                                        new PackageCleanItem(user, packageName, andCode));
1281                            }
1282                        } else {
1283                            mSettings.addPackageToCleanLPw(
1284                                    new PackageCleanItem(userId, packageName, andCode));
1285                        }
1286                    }
1287                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1288                    startCleaningPackages();
1289                } break;
1290                case POST_INSTALL: {
1291                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1292                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1293                    mRunningInstalls.delete(msg.arg1);
1294                    boolean deleteOld = false;
1295
1296                    if (data != null) {
1297                        InstallArgs args = data.args;
1298                        PackageInstalledInfo res = data.res;
1299
1300                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1301                            res.removedInfo.sendBroadcast(false, true, false);
1302                            Bundle extras = new Bundle(1);
1303                            extras.putInt(Intent.EXTRA_UID, res.uid);
1304
1305                            // Now that we successfully installed the package, grant runtime
1306                            // permissions if requested before broadcasting the install.
1307                            if ((args.installFlags
1308                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) {
1309                                grantRequestedRuntimePermissions(res.pkg,
1310                                        args.user.getIdentifier());
1311                            }
1312
1313                            // Determine the set of users who are adding this
1314                            // package for the first time vs. those who are seeing
1315                            // an update.
1316                            int[] firstUsers;
1317                            int[] updateUsers = new int[0];
1318                            if (res.origUsers == null || res.origUsers.length == 0) {
1319                                firstUsers = res.newUsers;
1320                            } else {
1321                                firstUsers = new int[0];
1322                                for (int i=0; i<res.newUsers.length; i++) {
1323                                    int user = res.newUsers[i];
1324                                    boolean isNew = true;
1325                                    for (int j=0; j<res.origUsers.length; j++) {
1326                                        if (res.origUsers[j] == user) {
1327                                            isNew = false;
1328                                            break;
1329                                        }
1330                                    }
1331                                    if (isNew) {
1332                                        int[] newFirst = new int[firstUsers.length+1];
1333                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1334                                                firstUsers.length);
1335                                        newFirst[firstUsers.length] = user;
1336                                        firstUsers = newFirst;
1337                                    } else {
1338                                        int[] newUpdate = new int[updateUsers.length+1];
1339                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1340                                                updateUsers.length);
1341                                        newUpdate[updateUsers.length] = user;
1342                                        updateUsers = newUpdate;
1343                                    }
1344                                }
1345                            }
1346                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1347                                    res.pkg.applicationInfo.packageName,
1348                                    extras, null, null, firstUsers);
1349                            final boolean update = res.removedInfo.removedPackage != null;
1350                            if (update) {
1351                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1352                            }
1353                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1354                                    res.pkg.applicationInfo.packageName,
1355                                    extras, null, null, updateUsers);
1356                            if (update) {
1357                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1358                                        res.pkg.applicationInfo.packageName,
1359                                        extras, null, null, updateUsers);
1360                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1361                                        null, null,
1362                                        res.pkg.applicationInfo.packageName, null, updateUsers);
1363
1364                                // treat asec-hosted packages like removable media on upgrade
1365                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1366                                    if (DEBUG_INSTALL) {
1367                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1368                                                + " is ASEC-hosted -> AVAILABLE");
1369                                    }
1370                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1371                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1372                                    pkgList.add(res.pkg.applicationInfo.packageName);
1373                                    sendResourcesChangedBroadcast(true, true,
1374                                            pkgList,uidArray, null);
1375                                }
1376                            }
1377                            if (res.removedInfo.args != null) {
1378                                // Remove the replaced package's older resources safely now
1379                                deleteOld = true;
1380                            }
1381
1382                            // Log current value of "unknown sources" setting
1383                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1384                                getUnknownSourcesSettings());
1385                        }
1386                        // Force a gc to clear up things
1387                        Runtime.getRuntime().gc();
1388                        // We delete after a gc for applications  on sdcard.
1389                        if (deleteOld) {
1390                            synchronized (mInstallLock) {
1391                                res.removedInfo.args.doPostDeleteLI(true);
1392                            }
1393                        }
1394                        if (args.observer != null) {
1395                            try {
1396                                Bundle extras = extrasForInstallResult(res);
1397                                args.observer.onPackageInstalled(res.name, res.returnCode,
1398                                        res.returnMsg, extras);
1399                            } catch (RemoteException e) {
1400                                Slog.i(TAG, "Observer no longer exists.");
1401                            }
1402                        }
1403                    } else {
1404                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1405                    }
1406                } break;
1407                case UPDATED_MEDIA_STATUS: {
1408                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1409                    boolean reportStatus = msg.arg1 == 1;
1410                    boolean doGc = msg.arg2 == 1;
1411                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1412                    if (doGc) {
1413                        // Force a gc to clear up stale containers.
1414                        Runtime.getRuntime().gc();
1415                    }
1416                    if (msg.obj != null) {
1417                        @SuppressWarnings("unchecked")
1418                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1419                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1420                        // Unload containers
1421                        unloadAllContainers(args);
1422                    }
1423                    if (reportStatus) {
1424                        try {
1425                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1426                            PackageHelper.getMountService().finishMediaUpdate();
1427                        } catch (RemoteException e) {
1428                            Log.e(TAG, "MountService not running?");
1429                        }
1430                    }
1431                } break;
1432                case WRITE_SETTINGS: {
1433                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1434                    synchronized (mPackages) {
1435                        removeMessages(WRITE_SETTINGS);
1436                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1437                        mSettings.writeLPr();
1438                        mDirtyUsers.clear();
1439                    }
1440                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1441                } break;
1442                case WRITE_PACKAGE_RESTRICTIONS: {
1443                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1444                    synchronized (mPackages) {
1445                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1446                        for (int userId : mDirtyUsers) {
1447                            mSettings.writePackageRestrictionsLPr(userId);
1448                        }
1449                        mDirtyUsers.clear();
1450                    }
1451                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1452                } break;
1453                case CHECK_PENDING_VERIFICATION: {
1454                    final int verificationId = msg.arg1;
1455                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1456
1457                    if ((state != null) && !state.timeoutExtended()) {
1458                        final InstallArgs args = state.getInstallArgs();
1459                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1460
1461                        Slog.i(TAG, "Verification timed out for " + originUri);
1462                        mPendingVerification.remove(verificationId);
1463
1464                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1465
1466                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1467                            Slog.i(TAG, "Continuing with installation of " + originUri);
1468                            state.setVerifierResponse(Binder.getCallingUid(),
1469                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1470                            broadcastPackageVerified(verificationId, originUri,
1471                                    PackageManager.VERIFICATION_ALLOW,
1472                                    state.getInstallArgs().getUser());
1473                            try {
1474                                ret = args.copyApk(mContainerService, true);
1475                            } catch (RemoteException e) {
1476                                Slog.e(TAG, "Could not contact the ContainerService");
1477                            }
1478                        } else {
1479                            broadcastPackageVerified(verificationId, originUri,
1480                                    PackageManager.VERIFICATION_REJECT,
1481                                    state.getInstallArgs().getUser());
1482                        }
1483
1484                        processPendingInstall(args, ret);
1485                        mHandler.sendEmptyMessage(MCS_UNBIND);
1486                    }
1487                    break;
1488                }
1489                case PACKAGE_VERIFIED: {
1490                    final int verificationId = msg.arg1;
1491
1492                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1493                    if (state == null) {
1494                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1495                        break;
1496                    }
1497
1498                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1499
1500                    state.setVerifierResponse(response.callerUid, response.code);
1501
1502                    if (state.isVerificationComplete()) {
1503                        mPendingVerification.remove(verificationId);
1504
1505                        final InstallArgs args = state.getInstallArgs();
1506                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1507
1508                        int ret;
1509                        if (state.isInstallAllowed()) {
1510                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1511                            broadcastPackageVerified(verificationId, originUri,
1512                                    response.code, state.getInstallArgs().getUser());
1513                            try {
1514                                ret = args.copyApk(mContainerService, true);
1515                            } catch (RemoteException e) {
1516                                Slog.e(TAG, "Could not contact the ContainerService");
1517                            }
1518                        } else {
1519                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1520                        }
1521
1522                        processPendingInstall(args, ret);
1523
1524                        mHandler.sendEmptyMessage(MCS_UNBIND);
1525                    }
1526
1527                    break;
1528                }
1529                case START_INTENT_FILTER_VERIFICATIONS: {
1530                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1531                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1532                            params.replacing, params.pkg);
1533                    break;
1534                }
1535                case INTENT_FILTER_VERIFIED: {
1536                    final int verificationId = msg.arg1;
1537
1538                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1539                            verificationId);
1540                    if (state == null) {
1541                        Slog.w(TAG, "Invalid IntentFilter verification token "
1542                                + verificationId + " received");
1543                        break;
1544                    }
1545
1546                    final int userId = state.getUserId();
1547
1548                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1549                            "Processing IntentFilter verification with token:"
1550                            + verificationId + " and userId:" + userId);
1551
1552                    final IntentFilterVerificationResponse response =
1553                            (IntentFilterVerificationResponse) msg.obj;
1554
1555                    state.setVerifierResponse(response.callerUid, response.code);
1556
1557                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1558                            "IntentFilter verification with token:" + verificationId
1559                            + " and userId:" + userId
1560                            + " is settings verifier response with response code:"
1561                            + response.code);
1562
1563                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1564                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1565                                + response.getFailedDomainsString());
1566                    }
1567
1568                    if (state.isVerificationComplete()) {
1569                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1570                    } else {
1571                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1572                                "IntentFilter verification with token:" + verificationId
1573                                + " was not said to be complete");
1574                    }
1575
1576                    break;
1577                }
1578            }
1579        }
1580    }
1581
1582    private StorageEventListener mStorageListener = new StorageEventListener() {
1583        @Override
1584        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1585            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1586                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1587                    // TODO: ensure that private directories exist for all active users
1588                    // TODO: remove user data whose serial number doesn't match
1589                    loadPrivatePackages(vol);
1590                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1591                    unloadPrivatePackages(vol);
1592                }
1593            }
1594
1595            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1596                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1597                    updateExternalMediaStatus(true, false);
1598                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1599                    updateExternalMediaStatus(false, false);
1600                }
1601            }
1602        }
1603
1604        @Override
1605        public void onVolumeForgotten(String fsUuid) {
1606            // TODO: remove all packages hosted on this uuid
1607        }
1608    };
1609
1610    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) {
1611        if (userId >= UserHandle.USER_OWNER) {
1612            grantRequestedRuntimePermissionsForUser(pkg, userId);
1613        } else if (userId == UserHandle.USER_ALL) {
1614            for (int someUserId : UserManagerService.getInstance().getUserIds()) {
1615                grantRequestedRuntimePermissionsForUser(pkg, someUserId);
1616            }
1617        }
1618
1619        // We could have touched GID membership, so flush out packages.list
1620        synchronized (mPackages) {
1621            mSettings.writePackageListLPr();
1622        }
1623    }
1624
1625    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) {
1626        SettingBase sb = (SettingBase) pkg.mExtras;
1627        if (sb == null) {
1628            return;
1629        }
1630
1631        PermissionsState permissionsState = sb.getPermissionsState();
1632
1633        for (String permission : pkg.requestedPermissions) {
1634            BasePermission bp = mSettings.mPermissions.get(permission);
1635            if (bp != null && bp.isRuntime()) {
1636                permissionsState.grantRuntimePermission(bp, userId);
1637            }
1638        }
1639    }
1640
1641    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1642        Bundle extras = null;
1643        switch (res.returnCode) {
1644            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1645                extras = new Bundle();
1646                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1647                        res.origPermission);
1648                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1649                        res.origPackage);
1650                break;
1651            }
1652            case PackageManager.INSTALL_SUCCEEDED: {
1653                extras = new Bundle();
1654                extras.putBoolean(Intent.EXTRA_REPLACING,
1655                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1656                break;
1657            }
1658        }
1659        return extras;
1660    }
1661
1662    void scheduleWriteSettingsLocked() {
1663        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1664            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1665        }
1666    }
1667
1668    void scheduleWritePackageRestrictionsLocked(int userId) {
1669        if (!sUserManager.exists(userId)) return;
1670        mDirtyUsers.add(userId);
1671        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1672            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1673        }
1674    }
1675
1676    public static PackageManagerService main(Context context, Installer installer,
1677            boolean factoryTest, boolean onlyCore) {
1678        PackageManagerService m = new PackageManagerService(context, installer,
1679                factoryTest, onlyCore);
1680        ServiceManager.addService("package", m);
1681        return m;
1682    }
1683
1684    static String[] splitString(String str, char sep) {
1685        int count = 1;
1686        int i = 0;
1687        while ((i=str.indexOf(sep, i)) >= 0) {
1688            count++;
1689            i++;
1690        }
1691
1692        String[] res = new String[count];
1693        i=0;
1694        count = 0;
1695        int lastI=0;
1696        while ((i=str.indexOf(sep, i)) >= 0) {
1697            res[count] = str.substring(lastI, i);
1698            count++;
1699            i++;
1700            lastI = i;
1701        }
1702        res[count] = str.substring(lastI, str.length());
1703        return res;
1704    }
1705
1706    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1707        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1708                Context.DISPLAY_SERVICE);
1709        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1710    }
1711
1712    public PackageManagerService(Context context, Installer installer,
1713            boolean factoryTest, boolean onlyCore) {
1714        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1715                SystemClock.uptimeMillis());
1716
1717        if (mSdkVersion <= 0) {
1718            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1719        }
1720
1721        mContext = context;
1722        mFactoryTest = factoryTest;
1723        mOnlyCore = onlyCore;
1724        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1725        mMetrics = new DisplayMetrics();
1726        mSettings = new Settings(mPackages);
1727        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1728                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1729        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1730                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1731        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1732                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1733        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1734                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1735        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1736                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1737        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1738                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1739
1740        // TODO: add a property to control this?
1741        long dexOptLRUThresholdInMinutes;
1742        if (mLazyDexOpt) {
1743            dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1744        } else {
1745            dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1746        }
1747        mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1748
1749        String separateProcesses = SystemProperties.get("debug.separate_processes");
1750        if (separateProcesses != null && separateProcesses.length() > 0) {
1751            if ("*".equals(separateProcesses)) {
1752                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1753                mSeparateProcesses = null;
1754                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1755            } else {
1756                mDefParseFlags = 0;
1757                mSeparateProcesses = separateProcesses.split(",");
1758                Slog.w(TAG, "Running with debug.separate_processes: "
1759                        + separateProcesses);
1760            }
1761        } else {
1762            mDefParseFlags = 0;
1763            mSeparateProcesses = null;
1764        }
1765
1766        mInstaller = installer;
1767        mPackageDexOptimizer = new PackageDexOptimizer(this);
1768        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1769
1770        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1771                FgThread.get().getLooper());
1772
1773        getDefaultDisplayMetrics(context, mMetrics);
1774
1775        SystemConfig systemConfig = SystemConfig.getInstance();
1776        mGlobalGids = systemConfig.getGlobalGids();
1777        mSystemPermissions = systemConfig.getSystemPermissions();
1778        mAvailableFeatures = systemConfig.getAvailableFeatures();
1779
1780        synchronized (mInstallLock) {
1781        // writer
1782        synchronized (mPackages) {
1783            mHandlerThread = new ServiceThread(TAG,
1784                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1785            mHandlerThread.start();
1786            mHandler = new PackageHandler(mHandlerThread.getLooper());
1787            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1788
1789            File dataDir = Environment.getDataDirectory();
1790            mAppDataDir = new File(dataDir, "data");
1791            mAppInstallDir = new File(dataDir, "app");
1792            mAppLib32InstallDir = new File(dataDir, "app-lib");
1793            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1794            mUserAppDataDir = new File(dataDir, "user");
1795            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1796
1797            sUserManager = new UserManagerService(context, this,
1798                    mInstallLock, mPackages);
1799
1800            // Propagate permission configuration in to package manager.
1801            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1802                    = systemConfig.getPermissions();
1803            for (int i=0; i<permConfig.size(); i++) {
1804                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1805                BasePermission bp = mSettings.mPermissions.get(perm.name);
1806                if (bp == null) {
1807                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1808                    mSettings.mPermissions.put(perm.name, bp);
1809                }
1810                if (perm.gids != null) {
1811                    bp.setGids(perm.gids, perm.perUser);
1812                }
1813            }
1814
1815            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1816            for (int i=0; i<libConfig.size(); i++) {
1817                mSharedLibraries.put(libConfig.keyAt(i),
1818                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1819            }
1820
1821            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1822
1823            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1824                    mSdkVersion, mOnlyCore);
1825
1826            String customResolverActivity = Resources.getSystem().getString(
1827                    R.string.config_customResolverActivity);
1828            if (TextUtils.isEmpty(customResolverActivity)) {
1829                customResolverActivity = null;
1830            } else {
1831                mCustomResolverComponentName = ComponentName.unflattenFromString(
1832                        customResolverActivity);
1833            }
1834
1835            long startTime = SystemClock.uptimeMillis();
1836
1837            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1838                    startTime);
1839
1840            // Set flag to monitor and not change apk file paths when
1841            // scanning install directories.
1842            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
1843
1844            final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1845
1846            /**
1847             * Add everything in the in the boot class path to the
1848             * list of process files because dexopt will have been run
1849             * if necessary during zygote startup.
1850             */
1851            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1852            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1853
1854            if (bootClassPath != null) {
1855                String[] bootClassPathElements = splitString(bootClassPath, ':');
1856                for (String element : bootClassPathElements) {
1857                    alreadyDexOpted.add(element);
1858                }
1859            } else {
1860                Slog.w(TAG, "No BOOTCLASSPATH found!");
1861            }
1862
1863            if (systemServerClassPath != null) {
1864                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1865                for (String element : systemServerClassPathElements) {
1866                    alreadyDexOpted.add(element);
1867                }
1868            } else {
1869                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1870            }
1871
1872            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
1873            final String[] dexCodeInstructionSets =
1874                    getDexCodeInstructionSets(
1875                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
1876
1877            /**
1878             * Ensure all external libraries have had dexopt run on them.
1879             */
1880            if (mSharedLibraries.size() > 0) {
1881                // NOTE: For now, we're compiling these system "shared libraries"
1882                // (and framework jars) into all available architectures. It's possible
1883                // to compile them only when we come across an app that uses them (there's
1884                // already logic for that in scanPackageLI) but that adds some complexity.
1885                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1886                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1887                        final String lib = libEntry.path;
1888                        if (lib == null) {
1889                            continue;
1890                        }
1891
1892                        try {
1893                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
1894                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1895                                alreadyDexOpted.add(lib);
1896                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1897                            }
1898                        } catch (FileNotFoundException e) {
1899                            Slog.w(TAG, "Library not found: " + lib);
1900                        } catch (IOException e) {
1901                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1902                                    + e.getMessage());
1903                        }
1904                    }
1905                }
1906            }
1907
1908            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1909
1910            // Gross hack for now: we know this file doesn't contain any
1911            // code, so don't dexopt it to avoid the resulting log spew.
1912            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1913
1914            // Gross hack for now: we know this file is only part of
1915            // the boot class path for art, so don't dexopt it to
1916            // avoid the resulting log spew.
1917            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1918
1919            /**
1920             * There are a number of commands implemented in Java, which
1921             * we currently need to do the dexopt on so that they can be
1922             * run from a non-root shell.
1923             */
1924            String[] frameworkFiles = frameworkDir.list();
1925            if (frameworkFiles != null) {
1926                // TODO: We could compile these only for the most preferred ABI. We should
1927                // first double check that the dex files for these commands are not referenced
1928                // by other system apps.
1929                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1930                    for (int i=0; i<frameworkFiles.length; i++) {
1931                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1932                        String path = libPath.getPath();
1933                        // Skip the file if we already did it.
1934                        if (alreadyDexOpted.contains(path)) {
1935                            continue;
1936                        }
1937                        // Skip the file if it is not a type we want to dexopt.
1938                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1939                            continue;
1940                        }
1941                        try {
1942                            int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false);
1943                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1944                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1945                            }
1946                        } catch (FileNotFoundException e) {
1947                            Slog.w(TAG, "Jar not found: " + path);
1948                        } catch (IOException e) {
1949                            Slog.w(TAG, "Exception reading jar: " + path, e);
1950                        }
1951                    }
1952                }
1953            }
1954
1955            // Collect vendor overlay packages.
1956            // (Do this before scanning any apps.)
1957            // For security and version matching reason, only consider
1958            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1959            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1960            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1961                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
1962
1963            // Find base frameworks (resource packages without code).
1964            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1965                    | PackageParser.PARSE_IS_SYSTEM_DIR
1966                    | PackageParser.PARSE_IS_PRIVILEGED,
1967                    scanFlags | SCAN_NO_DEX, 0);
1968
1969            // Collected privileged system packages.
1970            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1971            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1972                    | PackageParser.PARSE_IS_SYSTEM_DIR
1973                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
1974
1975            // Collect ordinary system packages.
1976            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
1977            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1978                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1979
1980            // Collect all vendor packages.
1981            File vendorAppDir = new File("/vendor/app");
1982            try {
1983                vendorAppDir = vendorAppDir.getCanonicalFile();
1984            } catch (IOException e) {
1985                // failed to look up canonical path, continue with original one
1986            }
1987            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1988                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1989
1990            // Collect all OEM packages.
1991            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
1992            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
1993                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1994
1995            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1996            mInstaller.moveFiles();
1997
1998            // Prune any system packages that no longer exist.
1999            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2000            final ArrayMap<String, File> expectingBetter = new ArrayMap<>();
2001            if (!mOnlyCore) {
2002                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2003                while (psit.hasNext()) {
2004                    PackageSetting ps = psit.next();
2005
2006                    /*
2007                     * If this is not a system app, it can't be a
2008                     * disable system app.
2009                     */
2010                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2011                        continue;
2012                    }
2013
2014                    /*
2015                     * If the package is scanned, it's not erased.
2016                     */
2017                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2018                    if (scannedPkg != null) {
2019                        /*
2020                         * If the system app is both scanned and in the
2021                         * disabled packages list, then it must have been
2022                         * added via OTA. Remove it from the currently
2023                         * scanned package so the previously user-installed
2024                         * application can be scanned.
2025                         */
2026                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2027                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2028                                    + ps.name + "; removing system app.  Last known codePath="
2029                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2030                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2031                                    + scannedPkg.mVersionCode);
2032                            removePackageLI(ps, true);
2033                            expectingBetter.put(ps.name, ps.codePath);
2034                        }
2035
2036                        continue;
2037                    }
2038
2039                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2040                        psit.remove();
2041                        logCriticalInfo(Log.WARN, "System package " + ps.name
2042                                + " no longer exists; wiping its data");
2043                        removeDataDirsLI(null, ps.name);
2044                    } else {
2045                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2046                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2047                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2048                        }
2049                    }
2050                }
2051            }
2052
2053            //look for any incomplete package installations
2054            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2055            //clean up list
2056            for(int i = 0; i < deletePkgsList.size(); i++) {
2057                //clean up here
2058                cleanupInstallFailedPackage(deletePkgsList.get(i));
2059            }
2060            //delete tmp files
2061            deleteTempPackageFiles();
2062
2063            // Remove any shared userIDs that have no associated packages
2064            mSettings.pruneSharedUsersLPw();
2065
2066            if (!mOnlyCore) {
2067                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2068                        SystemClock.uptimeMillis());
2069                scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2070
2071                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2072                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2073
2074                /**
2075                 * Remove disable package settings for any updated system
2076                 * apps that were removed via an OTA. If they're not a
2077                 * previously-updated app, remove them completely.
2078                 * Otherwise, just revoke their system-level permissions.
2079                 */
2080                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2081                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2082                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2083
2084                    String msg;
2085                    if (deletedPkg == null) {
2086                        msg = "Updated system package " + deletedAppName
2087                                + " no longer exists; wiping its data";
2088                        removeDataDirsLI(null, deletedAppName);
2089                    } else {
2090                        msg = "Updated system app + " + deletedAppName
2091                                + " no longer present; removing system privileges for "
2092                                + deletedAppName;
2093
2094                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2095
2096                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2097                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2098                    }
2099                    logCriticalInfo(Log.WARN, msg);
2100                }
2101
2102                /**
2103                 * Make sure all system apps that we expected to appear on
2104                 * the userdata partition actually showed up. If they never
2105                 * appeared, crawl back and revive the system version.
2106                 */
2107                for (int i = 0; i < expectingBetter.size(); i++) {
2108                    final String packageName = expectingBetter.keyAt(i);
2109                    if (!mPackages.containsKey(packageName)) {
2110                        final File scanFile = expectingBetter.valueAt(i);
2111
2112                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2113                                + " but never showed up; reverting to system");
2114
2115                        final int reparseFlags;
2116                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2117                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2118                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2119                                    | PackageParser.PARSE_IS_PRIVILEGED;
2120                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2121                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2122                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2123                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2124                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2125                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2126                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2127                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2128                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2129                        } else {
2130                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2131                            continue;
2132                        }
2133
2134                        mSettings.enableSystemPackageLPw(packageName);
2135
2136                        try {
2137                            scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
2138                        } catch (PackageManagerException e) {
2139                            Slog.e(TAG, "Failed to parse original system package: "
2140                                    + e.getMessage());
2141                        }
2142                    }
2143                }
2144            }
2145
2146            // Now that we know all of the shared libraries, update all clients to have
2147            // the correct library paths.
2148            updateAllSharedLibrariesLPw();
2149
2150            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2151                // NOTE: We ignore potential failures here during a system scan (like
2152                // the rest of the commands above) because there's precious little we
2153                // can do about it. A settings error is reported, though.
2154                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2155                        false /* force dexopt */, false /* defer dexopt */);
2156            }
2157
2158            // Now that we know all the packages we are keeping,
2159            // read and update their last usage times.
2160            mPackageUsage.readLP();
2161
2162            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2163                    SystemClock.uptimeMillis());
2164            Slog.i(TAG, "Time to scan packages: "
2165                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2166                    + " seconds");
2167
2168            // If the platform SDK has changed since the last time we booted,
2169            // we need to re-grant app permission to catch any new ones that
2170            // appear.  This is really a hack, and means that apps can in some
2171            // cases get permissions that the user didn't initially explicitly
2172            // allow...  it would be nice to have some better way to handle
2173            // this situation.
2174            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
2175                    != mSdkVersion;
2176            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
2177                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
2178                    + "; regranting permissions for internal storage");
2179            mSettings.mInternalSdkPlatform = mSdkVersion;
2180
2181            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
2182                    | (regrantPermissions
2183                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
2184                            : 0));
2185
2186            // If this is the first boot, and it is a normal boot, then
2187            // we need to initialize the default preferred apps.
2188            if (!mRestoredSettings && !onlyCore) {
2189                mSettings.readDefaultPreferredAppsLPw(this, 0);
2190            }
2191
2192            // If this is first boot after an OTA, and a normal boot, then
2193            // we need to clear code cache directories.
2194            mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint);
2195            if (mIsUpgrade && !onlyCore) {
2196                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2197                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2198                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2199                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2200                }
2201                mSettings.mFingerprint = Build.FINGERPRINT;
2202            }
2203
2204            primeDomainVerificationsLPw();
2205            checkDefaultBrowser();
2206
2207            // All the changes are done during package scanning.
2208            mSettings.updateInternalDatabaseVersion();
2209
2210            // can downgrade to reader
2211            mSettings.writeLPr();
2212
2213            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2214                    SystemClock.uptimeMillis());
2215
2216            mRequiredVerifierPackage = getRequiredVerifierLPr();
2217
2218            mInstallerService = new PackageInstallerService(context, this);
2219
2220            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2221            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2222                    mIntentFilterVerifierComponent);
2223
2224        } // synchronized (mPackages)
2225        } // synchronized (mInstallLock)
2226
2227        // Now after opening every single application zip, make sure they
2228        // are all flushed.  Not really needed, but keeps things nice and
2229        // tidy.
2230        Runtime.getRuntime().gc();
2231
2232        // Expose private service for system components to use.
2233        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2234    }
2235
2236    @Override
2237    public boolean isFirstBoot() {
2238        return !mRestoredSettings;
2239    }
2240
2241    @Override
2242    public boolean isOnlyCoreApps() {
2243        return mOnlyCore;
2244    }
2245
2246    @Override
2247    public boolean isUpgrade() {
2248        return mIsUpgrade;
2249    }
2250
2251    private String getRequiredVerifierLPr() {
2252        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2253        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2254                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
2255
2256        String requiredVerifier = null;
2257
2258        final int N = receivers.size();
2259        for (int i = 0; i < N; i++) {
2260            final ResolveInfo info = receivers.get(i);
2261
2262            if (info.activityInfo == null) {
2263                continue;
2264            }
2265
2266            final String packageName = info.activityInfo.packageName;
2267
2268            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2269                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2270                continue;
2271            }
2272
2273            if (requiredVerifier != null) {
2274                throw new RuntimeException("There can be only one required verifier");
2275            }
2276
2277            requiredVerifier = packageName;
2278        }
2279
2280        return requiredVerifier;
2281    }
2282
2283    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2284        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2285        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2286                PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */);
2287
2288        ComponentName verifierComponentName = null;
2289
2290        int priority = -1000;
2291        final int N = receivers.size();
2292        for (int i = 0; i < N; i++) {
2293            final ResolveInfo info = receivers.get(i);
2294
2295            if (info.activityInfo == null) {
2296                continue;
2297            }
2298
2299            final String packageName = info.activityInfo.packageName;
2300
2301            final PackageSetting ps = mSettings.mPackages.get(packageName);
2302            if (ps == null) {
2303                continue;
2304            }
2305
2306            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2307                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2308                continue;
2309            }
2310
2311            // Select the IntentFilterVerifier with the highest priority
2312            if (priority < info.priority) {
2313                priority = info.priority;
2314                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2315                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2316                        + verifierComponentName + " with priority: " + info.priority);
2317            }
2318        }
2319
2320        return verifierComponentName;
2321    }
2322
2323    private void primeDomainVerificationsLPw() {
2324        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Start priming domain verifications");
2325        boolean updated = false;
2326        ArraySet<String> allHostsSet = new ArraySet<>();
2327        for (PackageParser.Package pkg : mPackages.values()) {
2328            final String packageName = pkg.packageName;
2329            if (!hasDomainURLs(pkg)) {
2330                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "No priming domain verifications for " +
2331                            "package with no domain URLs: " + packageName);
2332                continue;
2333            }
2334            if (!pkg.isSystemApp()) {
2335                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2336                        "No priming domain verifications for a non system package : " +
2337                                packageName);
2338                continue;
2339            }
2340            for (PackageParser.Activity a : pkg.activities) {
2341                for (ActivityIntentInfo filter : a.intents) {
2342                    if (hasValidDomains(filter)) {
2343                        allHostsSet.addAll(filter.getHostsList());
2344                    }
2345                }
2346            }
2347            if (allHostsSet.size() == 0) {
2348                allHostsSet.add("*");
2349            }
2350            ArrayList<String> allHostsList = new ArrayList<>(allHostsSet);
2351            IntentFilterVerificationInfo ivi =
2352                    mSettings.createIntentFilterVerificationIfNeededLPw(packageName, allHostsList);
2353            if (ivi != null) {
2354                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2355                        "Priming domain verifications for package: " + packageName +
2356                        " with hosts:" + ivi.getDomainsString());
2357                ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
2358                updated = true;
2359            }
2360            else {
2361                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2362                        "No priming domain verifications for package: " + packageName);
2363            }
2364            allHostsSet.clear();
2365        }
2366        if (updated) {
2367            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2368                    "Will need to write primed domain verifications");
2369        }
2370        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "End priming domain verifications");
2371    }
2372
2373    private void checkDefaultBrowser() {
2374        final int myUserId = UserHandle.myUserId();
2375        final String packageName = getDefaultBrowserPackageName(myUserId);
2376        PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2377        if (info == null) {
2378            Slog.w(TAG, "Default browser no longer installed: " + packageName);
2379            setDefaultBrowserPackageName(null, myUserId);
2380        }
2381    }
2382
2383    @Override
2384    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2385            throws RemoteException {
2386        try {
2387            return super.onTransact(code, data, reply, flags);
2388        } catch (RuntimeException e) {
2389            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2390                Slog.wtf(TAG, "Package Manager Crash", e);
2391            }
2392            throw e;
2393        }
2394    }
2395
2396    void cleanupInstallFailedPackage(PackageSetting ps) {
2397        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2398
2399        removeDataDirsLI(ps.volumeUuid, ps.name);
2400        if (ps.codePath != null) {
2401            if (ps.codePath.isDirectory()) {
2402                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2403            } else {
2404                ps.codePath.delete();
2405            }
2406        }
2407        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2408            if (ps.resourcePath.isDirectory()) {
2409                FileUtils.deleteContents(ps.resourcePath);
2410            }
2411            ps.resourcePath.delete();
2412        }
2413        mSettings.removePackageLPw(ps.name);
2414    }
2415
2416    static int[] appendInts(int[] cur, int[] add) {
2417        if (add == null) return cur;
2418        if (cur == null) return add;
2419        final int N = add.length;
2420        for (int i=0; i<N; i++) {
2421            cur = appendInt(cur, add[i]);
2422        }
2423        return cur;
2424    }
2425
2426    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2427        if (!sUserManager.exists(userId)) return null;
2428        final PackageSetting ps = (PackageSetting) p.mExtras;
2429        if (ps == null) {
2430            return null;
2431        }
2432
2433        final PermissionsState permissionsState = ps.getPermissionsState();
2434
2435        final int[] gids = permissionsState.computeGids(userId);
2436        final Set<String> permissions = permissionsState.getPermissions(userId);
2437        final PackageUserState state = ps.readUserState(userId);
2438
2439        return PackageParser.generatePackageInfo(p, gids, flags,
2440                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2441    }
2442
2443    @Override
2444    public boolean isPackageFrozen(String packageName) {
2445        synchronized (mPackages) {
2446            final PackageSetting ps = mSettings.mPackages.get(packageName);
2447            if (ps != null) {
2448                return ps.frozen;
2449            }
2450        }
2451        Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen");
2452        return true;
2453    }
2454
2455    @Override
2456    public boolean isPackageAvailable(String packageName, int userId) {
2457        if (!sUserManager.exists(userId)) return false;
2458        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2459        synchronized (mPackages) {
2460            PackageParser.Package p = mPackages.get(packageName);
2461            if (p != null) {
2462                final PackageSetting ps = (PackageSetting) p.mExtras;
2463                if (ps != null) {
2464                    final PackageUserState state = ps.readUserState(userId);
2465                    if (state != null) {
2466                        return PackageParser.isAvailable(state);
2467                    }
2468                }
2469            }
2470        }
2471        return false;
2472    }
2473
2474    @Override
2475    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2476        if (!sUserManager.exists(userId)) return null;
2477        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2478        // reader
2479        synchronized (mPackages) {
2480            PackageParser.Package p = mPackages.get(packageName);
2481            if (DEBUG_PACKAGE_INFO)
2482                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2483            if (p != null) {
2484                return generatePackageInfo(p, flags, userId);
2485            }
2486            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2487                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2488            }
2489        }
2490        return null;
2491    }
2492
2493    @Override
2494    public String[] currentToCanonicalPackageNames(String[] names) {
2495        String[] out = new String[names.length];
2496        // reader
2497        synchronized (mPackages) {
2498            for (int i=names.length-1; i>=0; i--) {
2499                PackageSetting ps = mSettings.mPackages.get(names[i]);
2500                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2501            }
2502        }
2503        return out;
2504    }
2505
2506    @Override
2507    public String[] canonicalToCurrentPackageNames(String[] names) {
2508        String[] out = new String[names.length];
2509        // reader
2510        synchronized (mPackages) {
2511            for (int i=names.length-1; i>=0; i--) {
2512                String cur = mSettings.mRenamedPackages.get(names[i]);
2513                out[i] = cur != null ? cur : names[i];
2514            }
2515        }
2516        return out;
2517    }
2518
2519    @Override
2520    public int getPackageUid(String packageName, int userId) {
2521        if (!sUserManager.exists(userId)) return -1;
2522        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2523
2524        // reader
2525        synchronized (mPackages) {
2526            PackageParser.Package p = mPackages.get(packageName);
2527            if(p != null) {
2528                return UserHandle.getUid(userId, p.applicationInfo.uid);
2529            }
2530            PackageSetting ps = mSettings.mPackages.get(packageName);
2531            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2532                return -1;
2533            }
2534            p = ps.pkg;
2535            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2536        }
2537    }
2538
2539    @Override
2540    public int[] getPackageGids(String packageName, int userId) throws RemoteException {
2541        if (!sUserManager.exists(userId)) {
2542            return null;
2543        }
2544
2545        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2546                "getPackageGids");
2547
2548        // reader
2549        synchronized (mPackages) {
2550            PackageParser.Package p = mPackages.get(packageName);
2551            if (DEBUG_PACKAGE_INFO) {
2552                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2553            }
2554            if (p != null) {
2555                PackageSetting ps = (PackageSetting) p.mExtras;
2556                return ps.getPermissionsState().computeGids(userId);
2557            }
2558        }
2559
2560        return null;
2561    }
2562
2563    static PermissionInfo generatePermissionInfo(
2564            BasePermission bp, int flags) {
2565        if (bp.perm != null) {
2566            return PackageParser.generatePermissionInfo(bp.perm, flags);
2567        }
2568        PermissionInfo pi = new PermissionInfo();
2569        pi.name = bp.name;
2570        pi.packageName = bp.sourcePackage;
2571        pi.nonLocalizedLabel = bp.name;
2572        pi.protectionLevel = bp.protectionLevel;
2573        return pi;
2574    }
2575
2576    @Override
2577    public PermissionInfo getPermissionInfo(String name, int flags) {
2578        // reader
2579        synchronized (mPackages) {
2580            final BasePermission p = mSettings.mPermissions.get(name);
2581            if (p != null) {
2582                return generatePermissionInfo(p, flags);
2583            }
2584            return null;
2585        }
2586    }
2587
2588    @Override
2589    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2590        // reader
2591        synchronized (mPackages) {
2592            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2593            for (BasePermission p : mSettings.mPermissions.values()) {
2594                if (group == null) {
2595                    if (p.perm == null || p.perm.info.group == null) {
2596                        out.add(generatePermissionInfo(p, flags));
2597                    }
2598                } else {
2599                    if (p.perm != null && group.equals(p.perm.info.group)) {
2600                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2601                    }
2602                }
2603            }
2604
2605            if (out.size() > 0) {
2606                return out;
2607            }
2608            return mPermissionGroups.containsKey(group) ? out : null;
2609        }
2610    }
2611
2612    @Override
2613    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2614        // reader
2615        synchronized (mPackages) {
2616            return PackageParser.generatePermissionGroupInfo(
2617                    mPermissionGroups.get(name), flags);
2618        }
2619    }
2620
2621    @Override
2622    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2623        // reader
2624        synchronized (mPackages) {
2625            final int N = mPermissionGroups.size();
2626            ArrayList<PermissionGroupInfo> out
2627                    = new ArrayList<PermissionGroupInfo>(N);
2628            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2629                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2630            }
2631            return out;
2632        }
2633    }
2634
2635    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2636            int userId) {
2637        if (!sUserManager.exists(userId)) return null;
2638        PackageSetting ps = mSettings.mPackages.get(packageName);
2639        if (ps != null) {
2640            if (ps.pkg == null) {
2641                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2642                        flags, userId);
2643                if (pInfo != null) {
2644                    return pInfo.applicationInfo;
2645                }
2646                return null;
2647            }
2648            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2649                    ps.readUserState(userId), userId);
2650        }
2651        return null;
2652    }
2653
2654    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2655            int userId) {
2656        if (!sUserManager.exists(userId)) return null;
2657        PackageSetting ps = mSettings.mPackages.get(packageName);
2658        if (ps != null) {
2659            PackageParser.Package pkg = ps.pkg;
2660            if (pkg == null) {
2661                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2662                    return null;
2663                }
2664                // Only data remains, so we aren't worried about code paths
2665                pkg = new PackageParser.Package(packageName);
2666                pkg.applicationInfo.packageName = packageName;
2667                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2668                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2669                pkg.applicationInfo.dataDir = PackageManager.getDataDirForUser(ps.volumeUuid,
2670                        packageName, userId).getAbsolutePath();
2671                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2672                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2673            }
2674            return generatePackageInfo(pkg, flags, userId);
2675        }
2676        return null;
2677    }
2678
2679    @Override
2680    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2681        if (!sUserManager.exists(userId)) return null;
2682        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2683        // writer
2684        synchronized (mPackages) {
2685            PackageParser.Package p = mPackages.get(packageName);
2686            if (DEBUG_PACKAGE_INFO) Log.v(
2687                    TAG, "getApplicationInfo " + packageName
2688                    + ": " + p);
2689            if (p != null) {
2690                PackageSetting ps = mSettings.mPackages.get(packageName);
2691                if (ps == null) return null;
2692                // Note: isEnabledLP() does not apply here - always return info
2693                return PackageParser.generateApplicationInfo(
2694                        p, flags, ps.readUserState(userId), userId);
2695            }
2696            if ("android".equals(packageName)||"system".equals(packageName)) {
2697                return mAndroidApplication;
2698            }
2699            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2700                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2701            }
2702        }
2703        return null;
2704    }
2705
2706    @Override
2707    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
2708            final IPackageDataObserver observer) {
2709        mContext.enforceCallingOrSelfPermission(
2710                android.Manifest.permission.CLEAR_APP_CACHE, null);
2711        // Queue up an async operation since clearing cache may take a little while.
2712        mHandler.post(new Runnable() {
2713            public void run() {
2714                mHandler.removeCallbacks(this);
2715                int retCode = -1;
2716                synchronized (mInstallLock) {
2717                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2718                    if (retCode < 0) {
2719                        Slog.w(TAG, "Couldn't clear application caches");
2720                    }
2721                }
2722                if (observer != null) {
2723                    try {
2724                        observer.onRemoveCompleted(null, (retCode >= 0));
2725                    } catch (RemoteException e) {
2726                        Slog.w(TAG, "RemoveException when invoking call back");
2727                    }
2728                }
2729            }
2730        });
2731    }
2732
2733    @Override
2734    public void freeStorage(final String volumeUuid, final long freeStorageSize,
2735            final IntentSender pi) {
2736        mContext.enforceCallingOrSelfPermission(
2737                android.Manifest.permission.CLEAR_APP_CACHE, null);
2738        // Queue up an async operation since clearing cache may take a little while.
2739        mHandler.post(new Runnable() {
2740            public void run() {
2741                mHandler.removeCallbacks(this);
2742                int retCode = -1;
2743                synchronized (mInstallLock) {
2744                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2745                    if (retCode < 0) {
2746                        Slog.w(TAG, "Couldn't clear application caches");
2747                    }
2748                }
2749                if(pi != null) {
2750                    try {
2751                        // Callback via pending intent
2752                        int code = (retCode >= 0) ? 1 : 0;
2753                        pi.sendIntent(null, code, null,
2754                                null, null);
2755                    } catch (SendIntentException e1) {
2756                        Slog.i(TAG, "Failed to send pending intent");
2757                    }
2758                }
2759            }
2760        });
2761    }
2762
2763    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
2764        synchronized (mInstallLock) {
2765            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
2766                throw new IOException("Failed to free enough space");
2767            }
2768        }
2769    }
2770
2771    @Override
2772    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2773        if (!sUserManager.exists(userId)) return null;
2774        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2775        synchronized (mPackages) {
2776            PackageParser.Activity a = mActivities.mActivities.get(component);
2777
2778            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2779            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2780                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2781                if (ps == null) return null;
2782                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2783                        userId);
2784            }
2785            if (mResolveComponentName.equals(component)) {
2786                return PackageParser.generateActivityInfo(mResolveActivity, flags,
2787                        new PackageUserState(), userId);
2788            }
2789        }
2790        return null;
2791    }
2792
2793    @Override
2794    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2795            String resolvedType) {
2796        synchronized (mPackages) {
2797            PackageParser.Activity a = mActivities.mActivities.get(component);
2798            if (a == null) {
2799                return false;
2800            }
2801            for (int i=0; i<a.intents.size(); i++) {
2802                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2803                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2804                    return true;
2805                }
2806            }
2807            return false;
2808        }
2809    }
2810
2811    @Override
2812    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2813        if (!sUserManager.exists(userId)) return null;
2814        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
2815        synchronized (mPackages) {
2816            PackageParser.Activity a = mReceivers.mActivities.get(component);
2817            if (DEBUG_PACKAGE_INFO) Log.v(
2818                TAG, "getReceiverInfo " + component + ": " + a);
2819            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2820                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2821                if (ps == null) return null;
2822                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2823                        userId);
2824            }
2825        }
2826        return null;
2827    }
2828
2829    @Override
2830    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2831        if (!sUserManager.exists(userId)) return null;
2832        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
2833        synchronized (mPackages) {
2834            PackageParser.Service s = mServices.mServices.get(component);
2835            if (DEBUG_PACKAGE_INFO) Log.v(
2836                TAG, "getServiceInfo " + component + ": " + s);
2837            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2838                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2839                if (ps == null) return null;
2840                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2841                        userId);
2842            }
2843        }
2844        return null;
2845    }
2846
2847    @Override
2848    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2849        if (!sUserManager.exists(userId)) return null;
2850        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
2851        synchronized (mPackages) {
2852            PackageParser.Provider p = mProviders.mProviders.get(component);
2853            if (DEBUG_PACKAGE_INFO) Log.v(
2854                TAG, "getProviderInfo " + component + ": " + p);
2855            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2856                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2857                if (ps == null) return null;
2858                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2859                        userId);
2860            }
2861        }
2862        return null;
2863    }
2864
2865    @Override
2866    public String[] getSystemSharedLibraryNames() {
2867        Set<String> libSet;
2868        synchronized (mPackages) {
2869            libSet = mSharedLibraries.keySet();
2870            int size = libSet.size();
2871            if (size > 0) {
2872                String[] libs = new String[size];
2873                libSet.toArray(libs);
2874                return libs;
2875            }
2876        }
2877        return null;
2878    }
2879
2880    /**
2881     * @hide
2882     */
2883    PackageParser.Package findSharedNonSystemLibrary(String libName) {
2884        synchronized (mPackages) {
2885            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
2886            if (lib != null && lib.apk != null) {
2887                return mPackages.get(lib.apk);
2888            }
2889        }
2890        return null;
2891    }
2892
2893    @Override
2894    public FeatureInfo[] getSystemAvailableFeatures() {
2895        Collection<FeatureInfo> featSet;
2896        synchronized (mPackages) {
2897            featSet = mAvailableFeatures.values();
2898            int size = featSet.size();
2899            if (size > 0) {
2900                FeatureInfo[] features = new FeatureInfo[size+1];
2901                featSet.toArray(features);
2902                FeatureInfo fi = new FeatureInfo();
2903                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2904                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2905                features[size] = fi;
2906                return features;
2907            }
2908        }
2909        return null;
2910    }
2911
2912    @Override
2913    public boolean hasSystemFeature(String name) {
2914        synchronized (mPackages) {
2915            return mAvailableFeatures.containsKey(name);
2916        }
2917    }
2918
2919    private void checkValidCaller(int uid, int userId) {
2920        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2921            return;
2922
2923        throw new SecurityException("Caller uid=" + uid
2924                + " is not privileged to communicate with user=" + userId);
2925    }
2926
2927    @Override
2928    public int checkPermission(String permName, String pkgName, int userId) {
2929        if (!sUserManager.exists(userId)) {
2930            return PackageManager.PERMISSION_DENIED;
2931        }
2932
2933        synchronized (mPackages) {
2934            final PackageParser.Package p = mPackages.get(pkgName);
2935            if (p != null && p.mExtras != null) {
2936                final PackageSetting ps = (PackageSetting) p.mExtras;
2937                if (ps.getPermissionsState().hasPermission(permName, userId)) {
2938                    return PackageManager.PERMISSION_GRANTED;
2939                }
2940            }
2941        }
2942
2943        return PackageManager.PERMISSION_DENIED;
2944    }
2945
2946    @Override
2947    public int checkUidPermission(String permName, int uid) {
2948        final int userId = UserHandle.getUserId(uid);
2949
2950        if (!sUserManager.exists(userId)) {
2951            return PackageManager.PERMISSION_DENIED;
2952        }
2953
2954        synchronized (mPackages) {
2955            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2956            if (obj != null) {
2957                final SettingBase ps = (SettingBase) obj;
2958                if (ps.getPermissionsState().hasPermission(permName, userId)) {
2959                    return PackageManager.PERMISSION_GRANTED;
2960                }
2961            } else {
2962                ArraySet<String> perms = mSystemPermissions.get(uid);
2963                if (perms != null && perms.contains(permName)) {
2964                    return PackageManager.PERMISSION_GRANTED;
2965                }
2966            }
2967        }
2968
2969        return PackageManager.PERMISSION_DENIED;
2970    }
2971
2972    /**
2973     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2974     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2975     * @param checkShell TODO(yamasani):
2976     * @param message the message to log on security exception
2977     */
2978    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
2979            boolean checkShell, String message) {
2980        if (userId < 0) {
2981            throw new IllegalArgumentException("Invalid userId " + userId);
2982        }
2983        if (checkShell) {
2984            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
2985        }
2986        if (userId == UserHandle.getUserId(callingUid)) return;
2987        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2988            if (requireFullPermission) {
2989                mContext.enforceCallingOrSelfPermission(
2990                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2991            } else {
2992                try {
2993                    mContext.enforceCallingOrSelfPermission(
2994                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2995                } catch (SecurityException se) {
2996                    mContext.enforceCallingOrSelfPermission(
2997                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2998                }
2999            }
3000        }
3001    }
3002
3003    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3004        if (callingUid == Process.SHELL_UID) {
3005            if (userHandle >= 0
3006                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3007                throw new SecurityException("Shell does not have permission to access user "
3008                        + userHandle);
3009            } else if (userHandle < 0) {
3010                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3011                        + Debug.getCallers(3));
3012            }
3013        }
3014    }
3015
3016    private BasePermission findPermissionTreeLP(String permName) {
3017        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3018            if (permName.startsWith(bp.name) &&
3019                    permName.length() > bp.name.length() &&
3020                    permName.charAt(bp.name.length()) == '.') {
3021                return bp;
3022            }
3023        }
3024        return null;
3025    }
3026
3027    private BasePermission checkPermissionTreeLP(String permName) {
3028        if (permName != null) {
3029            BasePermission bp = findPermissionTreeLP(permName);
3030            if (bp != null) {
3031                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3032                    return bp;
3033                }
3034                throw new SecurityException("Calling uid "
3035                        + Binder.getCallingUid()
3036                        + " is not allowed to add to permission tree "
3037                        + bp.name + " owned by uid " + bp.uid);
3038            }
3039        }
3040        throw new SecurityException("No permission tree found for " + permName);
3041    }
3042
3043    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3044        if (s1 == null) {
3045            return s2 == null;
3046        }
3047        if (s2 == null) {
3048            return false;
3049        }
3050        if (s1.getClass() != s2.getClass()) {
3051            return false;
3052        }
3053        return s1.equals(s2);
3054    }
3055
3056    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3057        if (pi1.icon != pi2.icon) return false;
3058        if (pi1.logo != pi2.logo) return false;
3059        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3060        if (!compareStrings(pi1.name, pi2.name)) return false;
3061        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3062        // We'll take care of setting this one.
3063        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3064        // These are not currently stored in settings.
3065        //if (!compareStrings(pi1.group, pi2.group)) return false;
3066        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3067        //if (pi1.labelRes != pi2.labelRes) return false;
3068        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3069        return true;
3070    }
3071
3072    int permissionInfoFootprint(PermissionInfo info) {
3073        int size = info.name.length();
3074        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3075        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3076        return size;
3077    }
3078
3079    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3080        int size = 0;
3081        for (BasePermission perm : mSettings.mPermissions.values()) {
3082            if (perm.uid == tree.uid) {
3083                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3084            }
3085        }
3086        return size;
3087    }
3088
3089    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3090        // We calculate the max size of permissions defined by this uid and throw
3091        // if that plus the size of 'info' would exceed our stated maximum.
3092        if (tree.uid != Process.SYSTEM_UID) {
3093            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3094            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3095                throw new SecurityException("Permission tree size cap exceeded");
3096            }
3097        }
3098    }
3099
3100    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3101        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3102            throw new SecurityException("Label must be specified in permission");
3103        }
3104        BasePermission tree = checkPermissionTreeLP(info.name);
3105        BasePermission bp = mSettings.mPermissions.get(info.name);
3106        boolean added = bp == null;
3107        boolean changed = true;
3108        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3109        if (added) {
3110            enforcePermissionCapLocked(info, tree);
3111            bp = new BasePermission(info.name, tree.sourcePackage,
3112                    BasePermission.TYPE_DYNAMIC);
3113        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3114            throw new SecurityException(
3115                    "Not allowed to modify non-dynamic permission "
3116                    + info.name);
3117        } else {
3118            if (bp.protectionLevel == fixedLevel
3119                    && bp.perm.owner.equals(tree.perm.owner)
3120                    && bp.uid == tree.uid
3121                    && comparePermissionInfos(bp.perm.info, info)) {
3122                changed = false;
3123            }
3124        }
3125        bp.protectionLevel = fixedLevel;
3126        info = new PermissionInfo(info);
3127        info.protectionLevel = fixedLevel;
3128        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3129        bp.perm.info.packageName = tree.perm.info.packageName;
3130        bp.uid = tree.uid;
3131        if (added) {
3132            mSettings.mPermissions.put(info.name, bp);
3133        }
3134        if (changed) {
3135            if (!async) {
3136                mSettings.writeLPr();
3137            } else {
3138                scheduleWriteSettingsLocked();
3139            }
3140        }
3141        return added;
3142    }
3143
3144    @Override
3145    public boolean addPermission(PermissionInfo info) {
3146        synchronized (mPackages) {
3147            return addPermissionLocked(info, false);
3148        }
3149    }
3150
3151    @Override
3152    public boolean addPermissionAsync(PermissionInfo info) {
3153        synchronized (mPackages) {
3154            return addPermissionLocked(info, true);
3155        }
3156    }
3157
3158    @Override
3159    public void removePermission(String name) {
3160        synchronized (mPackages) {
3161            checkPermissionTreeLP(name);
3162            BasePermission bp = mSettings.mPermissions.get(name);
3163            if (bp != null) {
3164                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3165                    throw new SecurityException(
3166                            "Not allowed to modify non-dynamic permission "
3167                            + name);
3168                }
3169                mSettings.mPermissions.remove(name);
3170                mSettings.writeLPr();
3171            }
3172        }
3173    }
3174
3175    private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg,
3176            BasePermission bp) {
3177        int index = pkg.requestedPermissions.indexOf(bp.name);
3178        if (index == -1) {
3179            throw new SecurityException("Package " + pkg.packageName
3180                    + " has not requested permission " + bp.name);
3181        }
3182        if (!bp.isRuntime()) {
3183            throw new SecurityException("Permission " + bp.name
3184                    + " is not a changeable permission type");
3185        }
3186    }
3187
3188    @Override
3189    public void grantRuntimePermission(String packageName, String name, final int userId) {
3190        if (!sUserManager.exists(userId)) {
3191            Log.e(TAG, "No such user:" + userId);
3192            return;
3193        }
3194
3195        mContext.enforceCallingOrSelfPermission(
3196                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3197                "grantRuntimePermission");
3198
3199        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3200                "grantRuntimePermission");
3201
3202        final SettingBase sb;
3203
3204        synchronized (mPackages) {
3205            final PackageParser.Package pkg = mPackages.get(packageName);
3206            if (pkg == null) {
3207                throw new IllegalArgumentException("Unknown package: " + packageName);
3208            }
3209
3210            final BasePermission bp = mSettings.mPermissions.get(name);
3211            if (bp == null) {
3212                throw new IllegalArgumentException("Unknown permission: " + name);
3213            }
3214
3215            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3216
3217            sb = (SettingBase) pkg.mExtras;
3218            if (sb == null) {
3219                throw new IllegalArgumentException("Unknown package: " + packageName);
3220            }
3221
3222            final PermissionsState permissionsState = sb.getPermissionsState();
3223
3224            final int flags = permissionsState.getPermissionFlags(name, userId);
3225            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3226                throw new SecurityException("Cannot grant system fixed permission: "
3227                        + name + " for package: " + packageName);
3228            }
3229
3230            final int result = permissionsState.grantRuntimePermission(bp, userId);
3231            switch (result) {
3232                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3233                    return;
3234                }
3235
3236                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3237                    mHandler.post(new Runnable() {
3238                        @Override
3239                        public void run() {
3240                            killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED);
3241                        }
3242                    });
3243                } break;
3244            }
3245
3246            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3247
3248            // Not critical if that is lost - app has to request again.
3249            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3250        }
3251    }
3252
3253    @Override
3254    public void revokeRuntimePermission(String packageName, String name, int userId) {
3255        if (!sUserManager.exists(userId)) {
3256            Log.e(TAG, "No such user:" + userId);
3257            return;
3258        }
3259
3260        mContext.enforceCallingOrSelfPermission(
3261                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3262                "revokeRuntimePermission");
3263
3264        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3265                "revokeRuntimePermission");
3266
3267        final SettingBase sb;
3268
3269        synchronized (mPackages) {
3270            final PackageParser.Package pkg = mPackages.get(packageName);
3271            if (pkg == null) {
3272                throw new IllegalArgumentException("Unknown package: " + packageName);
3273            }
3274
3275            final BasePermission bp = mSettings.mPermissions.get(name);
3276            if (bp == null) {
3277                throw new IllegalArgumentException("Unknown permission: " + name);
3278            }
3279
3280            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3281
3282            sb = (SettingBase) pkg.mExtras;
3283            if (sb == null) {
3284                throw new IllegalArgumentException("Unknown package: " + packageName);
3285            }
3286
3287            final PermissionsState permissionsState = sb.getPermissionsState();
3288
3289            final int flags = permissionsState.getPermissionFlags(name, userId);
3290            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3291                throw new SecurityException("Cannot revoke system fixed permission: "
3292                        + name + " for package: " + packageName);
3293            }
3294
3295            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3296                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3297                return;
3298            }
3299
3300            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3301
3302            // Critical, after this call app should never have the permission.
3303            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3304        }
3305
3306        killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3307    }
3308
3309    @Override
3310    public int getPermissionFlags(String name, String packageName, int userId) {
3311        if (!sUserManager.exists(userId)) {
3312            return 0;
3313        }
3314
3315        mContext.enforceCallingOrSelfPermission(
3316                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3317                "getPermissionFlags");
3318
3319        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3320                "getPermissionFlags");
3321
3322        synchronized (mPackages) {
3323            final PackageParser.Package pkg = mPackages.get(packageName);
3324            if (pkg == null) {
3325                throw new IllegalArgumentException("Unknown package: " + packageName);
3326            }
3327
3328            final BasePermission bp = mSettings.mPermissions.get(name);
3329            if (bp == null) {
3330                throw new IllegalArgumentException("Unknown permission: " + name);
3331            }
3332
3333            SettingBase sb = (SettingBase) pkg.mExtras;
3334            if (sb == null) {
3335                throw new IllegalArgumentException("Unknown package: " + packageName);
3336            }
3337
3338            PermissionsState permissionsState = sb.getPermissionsState();
3339            return permissionsState.getPermissionFlags(name, userId);
3340        }
3341    }
3342
3343    @Override
3344    public void updatePermissionFlags(String name, String packageName, int flagMask,
3345            int flagValues, int userId) {
3346        if (!sUserManager.exists(userId)) {
3347            return;
3348        }
3349
3350        mContext.enforceCallingOrSelfPermission(
3351                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3352                "updatePermissionFlags");
3353
3354        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3355                "updatePermissionFlags");
3356
3357        // Only the system can change system fixed flags.
3358        if (getCallingUid() != Process.SYSTEM_UID) {
3359            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3360            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3361        }
3362
3363        synchronized (mPackages) {
3364            final PackageParser.Package pkg = mPackages.get(packageName);
3365            if (pkg == null) {
3366                throw new IllegalArgumentException("Unknown package: " + packageName);
3367            }
3368
3369            final BasePermission bp = mSettings.mPermissions.get(name);
3370            if (bp == null) {
3371                throw new IllegalArgumentException("Unknown permission: " + name);
3372            }
3373
3374            SettingBase sb = (SettingBase) pkg.mExtras;
3375            if (sb == null) {
3376                throw new IllegalArgumentException("Unknown package: " + packageName);
3377            }
3378
3379            PermissionsState permissionsState = sb.getPermissionsState();
3380
3381            // Only the package manager can change flags for system component permissions.
3382            final int flags = permissionsState.getPermissionFlags(bp.name, userId);
3383            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3384                return;
3385            }
3386
3387            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3388
3389            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3390                // Install and runtime permissions are stored in different places,
3391                // so figure out what permission changed and persist the change.
3392                if (permissionsState.getInstallPermissionState(name) != null) {
3393                    scheduleWriteSettingsLocked();
3394                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3395                        || hadState) {
3396                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3397                }
3398            }
3399        }
3400    }
3401
3402    /**
3403     * Update the permission flags for all packages and runtime permissions of a user in order
3404     * to allow device or profile owner to remove POLICY_FIXED.
3405     */
3406    @Override
3407    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3408        if (!sUserManager.exists(userId)) {
3409            return;
3410        }
3411
3412        mContext.enforceCallingOrSelfPermission(
3413                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3414                "updatePermissionFlagsForAllApps");
3415
3416        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3417                "updatePermissionFlagsForAllApps");
3418
3419        // Only the system can change system fixed flags.
3420        if (getCallingUid() != Process.SYSTEM_UID) {
3421            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3422            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3423        }
3424
3425        synchronized (mPackages) {
3426            boolean changed = false;
3427            final int packageCount = mPackages.size();
3428            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
3429                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
3430                SettingBase sb = (SettingBase) pkg.mExtras;
3431                if (sb == null) {
3432                    continue;
3433                }
3434                PermissionsState permissionsState = sb.getPermissionsState();
3435                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
3436                        userId, flagMask, flagValues);
3437            }
3438            if (changed) {
3439                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3440            }
3441        }
3442    }
3443
3444    @Override
3445    public boolean shouldShowRequestPermissionRationale(String permissionName,
3446            String packageName, int userId) {
3447        if (UserHandle.getCallingUserId() != userId) {
3448            mContext.enforceCallingPermission(
3449                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3450                    "canShowRequestPermissionRationale for user " + userId);
3451        }
3452
3453        final int uid = getPackageUid(packageName, userId);
3454        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
3455            return false;
3456        }
3457
3458        if (checkPermission(permissionName, packageName, userId)
3459                == PackageManager.PERMISSION_GRANTED) {
3460            return false;
3461        }
3462
3463        final int flags;
3464
3465        final long identity = Binder.clearCallingIdentity();
3466        try {
3467            flags = getPermissionFlags(permissionName,
3468                    packageName, userId);
3469        } finally {
3470            Binder.restoreCallingIdentity(identity);
3471        }
3472
3473        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
3474                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
3475                | PackageManager.FLAG_PERMISSION_USER_FIXED;
3476
3477        if ((flags & fixedFlags) != 0) {
3478            return false;
3479        }
3480
3481        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
3482    }
3483
3484    void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) {
3485        BasePermission bp = mSettings.mPermissions.get(permission);
3486        if (bp == null) {
3487            throw new SecurityException("Missing " + permission + " permission");
3488        }
3489
3490        SettingBase sb = (SettingBase) pkg.mExtras;
3491        PermissionsState permissionsState = sb.getPermissionsState();
3492
3493        if (permissionsState.grantInstallPermission(bp) !=
3494                PermissionsState.PERMISSION_OPERATION_FAILURE) {
3495            scheduleWriteSettingsLocked();
3496        }
3497    }
3498
3499    @Override
3500    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3501        mContext.enforceCallingOrSelfPermission(
3502                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
3503                "addOnPermissionsChangeListener");
3504
3505        synchronized (mPackages) {
3506            mOnPermissionChangeListeners.addListenerLocked(listener);
3507        }
3508    }
3509
3510    @Override
3511    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3512        synchronized (mPackages) {
3513            mOnPermissionChangeListeners.removeListenerLocked(listener);
3514        }
3515    }
3516
3517    @Override
3518    public boolean isProtectedBroadcast(String actionName) {
3519        synchronized (mPackages) {
3520            return mProtectedBroadcasts.contains(actionName);
3521        }
3522    }
3523
3524    @Override
3525    public int checkSignatures(String pkg1, String pkg2) {
3526        synchronized (mPackages) {
3527            final PackageParser.Package p1 = mPackages.get(pkg1);
3528            final PackageParser.Package p2 = mPackages.get(pkg2);
3529            if (p1 == null || p1.mExtras == null
3530                    || p2 == null || p2.mExtras == null) {
3531                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3532            }
3533            return compareSignatures(p1.mSignatures, p2.mSignatures);
3534        }
3535    }
3536
3537    @Override
3538    public int checkUidSignatures(int uid1, int uid2) {
3539        // Map to base uids.
3540        uid1 = UserHandle.getAppId(uid1);
3541        uid2 = UserHandle.getAppId(uid2);
3542        // reader
3543        synchronized (mPackages) {
3544            Signature[] s1;
3545            Signature[] s2;
3546            Object obj = mSettings.getUserIdLPr(uid1);
3547            if (obj != null) {
3548                if (obj instanceof SharedUserSetting) {
3549                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3550                } else if (obj instanceof PackageSetting) {
3551                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3552                } else {
3553                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3554                }
3555            } else {
3556                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3557            }
3558            obj = mSettings.getUserIdLPr(uid2);
3559            if (obj != null) {
3560                if (obj instanceof SharedUserSetting) {
3561                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3562                } else if (obj instanceof PackageSetting) {
3563                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3564                } else {
3565                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3566                }
3567            } else {
3568                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3569            }
3570            return compareSignatures(s1, s2);
3571        }
3572    }
3573
3574    private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) {
3575        final long identity = Binder.clearCallingIdentity();
3576        try {
3577            if (sb instanceof SharedUserSetting) {
3578                SharedUserSetting sus = (SharedUserSetting) sb;
3579                final int packageCount = sus.packages.size();
3580                for (int i = 0; i < packageCount; i++) {
3581                    PackageSetting susPs = sus.packages.valueAt(i);
3582                    if (userId == UserHandle.USER_ALL) {
3583                        killApplication(susPs.pkg.packageName, susPs.appId, reason);
3584                    } else {
3585                        final int uid = UserHandle.getUid(userId, susPs.appId);
3586                        killUid(uid, reason);
3587                    }
3588                }
3589            } else if (sb instanceof PackageSetting) {
3590                PackageSetting ps = (PackageSetting) sb;
3591                if (userId == UserHandle.USER_ALL) {
3592                    killApplication(ps.pkg.packageName, ps.appId, reason);
3593                } else {
3594                    final int uid = UserHandle.getUid(userId, ps.appId);
3595                    killUid(uid, reason);
3596                }
3597            }
3598        } finally {
3599            Binder.restoreCallingIdentity(identity);
3600        }
3601    }
3602
3603    private static void killUid(int uid, String reason) {
3604        IActivityManager am = ActivityManagerNative.getDefault();
3605        if (am != null) {
3606            try {
3607                am.killUid(uid, reason);
3608            } catch (RemoteException e) {
3609                /* ignore - same process */
3610            }
3611        }
3612    }
3613
3614    /**
3615     * Compares two sets of signatures. Returns:
3616     * <br />
3617     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3618     * <br />
3619     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3620     * <br />
3621     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3622     * <br />
3623     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3624     * <br />
3625     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3626     */
3627    static int compareSignatures(Signature[] s1, Signature[] s2) {
3628        if (s1 == null) {
3629            return s2 == null
3630                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3631                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3632        }
3633
3634        if (s2 == null) {
3635            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3636        }
3637
3638        if (s1.length != s2.length) {
3639            return PackageManager.SIGNATURE_NO_MATCH;
3640        }
3641
3642        // Since both signature sets are of size 1, we can compare without HashSets.
3643        if (s1.length == 1) {
3644            return s1[0].equals(s2[0]) ?
3645                    PackageManager.SIGNATURE_MATCH :
3646                    PackageManager.SIGNATURE_NO_MATCH;
3647        }
3648
3649        ArraySet<Signature> set1 = new ArraySet<Signature>();
3650        for (Signature sig : s1) {
3651            set1.add(sig);
3652        }
3653        ArraySet<Signature> set2 = new ArraySet<Signature>();
3654        for (Signature sig : s2) {
3655            set2.add(sig);
3656        }
3657        // Make sure s2 contains all signatures in s1.
3658        if (set1.equals(set2)) {
3659            return PackageManager.SIGNATURE_MATCH;
3660        }
3661        return PackageManager.SIGNATURE_NO_MATCH;
3662    }
3663
3664    /**
3665     * If the database version for this type of package (internal storage or
3666     * external storage) is less than the version where package signatures
3667     * were updated, return true.
3668     */
3669    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3670        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
3671                DatabaseVersion.SIGNATURE_END_ENTITY))
3672                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
3673                        DatabaseVersion.SIGNATURE_END_ENTITY));
3674    }
3675
3676    /**
3677     * Used for backward compatibility to make sure any packages with
3678     * certificate chains get upgraded to the new style. {@code existingSigs}
3679     * will be in the old format (since they were stored on disk from before the
3680     * system upgrade) and {@code scannedSigs} will be in the newer format.
3681     */
3682    private int compareSignaturesCompat(PackageSignatures existingSigs,
3683            PackageParser.Package scannedPkg) {
3684        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
3685            return PackageManager.SIGNATURE_NO_MATCH;
3686        }
3687
3688        ArraySet<Signature> existingSet = new ArraySet<Signature>();
3689        for (Signature sig : existingSigs.mSignatures) {
3690            existingSet.add(sig);
3691        }
3692        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
3693        for (Signature sig : scannedPkg.mSignatures) {
3694            try {
3695                Signature[] chainSignatures = sig.getChainSignatures();
3696                for (Signature chainSig : chainSignatures) {
3697                    scannedCompatSet.add(chainSig);
3698                }
3699            } catch (CertificateEncodingException e) {
3700                scannedCompatSet.add(sig);
3701            }
3702        }
3703        /*
3704         * Make sure the expanded scanned set contains all signatures in the
3705         * existing one.
3706         */
3707        if (scannedCompatSet.equals(existingSet)) {
3708            // Migrate the old signatures to the new scheme.
3709            existingSigs.assignSignatures(scannedPkg.mSignatures);
3710            // The new KeySets will be re-added later in the scanning process.
3711            synchronized (mPackages) {
3712                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
3713            }
3714            return PackageManager.SIGNATURE_MATCH;
3715        }
3716        return PackageManager.SIGNATURE_NO_MATCH;
3717    }
3718
3719    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3720        if (isExternal(scannedPkg)) {
3721            return mSettings.isExternalDatabaseVersionOlderThan(
3722                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3723        } else {
3724            return mSettings.isInternalDatabaseVersionOlderThan(
3725                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3726        }
3727    }
3728
3729    private int compareSignaturesRecover(PackageSignatures existingSigs,
3730            PackageParser.Package scannedPkg) {
3731        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
3732            return PackageManager.SIGNATURE_NO_MATCH;
3733        }
3734
3735        String msg = null;
3736        try {
3737            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
3738                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
3739                        + scannedPkg.packageName);
3740                return PackageManager.SIGNATURE_MATCH;
3741            }
3742        } catch (CertificateException e) {
3743            msg = e.getMessage();
3744        }
3745
3746        logCriticalInfo(Log.INFO,
3747                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
3748        return PackageManager.SIGNATURE_NO_MATCH;
3749    }
3750
3751    @Override
3752    public String[] getPackagesForUid(int uid) {
3753        uid = UserHandle.getAppId(uid);
3754        // reader
3755        synchronized (mPackages) {
3756            Object obj = mSettings.getUserIdLPr(uid);
3757            if (obj instanceof SharedUserSetting) {
3758                final SharedUserSetting sus = (SharedUserSetting) obj;
3759                final int N = sus.packages.size();
3760                final String[] res = new String[N];
3761                final Iterator<PackageSetting> it = sus.packages.iterator();
3762                int i = 0;
3763                while (it.hasNext()) {
3764                    res[i++] = it.next().name;
3765                }
3766                return res;
3767            } else if (obj instanceof PackageSetting) {
3768                final PackageSetting ps = (PackageSetting) obj;
3769                return new String[] { ps.name };
3770            }
3771        }
3772        return null;
3773    }
3774
3775    @Override
3776    public String getNameForUid(int uid) {
3777        // reader
3778        synchronized (mPackages) {
3779            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3780            if (obj instanceof SharedUserSetting) {
3781                final SharedUserSetting sus = (SharedUserSetting) obj;
3782                return sus.name + ":" + sus.userId;
3783            } else if (obj instanceof PackageSetting) {
3784                final PackageSetting ps = (PackageSetting) obj;
3785                return ps.name;
3786            }
3787        }
3788        return null;
3789    }
3790
3791    @Override
3792    public int getUidForSharedUser(String sharedUserName) {
3793        if(sharedUserName == null) {
3794            return -1;
3795        }
3796        // reader
3797        synchronized (mPackages) {
3798            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
3799            if (suid == null) {
3800                return -1;
3801            }
3802            return suid.userId;
3803        }
3804    }
3805
3806    @Override
3807    public int getFlagsForUid(int uid) {
3808        synchronized (mPackages) {
3809            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3810            if (obj instanceof SharedUserSetting) {
3811                final SharedUserSetting sus = (SharedUserSetting) obj;
3812                return sus.pkgFlags;
3813            } else if (obj instanceof PackageSetting) {
3814                final PackageSetting ps = (PackageSetting) obj;
3815                return ps.pkgFlags;
3816            }
3817        }
3818        return 0;
3819    }
3820
3821    @Override
3822    public int getPrivateFlagsForUid(int uid) {
3823        synchronized (mPackages) {
3824            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3825            if (obj instanceof SharedUserSetting) {
3826                final SharedUserSetting sus = (SharedUserSetting) obj;
3827                return sus.pkgPrivateFlags;
3828            } else if (obj instanceof PackageSetting) {
3829                final PackageSetting ps = (PackageSetting) obj;
3830                return ps.pkgPrivateFlags;
3831            }
3832        }
3833        return 0;
3834    }
3835
3836    @Override
3837    public boolean isUidPrivileged(int uid) {
3838        uid = UserHandle.getAppId(uid);
3839        // reader
3840        synchronized (mPackages) {
3841            Object obj = mSettings.getUserIdLPr(uid);
3842            if (obj instanceof SharedUserSetting) {
3843                final SharedUserSetting sus = (SharedUserSetting) obj;
3844                final Iterator<PackageSetting> it = sus.packages.iterator();
3845                while (it.hasNext()) {
3846                    if (it.next().isPrivileged()) {
3847                        return true;
3848                    }
3849                }
3850            } else if (obj instanceof PackageSetting) {
3851                final PackageSetting ps = (PackageSetting) obj;
3852                return ps.isPrivileged();
3853            }
3854        }
3855        return false;
3856    }
3857
3858    @Override
3859    public String[] getAppOpPermissionPackages(String permissionName) {
3860        synchronized (mPackages) {
3861            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
3862            if (pkgs == null) {
3863                return null;
3864            }
3865            return pkgs.toArray(new String[pkgs.size()]);
3866        }
3867    }
3868
3869    @Override
3870    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
3871            int flags, int userId) {
3872        if (!sUserManager.exists(userId)) return null;
3873        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
3874        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3875        return chooseBestActivity(intent, resolvedType, flags, query, userId);
3876    }
3877
3878    @Override
3879    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
3880            IntentFilter filter, int match, ComponentName activity) {
3881        final int userId = UserHandle.getCallingUserId();
3882        if (DEBUG_PREFERRED) {
3883            Log.v(TAG, "setLastChosenActivity intent=" + intent
3884                + " resolvedType=" + resolvedType
3885                + " flags=" + flags
3886                + " filter=" + filter
3887                + " match=" + match
3888                + " activity=" + activity);
3889            filter.dump(new PrintStreamPrinter(System.out), "    ");
3890        }
3891        intent.setComponent(null);
3892        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3893        // Find any earlier preferred or last chosen entries and nuke them
3894        findPreferredActivity(intent, resolvedType,
3895                flags, query, 0, false, true, false, userId);
3896        // Add the new activity as the last chosen for this filter
3897        addPreferredActivityInternal(filter, match, null, activity, false, userId,
3898                "Setting last chosen");
3899    }
3900
3901    @Override
3902    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
3903        final int userId = UserHandle.getCallingUserId();
3904        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
3905        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3906        return findPreferredActivity(intent, resolvedType, flags, query, 0,
3907                false, false, false, userId);
3908    }
3909
3910    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
3911            int flags, List<ResolveInfo> query, int userId) {
3912        if (query != null) {
3913            final int N = query.size();
3914            if (N == 1) {
3915                return query.get(0);
3916            } else if (N > 1) {
3917                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
3918                // If there is more than one activity with the same priority,
3919                // then let the user decide between them.
3920                ResolveInfo r0 = query.get(0);
3921                ResolveInfo r1 = query.get(1);
3922                if (DEBUG_INTENT_MATCHING || debug) {
3923                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
3924                            + r1.activityInfo.name + "=" + r1.priority);
3925                }
3926                // If the first activity has a higher priority, or a different
3927                // default, then it is always desireable to pick it.
3928                if (r0.priority != r1.priority
3929                        || r0.preferredOrder != r1.preferredOrder
3930                        || r0.isDefault != r1.isDefault) {
3931                    return query.get(0);
3932                }
3933                // If we have saved a preference for a preferred activity for
3934                // this Intent, use that.
3935                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
3936                        flags, query, r0.priority, true, false, debug, userId);
3937                if (ri != null) {
3938                    return ri;
3939                }
3940                if (userId != 0) {
3941                    ri = new ResolveInfo(mResolveInfo);
3942                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
3943                    ri.activityInfo.applicationInfo = new ApplicationInfo(
3944                            ri.activityInfo.applicationInfo);
3945                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
3946                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
3947                    return ri;
3948                }
3949                return mResolveInfo;
3950            }
3951        }
3952        return null;
3953    }
3954
3955    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
3956            int flags, List<ResolveInfo> query, boolean debug, int userId) {
3957        final int N = query.size();
3958        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
3959                .get(userId);
3960        // Get the list of persistent preferred activities that handle the intent
3961        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
3962        List<PersistentPreferredActivity> pprefs = ppir != null
3963                ? ppir.queryIntent(intent, resolvedType,
3964                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3965                : null;
3966        if (pprefs != null && pprefs.size() > 0) {
3967            final int M = pprefs.size();
3968            for (int i=0; i<M; i++) {
3969                final PersistentPreferredActivity ppa = pprefs.get(i);
3970                if (DEBUG_PREFERRED || debug) {
3971                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
3972                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
3973                            + "\n  component=" + ppa.mComponent);
3974                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3975                }
3976                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
3977                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3978                if (DEBUG_PREFERRED || debug) {
3979                    Slog.v(TAG, "Found persistent preferred activity:");
3980                    if (ai != null) {
3981                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3982                    } else {
3983                        Slog.v(TAG, "  null");
3984                    }
3985                }
3986                if (ai == null) {
3987                    // This previously registered persistent preferred activity
3988                    // component is no longer known. Ignore it and do NOT remove it.
3989                    continue;
3990                }
3991                for (int j=0; j<N; j++) {
3992                    final ResolveInfo ri = query.get(j);
3993                    if (!ri.activityInfo.applicationInfo.packageName
3994                            .equals(ai.applicationInfo.packageName)) {
3995                        continue;
3996                    }
3997                    if (!ri.activityInfo.name.equals(ai.name)) {
3998                        continue;
3999                    }
4000                    //  Found a persistent preference that can handle the intent.
4001                    if (DEBUG_PREFERRED || debug) {
4002                        Slog.v(TAG, "Returning persistent preferred activity: " +
4003                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4004                    }
4005                    return ri;
4006                }
4007            }
4008        }
4009        return null;
4010    }
4011
4012    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4013            List<ResolveInfo> query, int priority, boolean always,
4014            boolean removeMatches, boolean debug, int userId) {
4015        if (!sUserManager.exists(userId)) return null;
4016        // writer
4017        synchronized (mPackages) {
4018            if (intent.getSelector() != null) {
4019                intent = intent.getSelector();
4020            }
4021            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4022
4023            // Try to find a matching persistent preferred activity.
4024            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4025                    debug, userId);
4026
4027            // If a persistent preferred activity matched, use it.
4028            if (pri != null) {
4029                return pri;
4030            }
4031
4032            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4033            // Get the list of preferred activities that handle the intent
4034            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4035            List<PreferredActivity> prefs = pir != null
4036                    ? pir.queryIntent(intent, resolvedType,
4037                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4038                    : null;
4039            if (prefs != null && prefs.size() > 0) {
4040                boolean changed = false;
4041                try {
4042                    // First figure out how good the original match set is.
4043                    // We will only allow preferred activities that came
4044                    // from the same match quality.
4045                    int match = 0;
4046
4047                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4048
4049                    final int N = query.size();
4050                    for (int j=0; j<N; j++) {
4051                        final ResolveInfo ri = query.get(j);
4052                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4053                                + ": 0x" + Integer.toHexString(match));
4054                        if (ri.match > match) {
4055                            match = ri.match;
4056                        }
4057                    }
4058
4059                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4060                            + Integer.toHexString(match));
4061
4062                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4063                    final int M = prefs.size();
4064                    for (int i=0; i<M; i++) {
4065                        final PreferredActivity pa = prefs.get(i);
4066                        if (DEBUG_PREFERRED || debug) {
4067                            Slog.v(TAG, "Checking PreferredActivity ds="
4068                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4069                                    + "\n  component=" + pa.mPref.mComponent);
4070                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4071                        }
4072                        if (pa.mPref.mMatch != match) {
4073                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4074                                    + Integer.toHexString(pa.mPref.mMatch));
4075                            continue;
4076                        }
4077                        // If it's not an "always" type preferred activity and that's what we're
4078                        // looking for, skip it.
4079                        if (always && !pa.mPref.mAlways) {
4080                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4081                            continue;
4082                        }
4083                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4084                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4085                        if (DEBUG_PREFERRED || debug) {
4086                            Slog.v(TAG, "Found preferred activity:");
4087                            if (ai != null) {
4088                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4089                            } else {
4090                                Slog.v(TAG, "  null");
4091                            }
4092                        }
4093                        if (ai == null) {
4094                            // This previously registered preferred activity
4095                            // component is no longer known.  Most likely an update
4096                            // to the app was installed and in the new version this
4097                            // component no longer exists.  Clean it up by removing
4098                            // it from the preferred activities list, and skip it.
4099                            Slog.w(TAG, "Removing dangling preferred activity: "
4100                                    + pa.mPref.mComponent);
4101                            pir.removeFilter(pa);
4102                            changed = true;
4103                            continue;
4104                        }
4105                        for (int j=0; j<N; j++) {
4106                            final ResolveInfo ri = query.get(j);
4107                            if (!ri.activityInfo.applicationInfo.packageName
4108                                    .equals(ai.applicationInfo.packageName)) {
4109                                continue;
4110                            }
4111                            if (!ri.activityInfo.name.equals(ai.name)) {
4112                                continue;
4113                            }
4114
4115                            if (removeMatches) {
4116                                pir.removeFilter(pa);
4117                                changed = true;
4118                                if (DEBUG_PREFERRED) {
4119                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4120                                }
4121                                break;
4122                            }
4123
4124                            // Okay we found a previously set preferred or last chosen app.
4125                            // If the result set is different from when this
4126                            // was created, we need to clear it and re-ask the
4127                            // user their preference, if we're looking for an "always" type entry.
4128                            if (always && !pa.mPref.sameSet(query)) {
4129                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4130                                        + intent + " type " + resolvedType);
4131                                if (DEBUG_PREFERRED) {
4132                                    Slog.v(TAG, "Removing preferred activity since set changed "
4133                                            + pa.mPref.mComponent);
4134                                }
4135                                pir.removeFilter(pa);
4136                                // Re-add the filter as a "last chosen" entry (!always)
4137                                PreferredActivity lastChosen = new PreferredActivity(
4138                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4139                                pir.addFilter(lastChosen);
4140                                changed = true;
4141                                return null;
4142                            }
4143
4144                            // Yay! Either the set matched or we're looking for the last chosen
4145                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4146                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4147                            return ri;
4148                        }
4149                    }
4150                } finally {
4151                    if (changed) {
4152                        if (DEBUG_PREFERRED) {
4153                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4154                        }
4155                        scheduleWritePackageRestrictionsLocked(userId);
4156                    }
4157                }
4158            }
4159        }
4160        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4161        return null;
4162    }
4163
4164    /*
4165     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4166     */
4167    @Override
4168    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4169            int targetUserId) {
4170        mContext.enforceCallingOrSelfPermission(
4171                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4172        List<CrossProfileIntentFilter> matches =
4173                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4174        if (matches != null) {
4175            int size = matches.size();
4176            for (int i = 0; i < size; i++) {
4177                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4178            }
4179        }
4180        if (hasWebURI(intent)) {
4181            // cross-profile app linking works only towards the parent.
4182            final UserInfo parent = getProfileParent(sourceUserId);
4183            synchronized(mPackages) {
4184                return getCrossProfileDomainPreferredLpr(intent, resolvedType, 0, sourceUserId,
4185                        parent.id) != null;
4186            }
4187        }
4188        return false;
4189    }
4190
4191    private UserInfo getProfileParent(int userId) {
4192        final long identity = Binder.clearCallingIdentity();
4193        try {
4194            return sUserManager.getProfileParent(userId);
4195        } finally {
4196            Binder.restoreCallingIdentity(identity);
4197        }
4198    }
4199
4200    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4201            String resolvedType, int userId) {
4202        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4203        if (resolver != null) {
4204            return resolver.queryIntent(intent, resolvedType, false, userId);
4205        }
4206        return null;
4207    }
4208
4209    @Override
4210    public List<ResolveInfo> queryIntentActivities(Intent intent,
4211            String resolvedType, int flags, int userId) {
4212        if (!sUserManager.exists(userId)) return Collections.emptyList();
4213        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4214        ComponentName comp = intent.getComponent();
4215        if (comp == null) {
4216            if (intent.getSelector() != null) {
4217                intent = intent.getSelector();
4218                comp = intent.getComponent();
4219            }
4220        }
4221
4222        if (comp != null) {
4223            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4224            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4225            if (ai != null) {
4226                final ResolveInfo ri = new ResolveInfo();
4227                ri.activityInfo = ai;
4228                list.add(ri);
4229            }
4230            return list;
4231        }
4232
4233        // reader
4234        synchronized (mPackages) {
4235            final String pkgName = intent.getPackage();
4236            if (pkgName == null) {
4237                List<CrossProfileIntentFilter> matchingFilters =
4238                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4239                // Check for results that need to skip the current profile.
4240                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4241                        resolvedType, flags, userId);
4242                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4243                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4244                    result.add(xpResolveInfo);
4245                    return filterIfNotPrimaryUser(result, userId);
4246                }
4247
4248                // Check for results in the current profile.
4249                List<ResolveInfo> result = mActivities.queryIntent(
4250                        intent, resolvedType, flags, userId);
4251
4252                // Check for cross profile results.
4253                xpResolveInfo = queryCrossProfileIntents(
4254                        matchingFilters, intent, resolvedType, flags, userId);
4255                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4256                    result.add(xpResolveInfo);
4257                    Collections.sort(result, mResolvePrioritySorter);
4258                }
4259                result = filterIfNotPrimaryUser(result, userId);
4260                if (hasWebURI(intent)) {
4261                    CrossProfileDomainInfo xpDomainInfo = null;
4262                    final UserInfo parent = getProfileParent(userId);
4263                    if (parent != null) {
4264                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4265                                flags, userId, parent.id);
4266                    }
4267                    if (xpDomainInfo != null) {
4268                        if (xpResolveInfo != null) {
4269                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4270                            // in the result.
4271                            result.remove(xpResolveInfo);
4272                        }
4273                        if (result.size() == 0) {
4274                            result.add(xpDomainInfo.resolveInfo);
4275                            return result;
4276                        }
4277                    } else if (result.size() <= 1) {
4278                        return result;
4279                    }
4280                    result = filterCandidatesWithDomainPreferredActivitiesLPr(flags, result,
4281                            xpDomainInfo);
4282                    Collections.sort(result, mResolvePrioritySorter);
4283                }
4284                return result;
4285            }
4286            final PackageParser.Package pkg = mPackages.get(pkgName);
4287            if (pkg != null) {
4288                return filterIfNotPrimaryUser(
4289                        mActivities.queryIntentForPackage(
4290                                intent, resolvedType, flags, pkg.activities, userId),
4291                        userId);
4292            }
4293            return new ArrayList<ResolveInfo>();
4294        }
4295    }
4296
4297    private static class CrossProfileDomainInfo {
4298        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4299        ResolveInfo resolveInfo;
4300        /* Best domain verification status of the activities found in the other profile */
4301        int bestDomainVerificationStatus;
4302    }
4303
4304    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4305            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4306        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_APP_LINKING,
4307                sourceUserId)) {
4308            return null;
4309        }
4310        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4311                resolvedType, flags, parentUserId);
4312
4313        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4314            return null;
4315        }
4316        CrossProfileDomainInfo result = null;
4317        int size = resultTargetUser.size();
4318        for (int i = 0; i < size; i++) {
4319            ResolveInfo riTargetUser = resultTargetUser.get(i);
4320            // Intent filter verification is only for filters that specify a host. So don't return
4321            // those that handle all web uris.
4322            if (riTargetUser.handleAllWebDataURI) {
4323                continue;
4324            }
4325            String packageName = riTargetUser.activityInfo.packageName;
4326            PackageSetting ps = mSettings.mPackages.get(packageName);
4327            if (ps == null) {
4328                continue;
4329            }
4330            int status = getDomainVerificationStatusLPr(ps, parentUserId);
4331            if (result == null) {
4332                result = new CrossProfileDomainInfo();
4333                result.resolveInfo =
4334                        createForwardingResolveInfo(null, sourceUserId, parentUserId);
4335                result.bestDomainVerificationStatus = status;
4336            } else {
4337                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
4338                        result.bestDomainVerificationStatus);
4339            }
4340        }
4341        return result;
4342    }
4343
4344    /**
4345     * Verification statuses are ordered from the worse to the best, except for
4346     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
4347     */
4348    private int bestDomainVerificationStatus(int status1, int status2) {
4349        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4350            return status2;
4351        }
4352        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4353            return status1;
4354        }
4355        return (int) MathUtils.max(status1, status2);
4356    }
4357
4358    private boolean isUserEnabled(int userId) {
4359        long callingId = Binder.clearCallingIdentity();
4360        try {
4361            UserInfo userInfo = sUserManager.getUserInfo(userId);
4362            return userInfo != null && userInfo.isEnabled();
4363        } finally {
4364            Binder.restoreCallingIdentity(callingId);
4365        }
4366    }
4367
4368    /**
4369     * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
4370     *
4371     * @return filtered list
4372     */
4373    private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
4374        if (userId == UserHandle.USER_OWNER) {
4375            return resolveInfos;
4376        }
4377        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4378            ResolveInfo info = resolveInfos.get(i);
4379            if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
4380                resolveInfos.remove(i);
4381            }
4382        }
4383        return resolveInfos;
4384    }
4385
4386    private static boolean hasWebURI(Intent intent) {
4387        if (intent.getData() == null) {
4388            return false;
4389        }
4390        final String scheme = intent.getScheme();
4391        if (TextUtils.isEmpty(scheme)) {
4392            return false;
4393        }
4394        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4395    }
4396
4397    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(
4398            int flags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo) {
4399        if (DEBUG_PREFERRED) {
4400            Slog.v("TAG", "Filtering results with prefered activities. Candidates count: " +
4401                    candidates.size());
4402        }
4403
4404        final int userId = UserHandle.getCallingUserId();
4405        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4406        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
4407        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4408        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4409        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4410
4411        synchronized (mPackages) {
4412            final int count = candidates.size();
4413            // First, try to use the domain prefered App. Partition the candidates into four lists:
4414            // one for the final results, one for the "do not use ever", one for "undefined status"
4415            // and finally one for "Browser App type".
4416            for (int n=0; n<count; n++) {
4417                ResolveInfo info = candidates.get(n);
4418                String packageName = info.activityInfo.packageName;
4419                PackageSetting ps = mSettings.mPackages.get(packageName);
4420                if (ps != null) {
4421                    // Add to the special match all list (Browser use case)
4422                    if (info.handleAllWebDataURI) {
4423                        matchAllList.add(info);
4424                        continue;
4425                    }
4426                    // Try to get the status from User settings first
4427                    int status = getDomainVerificationStatusLPr(ps, userId);
4428                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4429                        alwaysList.add(info);
4430                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4431                        neverList.add(info);
4432                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
4433                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
4434                        undefinedList.add(info);
4435                    }
4436                }
4437            }
4438            // First try to add the "always" resolution for the current user if there is any
4439            if (alwaysList.size() > 0) {
4440                result.addAll(alwaysList);
4441            // if there is an "always" for the parent user, add it.
4442            } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus
4443                    == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4444                result.add(xpDomainInfo.resolveInfo);
4445            } else {
4446                // Add all undefined Apps as we want them to appear in the Disambiguation dialog.
4447                result.addAll(undefinedList);
4448                if (xpDomainInfo != null && (
4449                        xpDomainInfo.bestDomainVerificationStatus
4450                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
4451                        || xpDomainInfo.bestDomainVerificationStatus
4452                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) {
4453                    result.add(xpDomainInfo.resolveInfo);
4454                }
4455                // Also add Browsers (all of them or only the default one)
4456                if ((flags & MATCH_ALL) != 0) {
4457                    result.addAll(matchAllList);
4458                } else {
4459                    // Try to add the Default Browser if we can
4460                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(
4461                            UserHandle.myUserId());
4462                    if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
4463                        boolean defaultBrowserFound = false;
4464                        final int browserCount = matchAllList.size();
4465                        for (int n=0; n<browserCount; n++) {
4466                            ResolveInfo browser = matchAllList.get(n);
4467                            if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) {
4468                                result.add(browser);
4469                                defaultBrowserFound = true;
4470                                break;
4471                            }
4472                        }
4473                        if (!defaultBrowserFound) {
4474                            result.addAll(matchAllList);
4475                        }
4476                    } else {
4477                        result.addAll(matchAllList);
4478                    }
4479                }
4480
4481                // If there is nothing selected, add all candidates and remove the ones that the User
4482                // has explicitely put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
4483                if (result.size() == 0) {
4484                    result.addAll(candidates);
4485                    result.removeAll(neverList);
4486                }
4487            }
4488        }
4489        if (DEBUG_PREFERRED) {
4490            Slog.v("TAG", "Filtered results with prefered activities. New candidates count: " +
4491                    result.size());
4492        }
4493        return result;
4494    }
4495
4496    private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4497        int status = ps.getDomainVerificationStatusForUser(userId);
4498        // if none available, get the master status
4499        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4500            if (ps.getIntentFilterVerificationInfo() != null) {
4501                status = ps.getIntentFilterVerificationInfo().getStatus();
4502            }
4503        }
4504        return status;
4505    }
4506
4507    private ResolveInfo querySkipCurrentProfileIntents(
4508            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4509            int flags, int sourceUserId) {
4510        if (matchingFilters != null) {
4511            int size = matchingFilters.size();
4512            for (int i = 0; i < size; i ++) {
4513                CrossProfileIntentFilter filter = matchingFilters.get(i);
4514                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4515                    // Checking if there are activities in the target user that can handle the
4516                    // intent.
4517                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4518                            flags, sourceUserId);
4519                    if (resolveInfo != null) {
4520                        return resolveInfo;
4521                    }
4522                }
4523            }
4524        }
4525        return null;
4526    }
4527
4528    // Return matching ResolveInfo if any for skip current profile intent filters.
4529    private ResolveInfo queryCrossProfileIntents(
4530            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4531            int flags, int sourceUserId) {
4532        if (matchingFilters != null) {
4533            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4534            // match the same intent. For performance reasons, it is better not to
4535            // run queryIntent twice for the same userId
4536            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4537            int size = matchingFilters.size();
4538            for (int i = 0; i < size; i++) {
4539                CrossProfileIntentFilter filter = matchingFilters.get(i);
4540                int targetUserId = filter.getTargetUserId();
4541                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4542                        && !alreadyTriedUserIds.get(targetUserId)) {
4543                    // Checking if there are activities in the target user that can handle the
4544                    // intent.
4545                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4546                            flags, sourceUserId);
4547                    if (resolveInfo != null) return resolveInfo;
4548                    alreadyTriedUserIds.put(targetUserId, true);
4549                }
4550            }
4551        }
4552        return null;
4553    }
4554
4555    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
4556            String resolvedType, int flags, int sourceUserId) {
4557        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4558                resolvedType, flags, filter.getTargetUserId());
4559        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
4560            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
4561        }
4562        return null;
4563    }
4564
4565    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
4566            int sourceUserId, int targetUserId) {
4567        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4568        String className;
4569        if (targetUserId == UserHandle.USER_OWNER) {
4570            className = FORWARD_INTENT_TO_USER_OWNER;
4571        } else {
4572            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4573        }
4574        ComponentName forwardingActivityComponentName = new ComponentName(
4575                mAndroidApplication.packageName, className);
4576        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
4577                sourceUserId);
4578        if (targetUserId == UserHandle.USER_OWNER) {
4579            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
4580            forwardingResolveInfo.noResourceId = true;
4581        }
4582        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
4583        forwardingResolveInfo.priority = 0;
4584        forwardingResolveInfo.preferredOrder = 0;
4585        forwardingResolveInfo.match = 0;
4586        forwardingResolveInfo.isDefault = true;
4587        forwardingResolveInfo.filter = filter;
4588        forwardingResolveInfo.targetUserId = targetUserId;
4589        return forwardingResolveInfo;
4590    }
4591
4592    @Override
4593    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
4594            Intent[] specifics, String[] specificTypes, Intent intent,
4595            String resolvedType, int flags, int userId) {
4596        if (!sUserManager.exists(userId)) return Collections.emptyList();
4597        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
4598                false, "query intent activity options");
4599        final String resultsAction = intent.getAction();
4600
4601        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
4602                | PackageManager.GET_RESOLVED_FILTER, userId);
4603
4604        if (DEBUG_INTENT_MATCHING) {
4605            Log.v(TAG, "Query " + intent + ": " + results);
4606        }
4607
4608        int specificsPos = 0;
4609        int N;
4610
4611        // todo: note that the algorithm used here is O(N^2).  This
4612        // isn't a problem in our current environment, but if we start running
4613        // into situations where we have more than 5 or 10 matches then this
4614        // should probably be changed to something smarter...
4615
4616        // First we go through and resolve each of the specific items
4617        // that were supplied, taking care of removing any corresponding
4618        // duplicate items in the generic resolve list.
4619        if (specifics != null) {
4620            for (int i=0; i<specifics.length; i++) {
4621                final Intent sintent = specifics[i];
4622                if (sintent == null) {
4623                    continue;
4624                }
4625
4626                if (DEBUG_INTENT_MATCHING) {
4627                    Log.v(TAG, "Specific #" + i + ": " + sintent);
4628                }
4629
4630                String action = sintent.getAction();
4631                if (resultsAction != null && resultsAction.equals(action)) {
4632                    // If this action was explicitly requested, then don't
4633                    // remove things that have it.
4634                    action = null;
4635                }
4636
4637                ResolveInfo ri = null;
4638                ActivityInfo ai = null;
4639
4640                ComponentName comp = sintent.getComponent();
4641                if (comp == null) {
4642                    ri = resolveIntent(
4643                        sintent,
4644                        specificTypes != null ? specificTypes[i] : null,
4645                            flags, userId);
4646                    if (ri == null) {
4647                        continue;
4648                    }
4649                    if (ri == mResolveInfo) {
4650                        // ACK!  Must do something better with this.
4651                    }
4652                    ai = ri.activityInfo;
4653                    comp = new ComponentName(ai.applicationInfo.packageName,
4654                            ai.name);
4655                } else {
4656                    ai = getActivityInfo(comp, flags, userId);
4657                    if (ai == null) {
4658                        continue;
4659                    }
4660                }
4661
4662                // Look for any generic query activities that are duplicates
4663                // of this specific one, and remove them from the results.
4664                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
4665                N = results.size();
4666                int j;
4667                for (j=specificsPos; j<N; j++) {
4668                    ResolveInfo sri = results.get(j);
4669                    if ((sri.activityInfo.name.equals(comp.getClassName())
4670                            && sri.activityInfo.applicationInfo.packageName.equals(
4671                                    comp.getPackageName()))
4672                        || (action != null && sri.filter.matchAction(action))) {
4673                        results.remove(j);
4674                        if (DEBUG_INTENT_MATCHING) Log.v(
4675                            TAG, "Removing duplicate item from " + j
4676                            + " due to specific " + specificsPos);
4677                        if (ri == null) {
4678                            ri = sri;
4679                        }
4680                        j--;
4681                        N--;
4682                    }
4683                }
4684
4685                // Add this specific item to its proper place.
4686                if (ri == null) {
4687                    ri = new ResolveInfo();
4688                    ri.activityInfo = ai;
4689                }
4690                results.add(specificsPos, ri);
4691                ri.specificIndex = i;
4692                specificsPos++;
4693            }
4694        }
4695
4696        // Now we go through the remaining generic results and remove any
4697        // duplicate actions that are found here.
4698        N = results.size();
4699        for (int i=specificsPos; i<N-1; i++) {
4700            final ResolveInfo rii = results.get(i);
4701            if (rii.filter == null) {
4702                continue;
4703            }
4704
4705            // Iterate over all of the actions of this result's intent
4706            // filter...  typically this should be just one.
4707            final Iterator<String> it = rii.filter.actionsIterator();
4708            if (it == null) {
4709                continue;
4710            }
4711            while (it.hasNext()) {
4712                final String action = it.next();
4713                if (resultsAction != null && resultsAction.equals(action)) {
4714                    // If this action was explicitly requested, then don't
4715                    // remove things that have it.
4716                    continue;
4717                }
4718                for (int j=i+1; j<N; j++) {
4719                    final ResolveInfo rij = results.get(j);
4720                    if (rij.filter != null && rij.filter.hasAction(action)) {
4721                        results.remove(j);
4722                        if (DEBUG_INTENT_MATCHING) Log.v(
4723                            TAG, "Removing duplicate item from " + j
4724                            + " due to action " + action + " at " + i);
4725                        j--;
4726                        N--;
4727                    }
4728                }
4729            }
4730
4731            // If the caller didn't request filter information, drop it now
4732            // so we don't have to marshall/unmarshall it.
4733            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4734                rii.filter = null;
4735            }
4736        }
4737
4738        // Filter out the caller activity if so requested.
4739        if (caller != null) {
4740            N = results.size();
4741            for (int i=0; i<N; i++) {
4742                ActivityInfo ainfo = results.get(i).activityInfo;
4743                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
4744                        && caller.getClassName().equals(ainfo.name)) {
4745                    results.remove(i);
4746                    break;
4747                }
4748            }
4749        }
4750
4751        // If the caller didn't request filter information,
4752        // drop them now so we don't have to
4753        // marshall/unmarshall it.
4754        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4755            N = results.size();
4756            for (int i=0; i<N; i++) {
4757                results.get(i).filter = null;
4758            }
4759        }
4760
4761        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
4762        return results;
4763    }
4764
4765    @Override
4766    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
4767            int userId) {
4768        if (!sUserManager.exists(userId)) return Collections.emptyList();
4769        ComponentName comp = intent.getComponent();
4770        if (comp == null) {
4771            if (intent.getSelector() != null) {
4772                intent = intent.getSelector();
4773                comp = intent.getComponent();
4774            }
4775        }
4776        if (comp != null) {
4777            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4778            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
4779            if (ai != null) {
4780                ResolveInfo ri = new ResolveInfo();
4781                ri.activityInfo = ai;
4782                list.add(ri);
4783            }
4784            return list;
4785        }
4786
4787        // reader
4788        synchronized (mPackages) {
4789            String pkgName = intent.getPackage();
4790            if (pkgName == null) {
4791                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
4792            }
4793            final PackageParser.Package pkg = mPackages.get(pkgName);
4794            if (pkg != null) {
4795                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
4796                        userId);
4797            }
4798            return null;
4799        }
4800    }
4801
4802    @Override
4803    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
4804        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
4805        if (!sUserManager.exists(userId)) return null;
4806        if (query != null) {
4807            if (query.size() >= 1) {
4808                // If there is more than one service with the same priority,
4809                // just arbitrarily pick the first one.
4810                return query.get(0);
4811            }
4812        }
4813        return null;
4814    }
4815
4816    @Override
4817    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
4818            int userId) {
4819        if (!sUserManager.exists(userId)) return Collections.emptyList();
4820        ComponentName comp = intent.getComponent();
4821        if (comp == null) {
4822            if (intent.getSelector() != null) {
4823                intent = intent.getSelector();
4824                comp = intent.getComponent();
4825            }
4826        }
4827        if (comp != null) {
4828            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4829            final ServiceInfo si = getServiceInfo(comp, flags, userId);
4830            if (si != null) {
4831                final ResolveInfo ri = new ResolveInfo();
4832                ri.serviceInfo = si;
4833                list.add(ri);
4834            }
4835            return list;
4836        }
4837
4838        // reader
4839        synchronized (mPackages) {
4840            String pkgName = intent.getPackage();
4841            if (pkgName == null) {
4842                return mServices.queryIntent(intent, resolvedType, flags, userId);
4843            }
4844            final PackageParser.Package pkg = mPackages.get(pkgName);
4845            if (pkg != null) {
4846                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
4847                        userId);
4848            }
4849            return null;
4850        }
4851    }
4852
4853    @Override
4854    public List<ResolveInfo> queryIntentContentProviders(
4855            Intent intent, String resolvedType, int flags, int userId) {
4856        if (!sUserManager.exists(userId)) return Collections.emptyList();
4857        ComponentName comp = intent.getComponent();
4858        if (comp == null) {
4859            if (intent.getSelector() != null) {
4860                intent = intent.getSelector();
4861                comp = intent.getComponent();
4862            }
4863        }
4864        if (comp != null) {
4865            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4866            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
4867            if (pi != null) {
4868                final ResolveInfo ri = new ResolveInfo();
4869                ri.providerInfo = pi;
4870                list.add(ri);
4871            }
4872            return list;
4873        }
4874
4875        // reader
4876        synchronized (mPackages) {
4877            String pkgName = intent.getPackage();
4878            if (pkgName == null) {
4879                return mProviders.queryIntent(intent, resolvedType, flags, userId);
4880            }
4881            final PackageParser.Package pkg = mPackages.get(pkgName);
4882            if (pkg != null) {
4883                return mProviders.queryIntentForPackage(
4884                        intent, resolvedType, flags, pkg.providers, userId);
4885            }
4886            return null;
4887        }
4888    }
4889
4890    @Override
4891    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
4892        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4893
4894        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
4895
4896        // writer
4897        synchronized (mPackages) {
4898            ArrayList<PackageInfo> list;
4899            if (listUninstalled) {
4900                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
4901                for (PackageSetting ps : mSettings.mPackages.values()) {
4902                    PackageInfo pi;
4903                    if (ps.pkg != null) {
4904                        pi = generatePackageInfo(ps.pkg, flags, userId);
4905                    } else {
4906                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
4907                    }
4908                    if (pi != null) {
4909                        list.add(pi);
4910                    }
4911                }
4912            } else {
4913                list = new ArrayList<PackageInfo>(mPackages.size());
4914                for (PackageParser.Package p : mPackages.values()) {
4915                    PackageInfo pi = generatePackageInfo(p, flags, userId);
4916                    if (pi != null) {
4917                        list.add(pi);
4918                    }
4919                }
4920            }
4921
4922            return new ParceledListSlice<PackageInfo>(list);
4923        }
4924    }
4925
4926    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
4927            String[] permissions, boolean[] tmp, int flags, int userId) {
4928        int numMatch = 0;
4929        final PermissionsState permissionsState = ps.getPermissionsState();
4930        for (int i=0; i<permissions.length; i++) {
4931            final String permission = permissions[i];
4932            if (permissionsState.hasPermission(permission, userId)) {
4933                tmp[i] = true;
4934                numMatch++;
4935            } else {
4936                tmp[i] = false;
4937            }
4938        }
4939        if (numMatch == 0) {
4940            return;
4941        }
4942        PackageInfo pi;
4943        if (ps.pkg != null) {
4944            pi = generatePackageInfo(ps.pkg, flags, userId);
4945        } else {
4946            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
4947        }
4948        // The above might return null in cases of uninstalled apps or install-state
4949        // skew across users/profiles.
4950        if (pi != null) {
4951            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
4952                if (numMatch == permissions.length) {
4953                    pi.requestedPermissions = permissions;
4954                } else {
4955                    pi.requestedPermissions = new String[numMatch];
4956                    numMatch = 0;
4957                    for (int i=0; i<permissions.length; i++) {
4958                        if (tmp[i]) {
4959                            pi.requestedPermissions[numMatch] = permissions[i];
4960                            numMatch++;
4961                        }
4962                    }
4963                }
4964            }
4965            list.add(pi);
4966        }
4967    }
4968
4969    @Override
4970    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
4971            String[] permissions, int flags, int userId) {
4972        if (!sUserManager.exists(userId)) return null;
4973        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4974
4975        // writer
4976        synchronized (mPackages) {
4977            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
4978            boolean[] tmpBools = new boolean[permissions.length];
4979            if (listUninstalled) {
4980                for (PackageSetting ps : mSettings.mPackages.values()) {
4981                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
4982                }
4983            } else {
4984                for (PackageParser.Package pkg : mPackages.values()) {
4985                    PackageSetting ps = (PackageSetting)pkg.mExtras;
4986                    if (ps != null) {
4987                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
4988                                userId);
4989                    }
4990                }
4991            }
4992
4993            return new ParceledListSlice<PackageInfo>(list);
4994        }
4995    }
4996
4997    @Override
4998    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
4999        if (!sUserManager.exists(userId)) return null;
5000        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5001
5002        // writer
5003        synchronized (mPackages) {
5004            ArrayList<ApplicationInfo> list;
5005            if (listUninstalled) {
5006                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5007                for (PackageSetting ps : mSettings.mPackages.values()) {
5008                    ApplicationInfo ai;
5009                    if (ps.pkg != null) {
5010                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5011                                ps.readUserState(userId), userId);
5012                    } else {
5013                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5014                    }
5015                    if (ai != null) {
5016                        list.add(ai);
5017                    }
5018                }
5019            } else {
5020                list = new ArrayList<ApplicationInfo>(mPackages.size());
5021                for (PackageParser.Package p : mPackages.values()) {
5022                    if (p.mExtras != null) {
5023                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5024                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5025                        if (ai != null) {
5026                            list.add(ai);
5027                        }
5028                    }
5029                }
5030            }
5031
5032            return new ParceledListSlice<ApplicationInfo>(list);
5033        }
5034    }
5035
5036    public List<ApplicationInfo> getPersistentApplications(int flags) {
5037        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5038
5039        // reader
5040        synchronized (mPackages) {
5041            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5042            final int userId = UserHandle.getCallingUserId();
5043            while (i.hasNext()) {
5044                final PackageParser.Package p = i.next();
5045                if (p.applicationInfo != null
5046                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5047                        && (!mSafeMode || isSystemApp(p))) {
5048                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5049                    if (ps != null) {
5050                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5051                                ps.readUserState(userId), userId);
5052                        if (ai != null) {
5053                            finalList.add(ai);
5054                        }
5055                    }
5056                }
5057            }
5058        }
5059
5060        return finalList;
5061    }
5062
5063    @Override
5064    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5065        if (!sUserManager.exists(userId)) return null;
5066        // reader
5067        synchronized (mPackages) {
5068            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5069            PackageSetting ps = provider != null
5070                    ? mSettings.mPackages.get(provider.owner.packageName)
5071                    : null;
5072            return ps != null
5073                    && mSettings.isEnabledLPr(provider.info, flags, userId)
5074                    && (!mSafeMode || (provider.info.applicationInfo.flags
5075                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5076                    ? PackageParser.generateProviderInfo(provider, flags,
5077                            ps.readUserState(userId), userId)
5078                    : null;
5079        }
5080    }
5081
5082    /**
5083     * @deprecated
5084     */
5085    @Deprecated
5086    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5087        // reader
5088        synchronized (mPackages) {
5089            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5090                    .entrySet().iterator();
5091            final int userId = UserHandle.getCallingUserId();
5092            while (i.hasNext()) {
5093                Map.Entry<String, PackageParser.Provider> entry = i.next();
5094                PackageParser.Provider p = entry.getValue();
5095                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5096
5097                if (ps != null && p.syncable
5098                        && (!mSafeMode || (p.info.applicationInfo.flags
5099                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5100                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5101                            ps.readUserState(userId), userId);
5102                    if (info != null) {
5103                        outNames.add(entry.getKey());
5104                        outInfo.add(info);
5105                    }
5106                }
5107            }
5108        }
5109    }
5110
5111    @Override
5112    public List<ProviderInfo> queryContentProviders(String processName,
5113            int uid, int flags) {
5114        ArrayList<ProviderInfo> finalList = null;
5115        // reader
5116        synchronized (mPackages) {
5117            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5118            final int userId = processName != null ?
5119                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
5120            while (i.hasNext()) {
5121                final PackageParser.Provider p = i.next();
5122                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5123                if (ps != null && p.info.authority != null
5124                        && (processName == null
5125                                || (p.info.processName.equals(processName)
5126                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5127                        && mSettings.isEnabledLPr(p.info, flags, userId)
5128                        && (!mSafeMode
5129                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5130                    if (finalList == null) {
5131                        finalList = new ArrayList<ProviderInfo>(3);
5132                    }
5133                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5134                            ps.readUserState(userId), userId);
5135                    if (info != null) {
5136                        finalList.add(info);
5137                    }
5138                }
5139            }
5140        }
5141
5142        if (finalList != null) {
5143            Collections.sort(finalList, mProviderInitOrderSorter);
5144        }
5145
5146        return finalList;
5147    }
5148
5149    @Override
5150    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
5151            int flags) {
5152        // reader
5153        synchronized (mPackages) {
5154            final PackageParser.Instrumentation i = mInstrumentation.get(name);
5155            return PackageParser.generateInstrumentationInfo(i, flags);
5156        }
5157    }
5158
5159    @Override
5160    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
5161            int flags) {
5162        ArrayList<InstrumentationInfo> finalList =
5163            new ArrayList<InstrumentationInfo>();
5164
5165        // reader
5166        synchronized (mPackages) {
5167            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
5168            while (i.hasNext()) {
5169                final PackageParser.Instrumentation p = i.next();
5170                if (targetPackage == null
5171                        || targetPackage.equals(p.info.targetPackage)) {
5172                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
5173                            flags);
5174                    if (ii != null) {
5175                        finalList.add(ii);
5176                    }
5177                }
5178            }
5179        }
5180
5181        return finalList;
5182    }
5183
5184    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
5185        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
5186        if (overlays == null) {
5187            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
5188            return;
5189        }
5190        for (PackageParser.Package opkg : overlays.values()) {
5191            // Not much to do if idmap fails: we already logged the error
5192            // and we certainly don't want to abort installation of pkg simply
5193            // because an overlay didn't fit properly. For these reasons,
5194            // ignore the return value of createIdmapForPackagePairLI.
5195            createIdmapForPackagePairLI(pkg, opkg);
5196        }
5197    }
5198
5199    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
5200            PackageParser.Package opkg) {
5201        if (!opkg.mTrustedOverlay) {
5202            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
5203                    opkg.baseCodePath + ": overlay not trusted");
5204            return false;
5205        }
5206        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
5207        if (overlaySet == null) {
5208            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
5209                    opkg.baseCodePath + " but target package has no known overlays");
5210            return false;
5211        }
5212        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
5213        // TODO: generate idmap for split APKs
5214        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
5215            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
5216                    + opkg.baseCodePath);
5217            return false;
5218        }
5219        PackageParser.Package[] overlayArray =
5220            overlaySet.values().toArray(new PackageParser.Package[0]);
5221        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
5222            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
5223                return p1.mOverlayPriority - p2.mOverlayPriority;
5224            }
5225        };
5226        Arrays.sort(overlayArray, cmp);
5227
5228        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5229        int i = 0;
5230        for (PackageParser.Package p : overlayArray) {
5231            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5232        }
5233        return true;
5234    }
5235
5236    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5237        final File[] files = dir.listFiles();
5238        if (ArrayUtils.isEmpty(files)) {
5239            Log.d(TAG, "No files in app dir " + dir);
5240            return;
5241        }
5242
5243        if (DEBUG_PACKAGE_SCANNING) {
5244            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
5245                    + " flags=0x" + Integer.toHexString(parseFlags));
5246        }
5247
5248        for (File file : files) {
5249            final boolean isPackage = (isApkFile(file) || file.isDirectory())
5250                    && !PackageInstallerService.isStageName(file.getName());
5251            if (!isPackage) {
5252                // Ignore entries which are not packages
5253                continue;
5254            }
5255            try {
5256                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
5257                        scanFlags, currentTime, null);
5258            } catch (PackageManagerException e) {
5259                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
5260
5261                // Delete invalid userdata apps
5262                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
5263                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
5264                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
5265                    if (file.isDirectory()) {
5266                        mInstaller.rmPackageDir(file.getAbsolutePath());
5267                    } else {
5268                        file.delete();
5269                    }
5270                }
5271            }
5272        }
5273    }
5274
5275    private static File getSettingsProblemFile() {
5276        File dataDir = Environment.getDataDirectory();
5277        File systemDir = new File(dataDir, "system");
5278        File fname = new File(systemDir, "uiderrors.txt");
5279        return fname;
5280    }
5281
5282    static void reportSettingsProblem(int priority, String msg) {
5283        logCriticalInfo(priority, msg);
5284    }
5285
5286    static void logCriticalInfo(int priority, String msg) {
5287        Slog.println(priority, TAG, msg);
5288        EventLogTags.writePmCriticalInfo(msg);
5289        try {
5290            File fname = getSettingsProblemFile();
5291            FileOutputStream out = new FileOutputStream(fname, true);
5292            PrintWriter pw = new FastPrintWriter(out);
5293            SimpleDateFormat formatter = new SimpleDateFormat();
5294            String dateString = formatter.format(new Date(System.currentTimeMillis()));
5295            pw.println(dateString + ": " + msg);
5296            pw.close();
5297            FileUtils.setPermissions(
5298                    fname.toString(),
5299                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5300                    -1, -1);
5301        } catch (java.io.IOException e) {
5302        }
5303    }
5304
5305    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5306            PackageParser.Package pkg, File srcFile, int parseFlags)
5307            throws PackageManagerException {
5308        if (ps != null
5309                && ps.codePath.equals(srcFile)
5310                && ps.timeStamp == srcFile.lastModified()
5311                && !isCompatSignatureUpdateNeeded(pkg)
5312                && !isRecoverSignatureUpdateNeeded(pkg)) {
5313            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5314            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5315            ArraySet<PublicKey> signingKs;
5316            synchronized (mPackages) {
5317                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
5318            }
5319            if (ps.signatures.mSignatures != null
5320                    && ps.signatures.mSignatures.length != 0
5321                    && signingKs != null) {
5322                // Optimization: reuse the existing cached certificates
5323                // if the package appears to be unchanged.
5324                pkg.mSignatures = ps.signatures.mSignatures;
5325                pkg.mSigningKeys = signingKs;
5326                return;
5327            }
5328
5329            Slog.w(TAG, "PackageSetting for " + ps.name
5330                    + " is missing signatures.  Collecting certs again to recover them.");
5331        } else {
5332            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
5333        }
5334
5335        try {
5336            pp.collectCertificates(pkg, parseFlags);
5337            pp.collectManifestDigest(pkg);
5338        } catch (PackageParserException e) {
5339            throw PackageManagerException.from(e);
5340        }
5341    }
5342
5343    /*
5344     *  Scan a package and return the newly parsed package.
5345     *  Returns null in case of errors and the error code is stored in mLastScanError
5346     */
5347    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
5348            long currentTime, UserHandle user) throws PackageManagerException {
5349        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
5350        parseFlags |= mDefParseFlags;
5351        PackageParser pp = new PackageParser();
5352        pp.setSeparateProcesses(mSeparateProcesses);
5353        pp.setOnlyCoreApps(mOnlyCore);
5354        pp.setDisplayMetrics(mMetrics);
5355
5356        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
5357            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
5358        }
5359
5360        final PackageParser.Package pkg;
5361        try {
5362            pkg = pp.parsePackage(scanFile, parseFlags);
5363        } catch (PackageParserException e) {
5364            throw PackageManagerException.from(e);
5365        }
5366
5367        PackageSetting ps = null;
5368        PackageSetting updatedPkg;
5369        // reader
5370        synchronized (mPackages) {
5371            // Look to see if we already know about this package.
5372            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
5373            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
5374                // This package has been renamed to its original name.  Let's
5375                // use that.
5376                ps = mSettings.peekPackageLPr(oldName);
5377            }
5378            // If there was no original package, see one for the real package name.
5379            if (ps == null) {
5380                ps = mSettings.peekPackageLPr(pkg.packageName);
5381            }
5382            // Check to see if this package could be hiding/updating a system
5383            // package.  Must look for it either under the original or real
5384            // package name depending on our state.
5385            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
5386            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
5387        }
5388        boolean updatedPkgBetter = false;
5389        // First check if this is a system package that may involve an update
5390        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5391            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
5392            // it needs to drop FLAG_PRIVILEGED.
5393            if (locationIsPrivileged(scanFile)) {
5394                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5395            } else {
5396                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5397            }
5398
5399            if (ps != null && !ps.codePath.equals(scanFile)) {
5400                // The path has changed from what was last scanned...  check the
5401                // version of the new path against what we have stored to determine
5402                // what to do.
5403                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
5404                if (pkg.mVersionCode <= ps.versionCode) {
5405                    // The system package has been updated and the code path does not match
5406                    // Ignore entry. Skip it.
5407                    Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5408                            + " ignored: updated version " + ps.versionCode
5409                            + " better than this " + pkg.mVersionCode);
5410                    if (!updatedPkg.codePath.equals(scanFile)) {
5411                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5412                                + ps.name + " changing from " + updatedPkg.codePathString
5413                                + " to " + scanFile);
5414                        updatedPkg.codePath = scanFile;
5415                        updatedPkg.codePathString = scanFile.toString();
5416                        updatedPkg.resourcePath = scanFile;
5417                        updatedPkg.resourcePathString = scanFile.toString();
5418                    }
5419                    updatedPkg.pkg = pkg;
5420                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null);
5421                } else {
5422                    // The current app on the system partition is better than
5423                    // what we have updated to on the data partition; switch
5424                    // back to the system partition version.
5425                    // At this point, its safely assumed that package installation for
5426                    // apps in system partition will go through. If not there won't be a working
5427                    // version of the app
5428                    // writer
5429                    synchronized (mPackages) {
5430                        // Just remove the loaded entries from package lists.
5431                        mPackages.remove(ps.name);
5432                    }
5433
5434                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5435                            + " reverting from " + ps.codePathString
5436                            + ": new version " + pkg.mVersionCode
5437                            + " better than installed " + ps.versionCode);
5438
5439                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5440                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5441                    synchronized (mInstallLock) {
5442                        args.cleanUpResourcesLI();
5443                    }
5444                    synchronized (mPackages) {
5445                        mSettings.enableSystemPackageLPw(ps.name);
5446                    }
5447                    updatedPkgBetter = true;
5448                }
5449            }
5450        }
5451
5452        if (updatedPkg != null) {
5453            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5454            // initially
5455            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5456
5457            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5458            // flag set initially
5459            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5460                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5461            }
5462        }
5463
5464        // Verify certificates against what was last scanned
5465        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5466
5467        /*
5468         * A new system app appeared, but we already had a non-system one of the
5469         * same name installed earlier.
5470         */
5471        boolean shouldHideSystemApp = false;
5472        if (updatedPkg == null && ps != null
5473                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5474            /*
5475             * Check to make sure the signatures match first. If they don't,
5476             * wipe the installed application and its data.
5477             */
5478            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5479                    != PackageManager.SIGNATURE_MATCH) {
5480                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5481                        + " signatures don't match existing userdata copy; removing");
5482                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5483                ps = null;
5484            } else {
5485                /*
5486                 * If the newly-added system app is an older version than the
5487                 * already installed version, hide it. It will be scanned later
5488                 * and re-added like an update.
5489                 */
5490                if (pkg.mVersionCode <= ps.versionCode) {
5491                    shouldHideSystemApp = true;
5492                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5493                            + " but new version " + pkg.mVersionCode + " better than installed "
5494                            + ps.versionCode + "; hiding system");
5495                } else {
5496                    /*
5497                     * The newly found system app is a newer version that the
5498                     * one previously installed. Simply remove the
5499                     * already-installed application and replace it with our own
5500                     * while keeping the application data.
5501                     */
5502                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5503                            + " reverting from " + ps.codePathString + ": new version "
5504                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5505                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5506                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5507                    synchronized (mInstallLock) {
5508                        args.cleanUpResourcesLI();
5509                    }
5510                }
5511            }
5512        }
5513
5514        // The apk is forward locked (not public) if its code and resources
5515        // are kept in different files. (except for app in either system or
5516        // vendor path).
5517        // TODO grab this value from PackageSettings
5518        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5519            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5520                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5521            }
5522        }
5523
5524        // TODO: extend to support forward-locked splits
5525        String resourcePath = null;
5526        String baseResourcePath = null;
5527        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5528            if (ps != null && ps.resourcePathString != null) {
5529                resourcePath = ps.resourcePathString;
5530                baseResourcePath = ps.resourcePathString;
5531            } else {
5532                // Should not happen at all. Just log an error.
5533                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5534            }
5535        } else {
5536            resourcePath = pkg.codePath;
5537            baseResourcePath = pkg.baseCodePath;
5538        }
5539
5540        // Set application objects path explicitly.
5541        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
5542        pkg.applicationInfo.setCodePath(pkg.codePath);
5543        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5544        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5545        pkg.applicationInfo.setResourcePath(resourcePath);
5546        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5547        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5548
5549        // Note that we invoke the following method only if we are about to unpack an application
5550        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5551                | SCAN_UPDATE_SIGNATURE, currentTime, user);
5552
5553        /*
5554         * If the system app should be overridden by a previously installed
5555         * data, hide the system app now and let the /data/app scan pick it up
5556         * again.
5557         */
5558        if (shouldHideSystemApp) {
5559            synchronized (mPackages) {
5560                /*
5561                 * We have to grant systems permissions before we hide, because
5562                 * grantPermissions will assume the package update is trying to
5563                 * expand its permissions.
5564                 */
5565                grantPermissionsLPw(pkg, true, pkg.packageName);
5566                mSettings.disableSystemPackageLPw(pkg.packageName);
5567            }
5568        }
5569
5570        return scannedPkg;
5571    }
5572
5573    private static String fixProcessName(String defProcessName,
5574            String processName, int uid) {
5575        if (processName == null) {
5576            return defProcessName;
5577        }
5578        return processName;
5579    }
5580
5581    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
5582            throws PackageManagerException {
5583        if (pkgSetting.signatures.mSignatures != null) {
5584            // Already existing package. Make sure signatures match
5585            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
5586                    == PackageManager.SIGNATURE_MATCH;
5587            if (!match) {
5588                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
5589                        == PackageManager.SIGNATURE_MATCH;
5590            }
5591            if (!match) {
5592                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
5593                        == PackageManager.SIGNATURE_MATCH;
5594            }
5595            if (!match) {
5596                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5597                        + pkg.packageName + " signatures do not match the "
5598                        + "previously installed version; ignoring!");
5599            }
5600        }
5601
5602        // Check for shared user signatures
5603        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
5604            // Already existing package. Make sure signatures match
5605            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5606                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
5607            if (!match) {
5608                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
5609                        == PackageManager.SIGNATURE_MATCH;
5610            }
5611            if (!match) {
5612                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
5613                        == PackageManager.SIGNATURE_MATCH;
5614            }
5615            if (!match) {
5616                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
5617                        "Package " + pkg.packageName
5618                        + " has no signatures that match those in shared user "
5619                        + pkgSetting.sharedUser.name + "; ignoring!");
5620            }
5621        }
5622    }
5623
5624    /**
5625     * Enforces that only the system UID or root's UID can call a method exposed
5626     * via Binder.
5627     *
5628     * @param message used as message if SecurityException is thrown
5629     * @throws SecurityException if the caller is not system or root
5630     */
5631    private static final void enforceSystemOrRoot(String message) {
5632        final int uid = Binder.getCallingUid();
5633        if (uid != Process.SYSTEM_UID && uid != 0) {
5634            throw new SecurityException(message);
5635        }
5636    }
5637
5638    @Override
5639    public void performBootDexOpt() {
5640        enforceSystemOrRoot("Only the system can request dexopt be performed");
5641
5642        // Before everything else, see whether we need to fstrim.
5643        try {
5644            IMountService ms = PackageHelper.getMountService();
5645            if (ms != null) {
5646                final boolean isUpgrade = isUpgrade();
5647                boolean doTrim = isUpgrade;
5648                if (doTrim) {
5649                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
5650                } else {
5651                    final long interval = android.provider.Settings.Global.getLong(
5652                            mContext.getContentResolver(),
5653                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
5654                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
5655                    if (interval > 0) {
5656                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
5657                        if (timeSinceLast > interval) {
5658                            doTrim = true;
5659                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
5660                                    + "; running immediately");
5661                        }
5662                    }
5663                }
5664                if (doTrim) {
5665                    if (!isFirstBoot()) {
5666                        try {
5667                            ActivityManagerNative.getDefault().showBootMessage(
5668                                    mContext.getResources().getString(
5669                                            R.string.android_upgrading_fstrim), true);
5670                        } catch (RemoteException e) {
5671                        }
5672                    }
5673                    ms.runMaintenance();
5674                }
5675            } else {
5676                Slog.e(TAG, "Mount service unavailable!");
5677            }
5678        } catch (RemoteException e) {
5679            // Can't happen; MountService is local
5680        }
5681
5682        final ArraySet<PackageParser.Package> pkgs;
5683        synchronized (mPackages) {
5684            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
5685        }
5686
5687        if (pkgs != null) {
5688            // Sort apps by importance for dexopt ordering. Important apps are given more priority
5689            // in case the device runs out of space.
5690            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
5691            // Give priority to core apps.
5692            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5693                PackageParser.Package pkg = it.next();
5694                if (pkg.coreApp) {
5695                    if (DEBUG_DEXOPT) {
5696                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
5697                    }
5698                    sortedPkgs.add(pkg);
5699                    it.remove();
5700                }
5701            }
5702            // Give priority to system apps that listen for pre boot complete.
5703            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
5704            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
5705            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5706                PackageParser.Package pkg = it.next();
5707                if (pkgNames.contains(pkg.packageName)) {
5708                    if (DEBUG_DEXOPT) {
5709                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
5710                    }
5711                    sortedPkgs.add(pkg);
5712                    it.remove();
5713                }
5714            }
5715            // Give priority to system apps.
5716            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5717                PackageParser.Package pkg = it.next();
5718                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
5719                    if (DEBUG_DEXOPT) {
5720                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
5721                    }
5722                    sortedPkgs.add(pkg);
5723                    it.remove();
5724                }
5725            }
5726            // Give priority to updated system apps.
5727            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5728                PackageParser.Package pkg = it.next();
5729                if (pkg.isUpdatedSystemApp()) {
5730                    if (DEBUG_DEXOPT) {
5731                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
5732                    }
5733                    sortedPkgs.add(pkg);
5734                    it.remove();
5735                }
5736            }
5737            // Give priority to apps that listen for boot complete.
5738            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
5739            pkgNames = getPackageNamesForIntent(intent);
5740            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5741                PackageParser.Package pkg = it.next();
5742                if (pkgNames.contains(pkg.packageName)) {
5743                    if (DEBUG_DEXOPT) {
5744                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
5745                    }
5746                    sortedPkgs.add(pkg);
5747                    it.remove();
5748                }
5749            }
5750            // Filter out packages that aren't recently used.
5751            filterRecentlyUsedApps(pkgs);
5752            // Add all remaining apps.
5753            for (PackageParser.Package pkg : pkgs) {
5754                if (DEBUG_DEXOPT) {
5755                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
5756                }
5757                sortedPkgs.add(pkg);
5758            }
5759
5760            // If we want to be lazy, filter everything that wasn't recently used.
5761            if (mLazyDexOpt) {
5762                filterRecentlyUsedApps(sortedPkgs);
5763            }
5764
5765            int i = 0;
5766            int total = sortedPkgs.size();
5767            File dataDir = Environment.getDataDirectory();
5768            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
5769            if (lowThreshold == 0) {
5770                throw new IllegalStateException("Invalid low memory threshold");
5771            }
5772            for (PackageParser.Package pkg : sortedPkgs) {
5773                long usableSpace = dataDir.getUsableSpace();
5774                if (usableSpace < lowThreshold) {
5775                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
5776                    break;
5777                }
5778                performBootDexOpt(pkg, ++i, total);
5779            }
5780        }
5781    }
5782
5783    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
5784        // Filter out packages that aren't recently used.
5785        //
5786        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
5787        // should do a full dexopt.
5788        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
5789            int total = pkgs.size();
5790            int skipped = 0;
5791            long now = System.currentTimeMillis();
5792            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
5793                PackageParser.Package pkg = i.next();
5794                long then = pkg.mLastPackageUsageTimeInMills;
5795                if (then + mDexOptLRUThresholdInMills < now) {
5796                    if (DEBUG_DEXOPT) {
5797                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
5798                              ((then == 0) ? "never" : new Date(then)));
5799                    }
5800                    i.remove();
5801                    skipped++;
5802                }
5803            }
5804            if (DEBUG_DEXOPT) {
5805                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
5806            }
5807        }
5808    }
5809
5810    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
5811        List<ResolveInfo> ris = null;
5812        try {
5813            ris = AppGlobals.getPackageManager().queryIntentReceivers(
5814                    intent, null, 0, UserHandle.USER_OWNER);
5815        } catch (RemoteException e) {
5816        }
5817        ArraySet<String> pkgNames = new ArraySet<String>();
5818        if (ris != null) {
5819            for (ResolveInfo ri : ris) {
5820                pkgNames.add(ri.activityInfo.packageName);
5821            }
5822        }
5823        return pkgNames;
5824    }
5825
5826    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
5827        if (DEBUG_DEXOPT) {
5828            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
5829        }
5830        if (!isFirstBoot()) {
5831            try {
5832                ActivityManagerNative.getDefault().showBootMessage(
5833                        mContext.getResources().getString(R.string.android_upgrading_apk,
5834                                curr, total), true);
5835            } catch (RemoteException e) {
5836            }
5837        }
5838        PackageParser.Package p = pkg;
5839        synchronized (mInstallLock) {
5840            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
5841                    false /* force dex */, false /* defer */, true /* include dependencies */);
5842        }
5843    }
5844
5845    @Override
5846    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
5847        return performDexOpt(packageName, instructionSet, false);
5848    }
5849
5850    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
5851        boolean dexopt = mLazyDexOpt || backgroundDexopt;
5852        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
5853        if (!dexopt && !updateUsage) {
5854            // We aren't going to dexopt or update usage, so bail early.
5855            return false;
5856        }
5857        PackageParser.Package p;
5858        final String targetInstructionSet;
5859        synchronized (mPackages) {
5860            p = mPackages.get(packageName);
5861            if (p == null) {
5862                return false;
5863            }
5864            if (updateUsage) {
5865                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
5866            }
5867            mPackageUsage.write(false);
5868            if (!dexopt) {
5869                // We aren't going to dexopt, so bail early.
5870                return false;
5871            }
5872
5873            targetInstructionSet = instructionSet != null ? instructionSet :
5874                    getPrimaryInstructionSet(p.applicationInfo);
5875            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
5876                return false;
5877            }
5878        }
5879
5880        synchronized (mInstallLock) {
5881            final String[] instructionSets = new String[] { targetInstructionSet };
5882            int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
5883                    false /* forceDex */, false /* defer */, true /* inclDependencies */);
5884            return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
5885        }
5886    }
5887
5888    public ArraySet<String> getPackagesThatNeedDexOpt() {
5889        ArraySet<String> pkgs = null;
5890        synchronized (mPackages) {
5891            for (PackageParser.Package p : mPackages.values()) {
5892                if (DEBUG_DEXOPT) {
5893                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
5894                }
5895                if (!p.mDexOptPerformed.isEmpty()) {
5896                    continue;
5897                }
5898                if (pkgs == null) {
5899                    pkgs = new ArraySet<String>();
5900                }
5901                pkgs.add(p.packageName);
5902            }
5903        }
5904        return pkgs;
5905    }
5906
5907    public void shutdown() {
5908        mPackageUsage.write(true);
5909    }
5910
5911    @Override
5912    public void forceDexOpt(String packageName) {
5913        enforceSystemOrRoot("forceDexOpt");
5914
5915        PackageParser.Package pkg;
5916        synchronized (mPackages) {
5917            pkg = mPackages.get(packageName);
5918            if (pkg == null) {
5919                throw new IllegalArgumentException("Missing package: " + packageName);
5920            }
5921        }
5922
5923        synchronized (mInstallLock) {
5924            final String[] instructionSets = new String[] {
5925                    getPrimaryInstructionSet(pkg.applicationInfo) };
5926            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
5927                    true /*forceDex*/, false /* defer */, true /* inclDependencies */);
5928            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
5929                throw new IllegalStateException("Failed to dexopt: " + res);
5930            }
5931        }
5932    }
5933
5934    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
5935        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
5936            Slog.w(TAG, "Unable to update from " + oldPkg.name
5937                    + " to " + newPkg.packageName
5938                    + ": old package not in system partition");
5939            return false;
5940        } else if (mPackages.get(oldPkg.name) != null) {
5941            Slog.w(TAG, "Unable to update from " + oldPkg.name
5942                    + " to " + newPkg.packageName
5943                    + ": old package still exists");
5944            return false;
5945        }
5946        return true;
5947    }
5948
5949    private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
5950        int[] users = sUserManager.getUserIds();
5951        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
5952        if (res < 0) {
5953            return res;
5954        }
5955        for (int user : users) {
5956            if (user != 0) {
5957                res = mInstaller.createUserData(volumeUuid, packageName,
5958                        UserHandle.getUid(user, uid), user, seinfo);
5959                if (res < 0) {
5960                    return res;
5961                }
5962            }
5963        }
5964        return res;
5965    }
5966
5967    private int removeDataDirsLI(String volumeUuid, String packageName) {
5968        int[] users = sUserManager.getUserIds();
5969        int res = 0;
5970        for (int user : users) {
5971            int resInner = mInstaller.remove(volumeUuid, packageName, user);
5972            if (resInner < 0) {
5973                res = resInner;
5974            }
5975        }
5976
5977        return res;
5978    }
5979
5980    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
5981        int[] users = sUserManager.getUserIds();
5982        int res = 0;
5983        for (int user : users) {
5984            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
5985            if (resInner < 0) {
5986                res = resInner;
5987            }
5988        }
5989        return res;
5990    }
5991
5992    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
5993            PackageParser.Package changingLib) {
5994        if (file.path != null) {
5995            usesLibraryFiles.add(file.path);
5996            return;
5997        }
5998        PackageParser.Package p = mPackages.get(file.apk);
5999        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6000            // If we are doing this while in the middle of updating a library apk,
6001            // then we need to make sure to use that new apk for determining the
6002            // dependencies here.  (We haven't yet finished committing the new apk
6003            // to the package manager state.)
6004            if (p == null || p.packageName.equals(changingLib.packageName)) {
6005                p = changingLib;
6006            }
6007        }
6008        if (p != null) {
6009            usesLibraryFiles.addAll(p.getAllCodePaths());
6010        }
6011    }
6012
6013    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6014            PackageParser.Package changingLib) throws PackageManagerException {
6015        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6016            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6017            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6018            for (int i=0; i<N; i++) {
6019                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6020                if (file == null) {
6021                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6022                            "Package " + pkg.packageName + " requires unavailable shared library "
6023                            + pkg.usesLibraries.get(i) + "; failing!");
6024                }
6025                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6026            }
6027            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6028            for (int i=0; i<N; i++) {
6029                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6030                if (file == null) {
6031                    Slog.w(TAG, "Package " + pkg.packageName
6032                            + " desires unavailable shared library "
6033                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6034                } else {
6035                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6036                }
6037            }
6038            N = usesLibraryFiles.size();
6039            if (N > 0) {
6040                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6041            } else {
6042                pkg.usesLibraryFiles = null;
6043            }
6044        }
6045    }
6046
6047    private static boolean hasString(List<String> list, List<String> which) {
6048        if (list == null) {
6049            return false;
6050        }
6051        for (int i=list.size()-1; i>=0; i--) {
6052            for (int j=which.size()-1; j>=0; j--) {
6053                if (which.get(j).equals(list.get(i))) {
6054                    return true;
6055                }
6056            }
6057        }
6058        return false;
6059    }
6060
6061    private void updateAllSharedLibrariesLPw() {
6062        for (PackageParser.Package pkg : mPackages.values()) {
6063            try {
6064                updateSharedLibrariesLPw(pkg, null);
6065            } catch (PackageManagerException e) {
6066                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6067            }
6068        }
6069    }
6070
6071    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6072            PackageParser.Package changingPkg) {
6073        ArrayList<PackageParser.Package> res = null;
6074        for (PackageParser.Package pkg : mPackages.values()) {
6075            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6076                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6077                if (res == null) {
6078                    res = new ArrayList<PackageParser.Package>();
6079                }
6080                res.add(pkg);
6081                try {
6082                    updateSharedLibrariesLPw(pkg, changingPkg);
6083                } catch (PackageManagerException e) {
6084                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6085                }
6086            }
6087        }
6088        return res;
6089    }
6090
6091    /**
6092     * Derive the value of the {@code cpuAbiOverride} based on the provided
6093     * value and an optional stored value from the package settings.
6094     */
6095    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6096        String cpuAbiOverride = null;
6097
6098        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6099            cpuAbiOverride = null;
6100        } else if (abiOverride != null) {
6101            cpuAbiOverride = abiOverride;
6102        } else if (settings != null) {
6103            cpuAbiOverride = settings.cpuAbiOverrideString;
6104        }
6105
6106        return cpuAbiOverride;
6107    }
6108
6109    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6110            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6111        boolean success = false;
6112        try {
6113            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6114                    currentTime, user);
6115            success = true;
6116            return res;
6117        } finally {
6118            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6119                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6120            }
6121        }
6122    }
6123
6124    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6125            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6126        final File scanFile = new File(pkg.codePath);
6127        if (pkg.applicationInfo.getCodePath() == null ||
6128                pkg.applicationInfo.getResourcePath() == null) {
6129            // Bail out. The resource and code paths haven't been set.
6130            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6131                    "Code and resource paths haven't been set correctly");
6132        }
6133
6134        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6135            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6136        } else {
6137            // Only allow system apps to be flagged as core apps.
6138            pkg.coreApp = false;
6139        }
6140
6141        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6142            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6143        }
6144
6145        if (mCustomResolverComponentName != null &&
6146                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6147            setUpCustomResolverActivity(pkg);
6148        }
6149
6150        if (pkg.packageName.equals("android")) {
6151            synchronized (mPackages) {
6152                if (mAndroidApplication != null) {
6153                    Slog.w(TAG, "*************************************************");
6154                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6155                    Slog.w(TAG, " file=" + scanFile);
6156                    Slog.w(TAG, "*************************************************");
6157                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6158                            "Core android package being redefined.  Skipping.");
6159                }
6160
6161                // Set up information for our fall-back user intent resolution activity.
6162                mPlatformPackage = pkg;
6163                pkg.mVersionCode = mSdkVersion;
6164                mAndroidApplication = pkg.applicationInfo;
6165
6166                if (!mResolverReplaced) {
6167                    mResolveActivity.applicationInfo = mAndroidApplication;
6168                    mResolveActivity.name = ResolverActivity.class.getName();
6169                    mResolveActivity.packageName = mAndroidApplication.packageName;
6170                    mResolveActivity.processName = "system:ui";
6171                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6172                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6173                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6174                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6175                    mResolveActivity.exported = true;
6176                    mResolveActivity.enabled = true;
6177                    mResolveInfo.activityInfo = mResolveActivity;
6178                    mResolveInfo.priority = 0;
6179                    mResolveInfo.preferredOrder = 0;
6180                    mResolveInfo.match = 0;
6181                    mResolveComponentName = new ComponentName(
6182                            mAndroidApplication.packageName, mResolveActivity.name);
6183                }
6184            }
6185        }
6186
6187        if (DEBUG_PACKAGE_SCANNING) {
6188            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6189                Log.d(TAG, "Scanning package " + pkg.packageName);
6190        }
6191
6192        if (mPackages.containsKey(pkg.packageName)
6193                || mSharedLibraries.containsKey(pkg.packageName)) {
6194            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6195                    "Application package " + pkg.packageName
6196                    + " already installed.  Skipping duplicate.");
6197        }
6198
6199        // If we're only installing presumed-existing packages, require that the
6200        // scanned APK is both already known and at the path previously established
6201        // for it.  Previously unknown packages we pick up normally, but if we have an
6202        // a priori expectation about this package's install presence, enforce it.
6203        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6204            PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6205            if (known != null) {
6206                if (DEBUG_PACKAGE_SCANNING) {
6207                    Log.d(TAG, "Examining " + pkg.codePath
6208                            + " and requiring known paths " + known.codePathString
6209                            + " & " + known.resourcePathString);
6210                }
6211                if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6212                        || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6213                    throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6214                            "Application package " + pkg.packageName
6215                            + " found at " + pkg.applicationInfo.getCodePath()
6216                            + " but expected at " + known.codePathString + "; ignoring.");
6217                }
6218            }
6219        }
6220
6221        // Initialize package source and resource directories
6222        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6223        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6224
6225        SharedUserSetting suid = null;
6226        PackageSetting pkgSetting = null;
6227
6228        if (!isSystemApp(pkg)) {
6229            // Only system apps can use these features.
6230            pkg.mOriginalPackages = null;
6231            pkg.mRealPackage = null;
6232            pkg.mAdoptPermissions = null;
6233        }
6234
6235        // writer
6236        synchronized (mPackages) {
6237            if (pkg.mSharedUserId != null) {
6238                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6239                if (suid == null) {
6240                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6241                            "Creating application package " + pkg.packageName
6242                            + " for shared user failed");
6243                }
6244                if (DEBUG_PACKAGE_SCANNING) {
6245                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6246                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6247                                + "): packages=" + suid.packages);
6248                }
6249            }
6250
6251            // Check if we are renaming from an original package name.
6252            PackageSetting origPackage = null;
6253            String realName = null;
6254            if (pkg.mOriginalPackages != null) {
6255                // This package may need to be renamed to a previously
6256                // installed name.  Let's check on that...
6257                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
6258                if (pkg.mOriginalPackages.contains(renamed)) {
6259                    // This package had originally been installed as the
6260                    // original name, and we have already taken care of
6261                    // transitioning to the new one.  Just update the new
6262                    // one to continue using the old name.
6263                    realName = pkg.mRealPackage;
6264                    if (!pkg.packageName.equals(renamed)) {
6265                        // Callers into this function may have already taken
6266                        // care of renaming the package; only do it here if
6267                        // it is not already done.
6268                        pkg.setPackageName(renamed);
6269                    }
6270
6271                } else {
6272                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
6273                        if ((origPackage = mSettings.peekPackageLPr(
6274                                pkg.mOriginalPackages.get(i))) != null) {
6275                            // We do have the package already installed under its
6276                            // original name...  should we use it?
6277                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
6278                                // New package is not compatible with original.
6279                                origPackage = null;
6280                                continue;
6281                            } else if (origPackage.sharedUser != null) {
6282                                // Make sure uid is compatible between packages.
6283                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6284                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6285                                            + " to " + pkg.packageName + ": old uid "
6286                                            + origPackage.sharedUser.name
6287                                            + " differs from " + pkg.mSharedUserId);
6288                                    origPackage = null;
6289                                    continue;
6290                                }
6291                            } else {
6292                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6293                                        + pkg.packageName + " to old name " + origPackage.name);
6294                            }
6295                            break;
6296                        }
6297                    }
6298                }
6299            }
6300
6301            if (mTransferedPackages.contains(pkg.packageName)) {
6302                Slog.w(TAG, "Package " + pkg.packageName
6303                        + " was transferred to another, but its .apk remains");
6304            }
6305
6306            // Just create the setting, don't add it yet. For already existing packages
6307            // the PkgSetting exists already and doesn't have to be created.
6308            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6309                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6310                    pkg.applicationInfo.primaryCpuAbi,
6311                    pkg.applicationInfo.secondaryCpuAbi,
6312                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6313                    user, false);
6314            if (pkgSetting == null) {
6315                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6316                        "Creating application package " + pkg.packageName + " failed");
6317            }
6318
6319            if (pkgSetting.origPackage != null) {
6320                // If we are first transitioning from an original package,
6321                // fix up the new package's name now.  We need to do this after
6322                // looking up the package under its new name, so getPackageLP
6323                // can take care of fiddling things correctly.
6324                pkg.setPackageName(origPackage.name);
6325
6326                // File a report about this.
6327                String msg = "New package " + pkgSetting.realName
6328                        + " renamed to replace old package " + pkgSetting.name;
6329                reportSettingsProblem(Log.WARN, msg);
6330
6331                // Make a note of it.
6332                mTransferedPackages.add(origPackage.name);
6333
6334                // No longer need to retain this.
6335                pkgSetting.origPackage = null;
6336            }
6337
6338            if (realName != null) {
6339                // Make a note of it.
6340                mTransferedPackages.add(pkg.packageName);
6341            }
6342
6343            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6344                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6345            }
6346
6347            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6348                // Check all shared libraries and map to their actual file path.
6349                // We only do this here for apps not on a system dir, because those
6350                // are the only ones that can fail an install due to this.  We
6351                // will take care of the system apps by updating all of their
6352                // library paths after the scan is done.
6353                updateSharedLibrariesLPw(pkg, null);
6354            }
6355
6356            if (mFoundPolicyFile) {
6357                SELinuxMMAC.assignSeinfoValue(pkg);
6358            }
6359
6360            pkg.applicationInfo.uid = pkgSetting.appId;
6361            pkg.mExtras = pkgSetting;
6362            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
6363                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
6364                    // We just determined the app is signed correctly, so bring
6365                    // over the latest parsed certs.
6366                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6367                } else {
6368                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6369                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6370                                "Package " + pkg.packageName + " upgrade keys do not match the "
6371                                + "previously installed version");
6372                    } else {
6373                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
6374                        String msg = "System package " + pkg.packageName
6375                            + " signature changed; retaining data.";
6376                        reportSettingsProblem(Log.WARN, msg);
6377                    }
6378                }
6379            } else {
6380                try {
6381                    verifySignaturesLP(pkgSetting, pkg);
6382                    // We just determined the app is signed correctly, so bring
6383                    // over the latest parsed certs.
6384                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6385                } catch (PackageManagerException e) {
6386                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6387                        throw e;
6388                    }
6389                    // The signature has changed, but this package is in the system
6390                    // image...  let's recover!
6391                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6392                    // However...  if this package is part of a shared user, but it
6393                    // doesn't match the signature of the shared user, let's fail.
6394                    // What this means is that you can't change the signatures
6395                    // associated with an overall shared user, which doesn't seem all
6396                    // that unreasonable.
6397                    if (pkgSetting.sharedUser != null) {
6398                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6399                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
6400                            throw new PackageManagerException(
6401                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
6402                                            "Signature mismatch for shared user : "
6403                                            + pkgSetting.sharedUser);
6404                        }
6405                    }
6406                    // File a report about this.
6407                    String msg = "System package " + pkg.packageName
6408                        + " signature changed; retaining data.";
6409                    reportSettingsProblem(Log.WARN, msg);
6410                }
6411            }
6412            // Verify that this new package doesn't have any content providers
6413            // that conflict with existing packages.  Only do this if the
6414            // package isn't already installed, since we don't want to break
6415            // things that are installed.
6416            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6417                final int N = pkg.providers.size();
6418                int i;
6419                for (i=0; i<N; i++) {
6420                    PackageParser.Provider p = pkg.providers.get(i);
6421                    if (p.info.authority != null) {
6422                        String names[] = p.info.authority.split(";");
6423                        for (int j = 0; j < names.length; j++) {
6424                            if (mProvidersByAuthority.containsKey(names[j])) {
6425                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6426                                final String otherPackageName =
6427                                        ((other != null && other.getComponentName() != null) ?
6428                                                other.getComponentName().getPackageName() : "?");
6429                                throw new PackageManagerException(
6430                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
6431                                                "Can't install because provider name " + names[j]
6432                                                + " (in package " + pkg.applicationInfo.packageName
6433                                                + ") is already used by " + otherPackageName);
6434                            }
6435                        }
6436                    }
6437                }
6438            }
6439
6440            if (pkg.mAdoptPermissions != null) {
6441                // This package wants to adopt ownership of permissions from
6442                // another package.
6443                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6444                    final String origName = pkg.mAdoptPermissions.get(i);
6445                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
6446                    if (orig != null) {
6447                        if (verifyPackageUpdateLPr(orig, pkg)) {
6448                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
6449                                    + pkg.packageName);
6450                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
6451                        }
6452                    }
6453                }
6454            }
6455        }
6456
6457        final String pkgName = pkg.packageName;
6458
6459        final long scanFileTime = scanFile.lastModified();
6460        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6461        pkg.applicationInfo.processName = fixProcessName(
6462                pkg.applicationInfo.packageName,
6463                pkg.applicationInfo.processName,
6464                pkg.applicationInfo.uid);
6465
6466        File dataPath;
6467        if (mPlatformPackage == pkg) {
6468            // The system package is special.
6469            dataPath = new File(Environment.getDataDirectory(), "system");
6470
6471            pkg.applicationInfo.dataDir = dataPath.getPath();
6472
6473        } else {
6474            // This is a normal package, need to make its data directory.
6475            dataPath = PackageManager.getDataDirForUser(pkg.volumeUuid, pkg.packageName,
6476                    UserHandle.USER_OWNER);
6477
6478            boolean uidError = false;
6479            if (dataPath.exists()) {
6480                int currentUid = 0;
6481                try {
6482                    StructStat stat = Os.stat(dataPath.getPath());
6483                    currentUid = stat.st_uid;
6484                } catch (ErrnoException e) {
6485                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6486                }
6487
6488                // If we have mismatched owners for the data path, we have a problem.
6489                if (currentUid != pkg.applicationInfo.uid) {
6490                    boolean recovered = false;
6491                    if (currentUid == 0) {
6492                        // The directory somehow became owned by root.  Wow.
6493                        // This is probably because the system was stopped while
6494                        // installd was in the middle of messing with its libs
6495                        // directory.  Ask installd to fix that.
6496                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
6497                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
6498                        if (ret >= 0) {
6499                            recovered = true;
6500                            String msg = "Package " + pkg.packageName
6501                                    + " unexpectedly changed to uid 0; recovered to " +
6502                                    + pkg.applicationInfo.uid;
6503                            reportSettingsProblem(Log.WARN, msg);
6504                        }
6505                    }
6506                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6507                            || (scanFlags&SCAN_BOOTING) != 0)) {
6508                        // If this is a system app, we can at least delete its
6509                        // current data so the application will still work.
6510                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
6511                        if (ret >= 0) {
6512                            // TODO: Kill the processes first
6513                            // Old data gone!
6514                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6515                                    ? "System package " : "Third party package ";
6516                            String msg = prefix + pkg.packageName
6517                                    + " has changed from uid: "
6518                                    + currentUid + " to "
6519                                    + pkg.applicationInfo.uid + "; old data erased";
6520                            reportSettingsProblem(Log.WARN, msg);
6521                            recovered = true;
6522
6523                            // And now re-install the app.
6524                            ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6525                                    pkg.applicationInfo.seinfo);
6526                            if (ret == -1) {
6527                                // Ack should not happen!
6528                                msg = prefix + pkg.packageName
6529                                        + " could not have data directory re-created after delete.";
6530                                reportSettingsProblem(Log.WARN, msg);
6531                                throw new PackageManagerException(
6532                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6533                            }
6534                        }
6535                        if (!recovered) {
6536                            mHasSystemUidErrors = true;
6537                        }
6538                    } else if (!recovered) {
6539                        // If we allow this install to proceed, we will be broken.
6540                        // Abort, abort!
6541                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
6542                                "scanPackageLI");
6543                    }
6544                    if (!recovered) {
6545                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
6546                            + pkg.applicationInfo.uid + "/fs_"
6547                            + currentUid;
6548                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
6549                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
6550                        String msg = "Package " + pkg.packageName
6551                                + " has mismatched uid: "
6552                                + currentUid + " on disk, "
6553                                + pkg.applicationInfo.uid + " in settings";
6554                        // writer
6555                        synchronized (mPackages) {
6556                            mSettings.mReadMessages.append(msg);
6557                            mSettings.mReadMessages.append('\n');
6558                            uidError = true;
6559                            if (!pkgSetting.uidError) {
6560                                reportSettingsProblem(Log.ERROR, msg);
6561                            }
6562                        }
6563                    }
6564                }
6565                pkg.applicationInfo.dataDir = dataPath.getPath();
6566                if (mShouldRestoreconData) {
6567                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
6568                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
6569                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
6570                }
6571            } else {
6572                if (DEBUG_PACKAGE_SCANNING) {
6573                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6574                        Log.v(TAG, "Want this data dir: " + dataPath);
6575                }
6576                //invoke installer to do the actual installation
6577                int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6578                        pkg.applicationInfo.seinfo);
6579                if (ret < 0) {
6580                    // Error from installer
6581                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6582                            "Unable to create data dirs [errorCode=" + ret + "]");
6583                }
6584
6585                if (dataPath.exists()) {
6586                    pkg.applicationInfo.dataDir = dataPath.getPath();
6587                } else {
6588                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
6589                    pkg.applicationInfo.dataDir = null;
6590                }
6591            }
6592
6593            pkgSetting.uidError = uidError;
6594        }
6595
6596        final String path = scanFile.getPath();
6597        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
6598
6599        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
6600            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
6601
6602            // Some system apps still use directory structure for native libraries
6603            // in which case we might end up not detecting abi solely based on apk
6604            // structure. Try to detect abi based on directory structure.
6605            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
6606                    pkg.applicationInfo.primaryCpuAbi == null) {
6607                setBundledAppAbisAndRoots(pkg, pkgSetting);
6608                setNativeLibraryPaths(pkg);
6609            }
6610
6611        } else {
6612            if ((scanFlags & SCAN_MOVE) != 0) {
6613                // We haven't run dex-opt for this move (since we've moved the compiled output too)
6614                // but we already have this packages package info in the PackageSetting. We just
6615                // use that and derive the native library path based on the new codepath.
6616                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
6617                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
6618            }
6619
6620            // Set native library paths again. For moves, the path will be updated based on the
6621            // ABIs we've determined above. For non-moves, the path will be updated based on the
6622            // ABIs we determined during compilation, but the path will depend on the final
6623            // package path (after the rename away from the stage path).
6624            setNativeLibraryPaths(pkg);
6625        }
6626
6627        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
6628        final int[] userIds = sUserManager.getUserIds();
6629        synchronized (mInstallLock) {
6630            // Create a native library symlink only if we have native libraries
6631            // and if the native libraries are 32 bit libraries. We do not provide
6632            // this symlink for 64 bit libraries.
6633            if (pkg.applicationInfo.primaryCpuAbi != null &&
6634                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
6635                final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
6636                for (int userId : userIds) {
6637                    if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
6638                            nativeLibPath, userId) < 0) {
6639                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
6640                                "Failed linking native library dir (user=" + userId + ")");
6641                    }
6642                }
6643            }
6644        }
6645
6646        // This is a special case for the "system" package, where the ABI is
6647        // dictated by the zygote configuration (and init.rc). We should keep track
6648        // of this ABI so that we can deal with "normal" applications that run under
6649        // the same UID correctly.
6650        if (mPlatformPackage == pkg) {
6651            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
6652                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
6653        }
6654
6655        // If there's a mismatch between the abi-override in the package setting
6656        // and the abiOverride specified for the install. Warn about this because we
6657        // would've already compiled the app without taking the package setting into
6658        // account.
6659        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
6660            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
6661                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
6662                        " for package: " + pkg.packageName);
6663            }
6664        }
6665
6666        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6667        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6668        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
6669
6670        // Copy the derived override back to the parsed package, so that we can
6671        // update the package settings accordingly.
6672        pkg.cpuAbiOverride = cpuAbiOverride;
6673
6674        if (DEBUG_ABI_SELECTION) {
6675            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
6676                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
6677                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
6678        }
6679
6680        // Push the derived path down into PackageSettings so we know what to
6681        // clean up at uninstall time.
6682        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
6683
6684        if (DEBUG_ABI_SELECTION) {
6685            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
6686                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
6687                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
6688        }
6689
6690        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
6691            // We don't do this here during boot because we can do it all
6692            // at once after scanning all existing packages.
6693            //
6694            // We also do this *before* we perform dexopt on this package, so that
6695            // we can avoid redundant dexopts, and also to make sure we've got the
6696            // code and package path correct.
6697            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
6698                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
6699        }
6700
6701        if ((scanFlags & SCAN_NO_DEX) == 0) {
6702            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
6703                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */);
6704            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6705                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
6706            }
6707        }
6708        if (mFactoryTest && pkg.requestedPermissions.contains(
6709                android.Manifest.permission.FACTORY_TEST)) {
6710            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
6711        }
6712
6713        ArrayList<PackageParser.Package> clientLibPkgs = null;
6714
6715        // writer
6716        synchronized (mPackages) {
6717            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6718                // Only system apps can add new shared libraries.
6719                if (pkg.libraryNames != null) {
6720                    for (int i=0; i<pkg.libraryNames.size(); i++) {
6721                        String name = pkg.libraryNames.get(i);
6722                        boolean allowed = false;
6723                        if (pkg.isUpdatedSystemApp()) {
6724                            // New library entries can only be added through the
6725                            // system image.  This is important to get rid of a lot
6726                            // of nasty edge cases: for example if we allowed a non-
6727                            // system update of the app to add a library, then uninstalling
6728                            // the update would make the library go away, and assumptions
6729                            // we made such as through app install filtering would now
6730                            // have allowed apps on the device which aren't compatible
6731                            // with it.  Better to just have the restriction here, be
6732                            // conservative, and create many fewer cases that can negatively
6733                            // impact the user experience.
6734                            final PackageSetting sysPs = mSettings
6735                                    .getDisabledSystemPkgLPr(pkg.packageName);
6736                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
6737                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
6738                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
6739                                        allowed = true;
6740                                        allowed = true;
6741                                        break;
6742                                    }
6743                                }
6744                            }
6745                        } else {
6746                            allowed = true;
6747                        }
6748                        if (allowed) {
6749                            if (!mSharedLibraries.containsKey(name)) {
6750                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
6751                            } else if (!name.equals(pkg.packageName)) {
6752                                Slog.w(TAG, "Package " + pkg.packageName + " library "
6753                                        + name + " already exists; skipping");
6754                            }
6755                        } else {
6756                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
6757                                    + name + " that is not declared on system image; skipping");
6758                        }
6759                    }
6760                    if ((scanFlags&SCAN_BOOTING) == 0) {
6761                        // If we are not booting, we need to update any applications
6762                        // that are clients of our shared library.  If we are booting,
6763                        // this will all be done once the scan is complete.
6764                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
6765                    }
6766                }
6767            }
6768        }
6769
6770        // We also need to dexopt any apps that are dependent on this library.  Note that
6771        // if these fail, we should abort the install since installing the library will
6772        // result in some apps being broken.
6773        if (clientLibPkgs != null) {
6774            if ((scanFlags & SCAN_NO_DEX) == 0) {
6775                for (int i = 0; i < clientLibPkgs.size(); i++) {
6776                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
6777                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
6778                            null /* instruction sets */, forceDex,
6779                            (scanFlags & SCAN_DEFER_DEX) != 0, false);
6780                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6781                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
6782                                "scanPackageLI failed to dexopt clientLibPkgs");
6783                    }
6784                }
6785            }
6786        }
6787
6788        // Also need to kill any apps that are dependent on the library.
6789        if (clientLibPkgs != null) {
6790            for (int i=0; i<clientLibPkgs.size(); i++) {
6791                PackageParser.Package clientPkg = clientLibPkgs.get(i);
6792                killApplication(clientPkg.applicationInfo.packageName,
6793                        clientPkg.applicationInfo.uid, "update lib");
6794            }
6795        }
6796
6797        // Make sure we're not adding any bogus keyset info
6798        KeySetManagerService ksms = mSettings.mKeySetManagerService;
6799        ksms.assertScannedPackageValid(pkg);
6800
6801        // writer
6802        synchronized (mPackages) {
6803            // We don't expect installation to fail beyond this point
6804
6805            // Add the new setting to mSettings
6806            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
6807            // Add the new setting to mPackages
6808            mPackages.put(pkg.applicationInfo.packageName, pkg);
6809            // Make sure we don't accidentally delete its data.
6810            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
6811            while (iter.hasNext()) {
6812                PackageCleanItem item = iter.next();
6813                if (pkgName.equals(item.packageName)) {
6814                    iter.remove();
6815                }
6816            }
6817
6818            // Take care of first install / last update times.
6819            if (currentTime != 0) {
6820                if (pkgSetting.firstInstallTime == 0) {
6821                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
6822                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
6823                    pkgSetting.lastUpdateTime = currentTime;
6824                }
6825            } else if (pkgSetting.firstInstallTime == 0) {
6826                // We need *something*.  Take time time stamp of the file.
6827                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
6828            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
6829                if (scanFileTime != pkgSetting.timeStamp) {
6830                    // A package on the system image has changed; consider this
6831                    // to be an update.
6832                    pkgSetting.lastUpdateTime = scanFileTime;
6833                }
6834            }
6835
6836            // Add the package's KeySets to the global KeySetManagerService
6837            ksms.addScannedPackageLPw(pkg);
6838
6839            int N = pkg.providers.size();
6840            StringBuilder r = null;
6841            int i;
6842            for (i=0; i<N; i++) {
6843                PackageParser.Provider p = pkg.providers.get(i);
6844                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
6845                        p.info.processName, pkg.applicationInfo.uid);
6846                mProviders.addProvider(p);
6847                p.syncable = p.info.isSyncable;
6848                if (p.info.authority != null) {
6849                    String names[] = p.info.authority.split(";");
6850                    p.info.authority = null;
6851                    for (int j = 0; j < names.length; j++) {
6852                        if (j == 1 && p.syncable) {
6853                            // We only want the first authority for a provider to possibly be
6854                            // syncable, so if we already added this provider using a different
6855                            // authority clear the syncable flag. We copy the provider before
6856                            // changing it because the mProviders object contains a reference
6857                            // to a provider that we don't want to change.
6858                            // Only do this for the second authority since the resulting provider
6859                            // object can be the same for all future authorities for this provider.
6860                            p = new PackageParser.Provider(p);
6861                            p.syncable = false;
6862                        }
6863                        if (!mProvidersByAuthority.containsKey(names[j])) {
6864                            mProvidersByAuthority.put(names[j], p);
6865                            if (p.info.authority == null) {
6866                                p.info.authority = names[j];
6867                            } else {
6868                                p.info.authority = p.info.authority + ";" + names[j];
6869                            }
6870                            if (DEBUG_PACKAGE_SCANNING) {
6871                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6872                                    Log.d(TAG, "Registered content provider: " + names[j]
6873                                            + ", className = " + p.info.name + ", isSyncable = "
6874                                            + p.info.isSyncable);
6875                            }
6876                        } else {
6877                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6878                            Slog.w(TAG, "Skipping provider name " + names[j] +
6879                                    " (in package " + pkg.applicationInfo.packageName +
6880                                    "): name already used by "
6881                                    + ((other != null && other.getComponentName() != null)
6882                                            ? other.getComponentName().getPackageName() : "?"));
6883                        }
6884                    }
6885                }
6886                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6887                    if (r == null) {
6888                        r = new StringBuilder(256);
6889                    } else {
6890                        r.append(' ');
6891                    }
6892                    r.append(p.info.name);
6893                }
6894            }
6895            if (r != null) {
6896                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
6897            }
6898
6899            N = pkg.services.size();
6900            r = null;
6901            for (i=0; i<N; i++) {
6902                PackageParser.Service s = pkg.services.get(i);
6903                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
6904                        s.info.processName, pkg.applicationInfo.uid);
6905                mServices.addService(s);
6906                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6907                    if (r == null) {
6908                        r = new StringBuilder(256);
6909                    } else {
6910                        r.append(' ');
6911                    }
6912                    r.append(s.info.name);
6913                }
6914            }
6915            if (r != null) {
6916                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
6917            }
6918
6919            N = pkg.receivers.size();
6920            r = null;
6921            for (i=0; i<N; i++) {
6922                PackageParser.Activity a = pkg.receivers.get(i);
6923                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6924                        a.info.processName, pkg.applicationInfo.uid);
6925                mReceivers.addActivity(a, "receiver");
6926                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6927                    if (r == null) {
6928                        r = new StringBuilder(256);
6929                    } else {
6930                        r.append(' ');
6931                    }
6932                    r.append(a.info.name);
6933                }
6934            }
6935            if (r != null) {
6936                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
6937            }
6938
6939            N = pkg.activities.size();
6940            r = null;
6941            for (i=0; i<N; i++) {
6942                PackageParser.Activity a = pkg.activities.get(i);
6943                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6944                        a.info.processName, pkg.applicationInfo.uid);
6945                mActivities.addActivity(a, "activity");
6946                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6947                    if (r == null) {
6948                        r = new StringBuilder(256);
6949                    } else {
6950                        r.append(' ');
6951                    }
6952                    r.append(a.info.name);
6953                }
6954            }
6955            if (r != null) {
6956                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
6957            }
6958
6959            N = pkg.permissionGroups.size();
6960            r = null;
6961            for (i=0; i<N; i++) {
6962                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
6963                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
6964                if (cur == null) {
6965                    mPermissionGroups.put(pg.info.name, pg);
6966                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6967                        if (r == null) {
6968                            r = new StringBuilder(256);
6969                        } else {
6970                            r.append(' ');
6971                        }
6972                        r.append(pg.info.name);
6973                    }
6974                } else {
6975                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
6976                            + pg.info.packageName + " ignored: original from "
6977                            + cur.info.packageName);
6978                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6979                        if (r == null) {
6980                            r = new StringBuilder(256);
6981                        } else {
6982                            r.append(' ');
6983                        }
6984                        r.append("DUP:");
6985                        r.append(pg.info.name);
6986                    }
6987                }
6988            }
6989            if (r != null) {
6990                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
6991            }
6992
6993            N = pkg.permissions.size();
6994            r = null;
6995            for (i=0; i<N; i++) {
6996                PackageParser.Permission p = pkg.permissions.get(i);
6997
6998                // Now that permission groups have a special meaning, we ignore permission
6999                // groups for legacy apps to prevent unexpected behavior. In particular,
7000                // permissions for one app being granted to someone just becuase they happen
7001                // to be in a group defined by another app (before this had no implications).
7002                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7003                    p.group = mPermissionGroups.get(p.info.group);
7004                    // Warn for a permission in an unknown group.
7005                    if (p.info.group != null && p.group == null) {
7006                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7007                                + p.info.packageName + " in an unknown group " + p.info.group);
7008                    }
7009                }
7010
7011                ArrayMap<String, BasePermission> permissionMap =
7012                        p.tree ? mSettings.mPermissionTrees
7013                                : mSettings.mPermissions;
7014                BasePermission bp = permissionMap.get(p.info.name);
7015
7016                // Allow system apps to redefine non-system permissions
7017                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7018                    final boolean currentOwnerIsSystem = (bp.perm != null
7019                            && isSystemApp(bp.perm.owner));
7020                    if (isSystemApp(p.owner)) {
7021                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7022                            // It's a built-in permission and no owner, take ownership now
7023                            bp.packageSetting = pkgSetting;
7024                            bp.perm = p;
7025                            bp.uid = pkg.applicationInfo.uid;
7026                            bp.sourcePackage = p.info.packageName;
7027                        } else if (!currentOwnerIsSystem) {
7028                            String msg = "New decl " + p.owner + " of permission  "
7029                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7030                            reportSettingsProblem(Log.WARN, msg);
7031                            bp = null;
7032                        }
7033                    }
7034                }
7035
7036                if (bp == null) {
7037                    bp = new BasePermission(p.info.name, p.info.packageName,
7038                            BasePermission.TYPE_NORMAL);
7039                    permissionMap.put(p.info.name, bp);
7040                }
7041
7042                if (bp.perm == null) {
7043                    if (bp.sourcePackage == null
7044                            || bp.sourcePackage.equals(p.info.packageName)) {
7045                        BasePermission tree = findPermissionTreeLP(p.info.name);
7046                        if (tree == null
7047                                || tree.sourcePackage.equals(p.info.packageName)) {
7048                            bp.packageSetting = pkgSetting;
7049                            bp.perm = p;
7050                            bp.uid = pkg.applicationInfo.uid;
7051                            bp.sourcePackage = p.info.packageName;
7052                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7053                                if (r == null) {
7054                                    r = new StringBuilder(256);
7055                                } else {
7056                                    r.append(' ');
7057                                }
7058                                r.append(p.info.name);
7059                            }
7060                        } else {
7061                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7062                                    + p.info.packageName + " ignored: base tree "
7063                                    + tree.name + " is from package "
7064                                    + tree.sourcePackage);
7065                        }
7066                    } else {
7067                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7068                                + p.info.packageName + " ignored: original from "
7069                                + bp.sourcePackage);
7070                    }
7071                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7072                    if (r == null) {
7073                        r = new StringBuilder(256);
7074                    } else {
7075                        r.append(' ');
7076                    }
7077                    r.append("DUP:");
7078                    r.append(p.info.name);
7079                }
7080                if (bp.perm == p) {
7081                    bp.protectionLevel = p.info.protectionLevel;
7082                }
7083            }
7084
7085            if (r != null) {
7086                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7087            }
7088
7089            N = pkg.instrumentation.size();
7090            r = null;
7091            for (i=0; i<N; i++) {
7092                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7093                a.info.packageName = pkg.applicationInfo.packageName;
7094                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7095                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7096                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7097                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7098                a.info.dataDir = pkg.applicationInfo.dataDir;
7099
7100                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7101                // need other information about the application, like the ABI and what not ?
7102                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7103                mInstrumentation.put(a.getComponentName(), a);
7104                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7105                    if (r == null) {
7106                        r = new StringBuilder(256);
7107                    } else {
7108                        r.append(' ');
7109                    }
7110                    r.append(a.info.name);
7111                }
7112            }
7113            if (r != null) {
7114                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7115            }
7116
7117            if (pkg.protectedBroadcasts != null) {
7118                N = pkg.protectedBroadcasts.size();
7119                for (i=0; i<N; i++) {
7120                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7121                }
7122            }
7123
7124            pkgSetting.setTimeStamp(scanFileTime);
7125
7126            // Create idmap files for pairs of (packages, overlay packages).
7127            // Note: "android", ie framework-res.apk, is handled by native layers.
7128            if (pkg.mOverlayTarget != null) {
7129                // This is an overlay package.
7130                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7131                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7132                        mOverlays.put(pkg.mOverlayTarget,
7133                                new ArrayMap<String, PackageParser.Package>());
7134                    }
7135                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7136                    map.put(pkg.packageName, pkg);
7137                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7138                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7139                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7140                                "scanPackageLI failed to createIdmap");
7141                    }
7142                }
7143            } else if (mOverlays.containsKey(pkg.packageName) &&
7144                    !pkg.packageName.equals("android")) {
7145                // This is a regular package, with one or more known overlay packages.
7146                createIdmapsForPackageLI(pkg);
7147            }
7148        }
7149
7150        return pkg;
7151    }
7152
7153    /**
7154     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7155     * is derived purely on the basis of the contents of {@code scanFile} and
7156     * {@code cpuAbiOverride}.
7157     *
7158     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7159     */
7160    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7161                                 String cpuAbiOverride, boolean extractLibs)
7162            throws PackageManagerException {
7163        // TODO: We can probably be smarter about this stuff. For installed apps,
7164        // we can calculate this information at install time once and for all. For
7165        // system apps, we can probably assume that this information doesn't change
7166        // after the first boot scan. As things stand, we do lots of unnecessary work.
7167
7168        // Give ourselves some initial paths; we'll come back for another
7169        // pass once we've determined ABI below.
7170        setNativeLibraryPaths(pkg);
7171
7172        // We would never need to extract libs for forward-locked and external packages,
7173        // since the container service will do it for us. We shouldn't attempt to
7174        // extract libs from system app when it was not updated.
7175        if (pkg.isForwardLocked() || isExternal(pkg) ||
7176            (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) {
7177            extractLibs = false;
7178        }
7179
7180        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7181        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7182
7183        NativeLibraryHelper.Handle handle = null;
7184        try {
7185            handle = NativeLibraryHelper.Handle.create(scanFile);
7186            // TODO(multiArch): This can be null for apps that didn't go through the
7187            // usual installation process. We can calculate it again, like we
7188            // do during install time.
7189            //
7190            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7191            // unnecessary.
7192            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7193
7194            // Null out the abis so that they can be recalculated.
7195            pkg.applicationInfo.primaryCpuAbi = null;
7196            pkg.applicationInfo.secondaryCpuAbi = null;
7197            if (isMultiArch(pkg.applicationInfo)) {
7198                // Warn if we've set an abiOverride for multi-lib packages..
7199                // By definition, we need to copy both 32 and 64 bit libraries for
7200                // such packages.
7201                if (pkg.cpuAbiOverride != null
7202                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7203                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7204                }
7205
7206                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7207                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7208                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7209                    if (extractLibs) {
7210                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7211                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7212                                useIsaSpecificSubdirs);
7213                    } else {
7214                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7215                    }
7216                }
7217
7218                maybeThrowExceptionForMultiArchCopy(
7219                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7220
7221                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7222                    if (extractLibs) {
7223                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7224                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7225                                useIsaSpecificSubdirs);
7226                    } else {
7227                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7228                    }
7229                }
7230
7231                maybeThrowExceptionForMultiArchCopy(
7232                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7233
7234                if (abi64 >= 0) {
7235                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7236                }
7237
7238                if (abi32 >= 0) {
7239                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7240                    if (abi64 >= 0) {
7241                        pkg.applicationInfo.secondaryCpuAbi = abi;
7242                    } else {
7243                        pkg.applicationInfo.primaryCpuAbi = abi;
7244                    }
7245                }
7246            } else {
7247                String[] abiList = (cpuAbiOverride != null) ?
7248                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7249
7250                // Enable gross and lame hacks for apps that are built with old
7251                // SDK tools. We must scan their APKs for renderscript bitcode and
7252                // not launch them if it's present. Don't bother checking on devices
7253                // that don't have 64 bit support.
7254                boolean needsRenderScriptOverride = false;
7255                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7256                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7257                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7258                    needsRenderScriptOverride = true;
7259                }
7260
7261                final int copyRet;
7262                if (extractLibs) {
7263                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7264                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7265                } else {
7266                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7267                }
7268
7269                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7270                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7271                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7272                }
7273
7274                if (copyRet >= 0) {
7275                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7276                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7277                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7278                } else if (needsRenderScriptOverride) {
7279                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7280                }
7281            }
7282        } catch (IOException ioe) {
7283            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7284        } finally {
7285            IoUtils.closeQuietly(handle);
7286        }
7287
7288        // Now that we've calculated the ABIs and determined if it's an internal app,
7289        // we will go ahead and populate the nativeLibraryPath.
7290        setNativeLibraryPaths(pkg);
7291    }
7292
7293    /**
7294     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7295     * i.e, so that all packages can be run inside a single process if required.
7296     *
7297     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7298     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7299     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7300     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7301     * updating a package that belongs to a shared user.
7302     *
7303     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7304     * adds unnecessary complexity.
7305     */
7306    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7307            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
7308        String requiredInstructionSet = null;
7309        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7310            requiredInstructionSet = VMRuntime.getInstructionSet(
7311                     scannedPackage.applicationInfo.primaryCpuAbi);
7312        }
7313
7314        PackageSetting requirer = null;
7315        for (PackageSetting ps : packagesForUser) {
7316            // If packagesForUser contains scannedPackage, we skip it. This will happen
7317            // when scannedPackage is an update of an existing package. Without this check,
7318            // we will never be able to change the ABI of any package belonging to a shared
7319            // user, even if it's compatible with other packages.
7320            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7321                if (ps.primaryCpuAbiString == null) {
7322                    continue;
7323                }
7324
7325                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7326                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7327                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7328                    // this but there's not much we can do.
7329                    String errorMessage = "Instruction set mismatch, "
7330                            + ((requirer == null) ? "[caller]" : requirer)
7331                            + " requires " + requiredInstructionSet + " whereas " + ps
7332                            + " requires " + instructionSet;
7333                    Slog.w(TAG, errorMessage);
7334                }
7335
7336                if (requiredInstructionSet == null) {
7337                    requiredInstructionSet = instructionSet;
7338                    requirer = ps;
7339                }
7340            }
7341        }
7342
7343        if (requiredInstructionSet != null) {
7344            String adjustedAbi;
7345            if (requirer != null) {
7346                // requirer != null implies that either scannedPackage was null or that scannedPackage
7347                // did not require an ABI, in which case we have to adjust scannedPackage to match
7348                // the ABI of the set (which is the same as requirer's ABI)
7349                adjustedAbi = requirer.primaryCpuAbiString;
7350                if (scannedPackage != null) {
7351                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7352                }
7353            } else {
7354                // requirer == null implies that we're updating all ABIs in the set to
7355                // match scannedPackage.
7356                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7357            }
7358
7359            for (PackageSetting ps : packagesForUser) {
7360                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7361                    if (ps.primaryCpuAbiString != null) {
7362                        continue;
7363                    }
7364
7365                    ps.primaryCpuAbiString = adjustedAbi;
7366                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7367                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7368                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7369
7370                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
7371                                null /* instruction sets */, forceDexOpt, deferDexOpt, true);
7372                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7373                            ps.primaryCpuAbiString = null;
7374                            ps.pkg.applicationInfo.primaryCpuAbi = null;
7375                            return;
7376                        } else {
7377                            mInstaller.rmdex(ps.codePathString,
7378                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
7379                        }
7380                    }
7381                }
7382            }
7383        }
7384    }
7385
7386    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7387        synchronized (mPackages) {
7388            mResolverReplaced = true;
7389            // Set up information for custom user intent resolution activity.
7390            mResolveActivity.applicationInfo = pkg.applicationInfo;
7391            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7392            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7393            mResolveActivity.processName = pkg.applicationInfo.packageName;
7394            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7395            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7396                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7397            mResolveActivity.theme = 0;
7398            mResolveActivity.exported = true;
7399            mResolveActivity.enabled = true;
7400            mResolveInfo.activityInfo = mResolveActivity;
7401            mResolveInfo.priority = 0;
7402            mResolveInfo.preferredOrder = 0;
7403            mResolveInfo.match = 0;
7404            mResolveComponentName = mCustomResolverComponentName;
7405            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7406                    mResolveComponentName);
7407        }
7408    }
7409
7410    private static String calculateBundledApkRoot(final String codePathString) {
7411        final File codePath = new File(codePathString);
7412        final File codeRoot;
7413        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7414            codeRoot = Environment.getRootDirectory();
7415        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7416            codeRoot = Environment.getOemDirectory();
7417        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7418            codeRoot = Environment.getVendorDirectory();
7419        } else {
7420            // Unrecognized code path; take its top real segment as the apk root:
7421            // e.g. /something/app/blah.apk => /something
7422            try {
7423                File f = codePath.getCanonicalFile();
7424                File parent = f.getParentFile();    // non-null because codePath is a file
7425                File tmp;
7426                while ((tmp = parent.getParentFile()) != null) {
7427                    f = parent;
7428                    parent = tmp;
7429                }
7430                codeRoot = f;
7431                Slog.w(TAG, "Unrecognized code path "
7432                        + codePath + " - using " + codeRoot);
7433            } catch (IOException e) {
7434                // Can't canonicalize the code path -- shenanigans?
7435                Slog.w(TAG, "Can't canonicalize code path " + codePath);
7436                return Environment.getRootDirectory().getPath();
7437            }
7438        }
7439        return codeRoot.getPath();
7440    }
7441
7442    /**
7443     * Derive and set the location of native libraries for the given package,
7444     * which varies depending on where and how the package was installed.
7445     */
7446    private void setNativeLibraryPaths(PackageParser.Package pkg) {
7447        final ApplicationInfo info = pkg.applicationInfo;
7448        final String codePath = pkg.codePath;
7449        final File codeFile = new File(codePath);
7450        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7451        final boolean asecApp = info.isForwardLocked() || isExternal(info);
7452
7453        info.nativeLibraryRootDir = null;
7454        info.nativeLibraryRootRequiresIsa = false;
7455        info.nativeLibraryDir = null;
7456        info.secondaryNativeLibraryDir = null;
7457
7458        if (isApkFile(codeFile)) {
7459            // Monolithic install
7460            if (bundledApp) {
7461                // If "/system/lib64/apkname" exists, assume that is the per-package
7462                // native library directory to use; otherwise use "/system/lib/apkname".
7463                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
7464                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
7465                        getPrimaryInstructionSet(info));
7466
7467                // This is a bundled system app so choose the path based on the ABI.
7468                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
7469                // is just the default path.
7470                final String apkName = deriveCodePathName(codePath);
7471                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
7472                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
7473                        apkName).getAbsolutePath();
7474
7475                if (info.secondaryCpuAbi != null) {
7476                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7477                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7478                            secondaryLibDir, apkName).getAbsolutePath();
7479                }
7480            } else if (asecApp) {
7481                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
7482                        .getAbsolutePath();
7483            } else {
7484                final String apkName = deriveCodePathName(codePath);
7485                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
7486                        .getAbsolutePath();
7487            }
7488
7489            info.nativeLibraryRootRequiresIsa = false;
7490            info.nativeLibraryDir = info.nativeLibraryRootDir;
7491        } else {
7492            // Cluster install
7493            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7494            info.nativeLibraryRootRequiresIsa = true;
7495
7496            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7497                    getPrimaryInstructionSet(info)).getAbsolutePath();
7498
7499            if (info.secondaryCpuAbi != null) {
7500                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7501                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7502            }
7503        }
7504    }
7505
7506    /**
7507     * Calculate the abis and roots for a bundled app. These can uniquely
7508     * be determined from the contents of the system partition, i.e whether
7509     * it contains 64 or 32 bit shared libraries etc. We do not validate any
7510     * of this information, and instead assume that the system was built
7511     * sensibly.
7512     */
7513    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
7514                                           PackageSetting pkgSetting) {
7515        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
7516
7517        // If "/system/lib64/apkname" exists, assume that is the per-package
7518        // native library directory to use; otherwise use "/system/lib/apkname".
7519        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
7520        setBundledAppAbi(pkg, apkRoot, apkName);
7521        // pkgSetting might be null during rescan following uninstall of updates
7522        // to a bundled app, so accommodate that possibility.  The settings in
7523        // that case will be established later from the parsed package.
7524        //
7525        // If the settings aren't null, sync them up with what we've just derived.
7526        // note that apkRoot isn't stored in the package settings.
7527        if (pkgSetting != null) {
7528            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7529            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7530        }
7531    }
7532
7533    /**
7534     * Deduces the ABI of a bundled app and sets the relevant fields on the
7535     * parsed pkg object.
7536     *
7537     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
7538     *        under which system libraries are installed.
7539     * @param apkName the name of the installed package.
7540     */
7541    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7542        final File codeFile = new File(pkg.codePath);
7543
7544        final boolean has64BitLibs;
7545        final boolean has32BitLibs;
7546        if (isApkFile(codeFile)) {
7547            // Monolithic install
7548            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7549            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7550        } else {
7551            // Cluster install
7552            final File rootDir = new File(codeFile, LIB_DIR_NAME);
7553            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7554                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7555                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7556                has64BitLibs = (new File(rootDir, isa)).exists();
7557            } else {
7558                has64BitLibs = false;
7559            }
7560            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7561                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7562                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7563                has32BitLibs = (new File(rootDir, isa)).exists();
7564            } else {
7565                has32BitLibs = false;
7566            }
7567        }
7568
7569        if (has64BitLibs && !has32BitLibs) {
7570            // The package has 64 bit libs, but not 32 bit libs. Its primary
7571            // ABI should be 64 bit. We can safely assume here that the bundled
7572            // native libraries correspond to the most preferred ABI in the list.
7573
7574            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7575            pkg.applicationInfo.secondaryCpuAbi = null;
7576        } else if (has32BitLibs && !has64BitLibs) {
7577            // The package has 32 bit libs but not 64 bit libs. Its primary
7578            // ABI should be 32 bit.
7579
7580            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7581            pkg.applicationInfo.secondaryCpuAbi = null;
7582        } else if (has32BitLibs && has64BitLibs) {
7583            // The application has both 64 and 32 bit bundled libraries. We check
7584            // here that the app declares multiArch support, and warn if it doesn't.
7585            //
7586            // We will be lenient here and record both ABIs. The primary will be the
7587            // ABI that's higher on the list, i.e, a device that's configured to prefer
7588            // 64 bit apps will see a 64 bit primary ABI,
7589
7590            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
7591                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
7592            }
7593
7594            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
7595                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7596                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7597            } else {
7598                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7599                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7600            }
7601        } else {
7602            pkg.applicationInfo.primaryCpuAbi = null;
7603            pkg.applicationInfo.secondaryCpuAbi = null;
7604        }
7605    }
7606
7607    private void killApplication(String pkgName, int appId, String reason) {
7608        // Request the ActivityManager to kill the process(only for existing packages)
7609        // so that we do not end up in a confused state while the user is still using the older
7610        // version of the application while the new one gets installed.
7611        IActivityManager am = ActivityManagerNative.getDefault();
7612        if (am != null) {
7613            try {
7614                am.killApplicationWithAppId(pkgName, appId, reason);
7615            } catch (RemoteException e) {
7616            }
7617        }
7618    }
7619
7620    void removePackageLI(PackageSetting ps, boolean chatty) {
7621        if (DEBUG_INSTALL) {
7622            if (chatty)
7623                Log.d(TAG, "Removing package " + ps.name);
7624        }
7625
7626        // writer
7627        synchronized (mPackages) {
7628            mPackages.remove(ps.name);
7629            final PackageParser.Package pkg = ps.pkg;
7630            if (pkg != null) {
7631                cleanPackageDataStructuresLILPw(pkg, chatty);
7632            }
7633        }
7634    }
7635
7636    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
7637        if (DEBUG_INSTALL) {
7638            if (chatty)
7639                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
7640        }
7641
7642        // writer
7643        synchronized (mPackages) {
7644            mPackages.remove(pkg.applicationInfo.packageName);
7645            cleanPackageDataStructuresLILPw(pkg, chatty);
7646        }
7647    }
7648
7649    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
7650        int N = pkg.providers.size();
7651        StringBuilder r = null;
7652        int i;
7653        for (i=0; i<N; i++) {
7654            PackageParser.Provider p = pkg.providers.get(i);
7655            mProviders.removeProvider(p);
7656            if (p.info.authority == null) {
7657
7658                /* There was another ContentProvider with this authority when
7659                 * this app was installed so this authority is null,
7660                 * Ignore it as we don't have to unregister the provider.
7661                 */
7662                continue;
7663            }
7664            String names[] = p.info.authority.split(";");
7665            for (int j = 0; j < names.length; j++) {
7666                if (mProvidersByAuthority.get(names[j]) == p) {
7667                    mProvidersByAuthority.remove(names[j]);
7668                    if (DEBUG_REMOVE) {
7669                        if (chatty)
7670                            Log.d(TAG, "Unregistered content provider: " + names[j]
7671                                    + ", className = " + p.info.name + ", isSyncable = "
7672                                    + p.info.isSyncable);
7673                    }
7674                }
7675            }
7676            if (DEBUG_REMOVE && chatty) {
7677                if (r == null) {
7678                    r = new StringBuilder(256);
7679                } else {
7680                    r.append(' ');
7681                }
7682                r.append(p.info.name);
7683            }
7684        }
7685        if (r != null) {
7686            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
7687        }
7688
7689        N = pkg.services.size();
7690        r = null;
7691        for (i=0; i<N; i++) {
7692            PackageParser.Service s = pkg.services.get(i);
7693            mServices.removeService(s);
7694            if (chatty) {
7695                if (r == null) {
7696                    r = new StringBuilder(256);
7697                } else {
7698                    r.append(' ');
7699                }
7700                r.append(s.info.name);
7701            }
7702        }
7703        if (r != null) {
7704            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
7705        }
7706
7707        N = pkg.receivers.size();
7708        r = null;
7709        for (i=0; i<N; i++) {
7710            PackageParser.Activity a = pkg.receivers.get(i);
7711            mReceivers.removeActivity(a, "receiver");
7712            if (DEBUG_REMOVE && chatty) {
7713                if (r == null) {
7714                    r = new StringBuilder(256);
7715                } else {
7716                    r.append(' ');
7717                }
7718                r.append(a.info.name);
7719            }
7720        }
7721        if (r != null) {
7722            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
7723        }
7724
7725        N = pkg.activities.size();
7726        r = null;
7727        for (i=0; i<N; i++) {
7728            PackageParser.Activity a = pkg.activities.get(i);
7729            mActivities.removeActivity(a, "activity");
7730            if (DEBUG_REMOVE && chatty) {
7731                if (r == null) {
7732                    r = new StringBuilder(256);
7733                } else {
7734                    r.append(' ');
7735                }
7736                r.append(a.info.name);
7737            }
7738        }
7739        if (r != null) {
7740            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
7741        }
7742
7743        N = pkg.permissions.size();
7744        r = null;
7745        for (i=0; i<N; i++) {
7746            PackageParser.Permission p = pkg.permissions.get(i);
7747            BasePermission bp = mSettings.mPermissions.get(p.info.name);
7748            if (bp == null) {
7749                bp = mSettings.mPermissionTrees.get(p.info.name);
7750            }
7751            if (bp != null && bp.perm == p) {
7752                bp.perm = null;
7753                if (DEBUG_REMOVE && chatty) {
7754                    if (r == null) {
7755                        r = new StringBuilder(256);
7756                    } else {
7757                        r.append(' ');
7758                    }
7759                    r.append(p.info.name);
7760                }
7761            }
7762            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7763                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
7764                if (appOpPerms != null) {
7765                    appOpPerms.remove(pkg.packageName);
7766                }
7767            }
7768        }
7769        if (r != null) {
7770            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
7771        }
7772
7773        N = pkg.requestedPermissions.size();
7774        r = null;
7775        for (i=0; i<N; i++) {
7776            String perm = pkg.requestedPermissions.get(i);
7777            BasePermission bp = mSettings.mPermissions.get(perm);
7778            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7779                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
7780                if (appOpPerms != null) {
7781                    appOpPerms.remove(pkg.packageName);
7782                    if (appOpPerms.isEmpty()) {
7783                        mAppOpPermissionPackages.remove(perm);
7784                    }
7785                }
7786            }
7787        }
7788        if (r != null) {
7789            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
7790        }
7791
7792        N = pkg.instrumentation.size();
7793        r = null;
7794        for (i=0; i<N; i++) {
7795            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7796            mInstrumentation.remove(a.getComponentName());
7797            if (DEBUG_REMOVE && chatty) {
7798                if (r == null) {
7799                    r = new StringBuilder(256);
7800                } else {
7801                    r.append(' ');
7802                }
7803                r.append(a.info.name);
7804            }
7805        }
7806        if (r != null) {
7807            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
7808        }
7809
7810        r = null;
7811        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7812            // Only system apps can hold shared libraries.
7813            if (pkg.libraryNames != null) {
7814                for (i=0; i<pkg.libraryNames.size(); i++) {
7815                    String name = pkg.libraryNames.get(i);
7816                    SharedLibraryEntry cur = mSharedLibraries.get(name);
7817                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
7818                        mSharedLibraries.remove(name);
7819                        if (DEBUG_REMOVE && chatty) {
7820                            if (r == null) {
7821                                r = new StringBuilder(256);
7822                            } else {
7823                                r.append(' ');
7824                            }
7825                            r.append(name);
7826                        }
7827                    }
7828                }
7829            }
7830        }
7831        if (r != null) {
7832            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
7833        }
7834    }
7835
7836    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
7837        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
7838            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
7839                return true;
7840            }
7841        }
7842        return false;
7843    }
7844
7845    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
7846    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
7847    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
7848
7849    private void updatePermissionsLPw(String changingPkg,
7850            PackageParser.Package pkgInfo, int flags) {
7851        // Make sure there are no dangling permission trees.
7852        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
7853        while (it.hasNext()) {
7854            final BasePermission bp = it.next();
7855            if (bp.packageSetting == null) {
7856                // We may not yet have parsed the package, so just see if
7857                // we still know about its settings.
7858                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
7859            }
7860            if (bp.packageSetting == null) {
7861                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
7862                        + " from package " + bp.sourcePackage);
7863                it.remove();
7864            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
7865                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
7866                    Slog.i(TAG, "Removing old permission tree: " + bp.name
7867                            + " from package " + bp.sourcePackage);
7868                    flags |= UPDATE_PERMISSIONS_ALL;
7869                    it.remove();
7870                }
7871            }
7872        }
7873
7874        // Make sure all dynamic permissions have been assigned to a package,
7875        // and make sure there are no dangling permissions.
7876        it = mSettings.mPermissions.values().iterator();
7877        while (it.hasNext()) {
7878            final BasePermission bp = it.next();
7879            if (bp.type == BasePermission.TYPE_DYNAMIC) {
7880                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
7881                        + bp.name + " pkg=" + bp.sourcePackage
7882                        + " info=" + bp.pendingInfo);
7883                if (bp.packageSetting == null && bp.pendingInfo != null) {
7884                    final BasePermission tree = findPermissionTreeLP(bp.name);
7885                    if (tree != null && tree.perm != null) {
7886                        bp.packageSetting = tree.packageSetting;
7887                        bp.perm = new PackageParser.Permission(tree.perm.owner,
7888                                new PermissionInfo(bp.pendingInfo));
7889                        bp.perm.info.packageName = tree.perm.info.packageName;
7890                        bp.perm.info.name = bp.name;
7891                        bp.uid = tree.uid;
7892                    }
7893                }
7894            }
7895            if (bp.packageSetting == null) {
7896                // We may not yet have parsed the package, so just see if
7897                // we still know about its settings.
7898                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
7899            }
7900            if (bp.packageSetting == null) {
7901                Slog.w(TAG, "Removing dangling permission: " + bp.name
7902                        + " from package " + bp.sourcePackage);
7903                it.remove();
7904            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
7905                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
7906                    Slog.i(TAG, "Removing old permission: " + bp.name
7907                            + " from package " + bp.sourcePackage);
7908                    flags |= UPDATE_PERMISSIONS_ALL;
7909                    it.remove();
7910                }
7911            }
7912        }
7913
7914        // Now update the permissions for all packages, in particular
7915        // replace the granted permissions of the system packages.
7916        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
7917            for (PackageParser.Package pkg : mPackages.values()) {
7918                if (pkg != pkgInfo) {
7919                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
7920                            changingPkg);
7921                }
7922            }
7923        }
7924
7925        if (pkgInfo != null) {
7926            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
7927        }
7928    }
7929
7930    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
7931            String packageOfInterest) {
7932        // IMPORTANT: There are two types of permissions: install and runtime.
7933        // Install time permissions are granted when the app is installed to
7934        // all device users and users added in the future. Runtime permissions
7935        // are granted at runtime explicitly to specific users. Normal and signature
7936        // protected permissions are install time permissions. Dangerous permissions
7937        // are install permissions if the app's target SDK is Lollipop MR1 or older,
7938        // otherwise they are runtime permissions. This function does not manage
7939        // runtime permissions except for the case an app targeting Lollipop MR1
7940        // being upgraded to target a newer SDK, in which case dangerous permissions
7941        // are transformed from install time to runtime ones.
7942
7943        final PackageSetting ps = (PackageSetting) pkg.mExtras;
7944        if (ps == null) {
7945            return;
7946        }
7947
7948        PermissionsState permissionsState = ps.getPermissionsState();
7949        PermissionsState origPermissions = permissionsState;
7950
7951        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
7952
7953        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
7954
7955        boolean changedInstallPermission = false;
7956
7957        if (replace) {
7958            ps.installPermissionsFixed = false;
7959            if (!ps.isSharedUser()) {
7960                origPermissions = new PermissionsState(permissionsState);
7961                permissionsState.reset();
7962            }
7963        }
7964
7965        permissionsState.setGlobalGids(mGlobalGids);
7966
7967        final int N = pkg.requestedPermissions.size();
7968        for (int i=0; i<N; i++) {
7969            final String name = pkg.requestedPermissions.get(i);
7970            final BasePermission bp = mSettings.mPermissions.get(name);
7971
7972            if (DEBUG_INSTALL) {
7973                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
7974            }
7975
7976            if (bp == null || bp.packageSetting == null) {
7977                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7978                    Slog.w(TAG, "Unknown permission " + name
7979                            + " in package " + pkg.packageName);
7980                }
7981                continue;
7982            }
7983
7984            final String perm = bp.name;
7985            boolean allowedSig = false;
7986            int grant = GRANT_DENIED;
7987
7988            // Keep track of app op permissions.
7989            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7990                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
7991                if (pkgs == null) {
7992                    pkgs = new ArraySet<>();
7993                    mAppOpPermissionPackages.put(bp.name, pkgs);
7994                }
7995                pkgs.add(pkg.packageName);
7996            }
7997
7998            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
7999            switch (level) {
8000                case PermissionInfo.PROTECTION_NORMAL: {
8001                    // For all apps normal permissions are install time ones.
8002                    grant = GRANT_INSTALL;
8003                } break;
8004
8005                case PermissionInfo.PROTECTION_DANGEROUS: {
8006                    if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
8007                        // For legacy apps dangerous permissions are install time ones.
8008                        grant = GRANT_INSTALL_LEGACY;
8009                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8010                        // For legacy apps that became modern, install becomes runtime.
8011                        grant = GRANT_UPGRADE;
8012                    } else {
8013                        // For modern apps keep runtime permissions unchanged.
8014                        grant = GRANT_RUNTIME;
8015                    }
8016                } break;
8017
8018                case PermissionInfo.PROTECTION_SIGNATURE: {
8019                    // For all apps signature permissions are install time ones.
8020                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8021                    if (allowedSig) {
8022                        grant = GRANT_INSTALL;
8023                    }
8024                } break;
8025            }
8026
8027            if (DEBUG_INSTALL) {
8028                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8029            }
8030
8031            if (grant != GRANT_DENIED) {
8032                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8033                    // If this is an existing, non-system package, then
8034                    // we can't add any new permissions to it.
8035                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8036                        // Except...  if this is a permission that was added
8037                        // to the platform (note: need to only do this when
8038                        // updating the platform).
8039                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8040                            grant = GRANT_DENIED;
8041                        }
8042                    }
8043                }
8044
8045                switch (grant) {
8046                    case GRANT_INSTALL: {
8047                        // Revoke this as runtime permission to handle the case of
8048                        // a runtime permission being downgraded to an install one.
8049                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8050                            if (origPermissions.getRuntimePermissionState(
8051                                    bp.name, userId) != null) {
8052                                // Revoke the runtime permission and clear the flags.
8053                                origPermissions.revokeRuntimePermission(bp, userId);
8054                                origPermissions.updatePermissionFlags(bp, userId,
8055                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8056                                // If we revoked a permission permission, we have to write.
8057                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8058                                        changedRuntimePermissionUserIds, userId);
8059                            }
8060                        }
8061                        // Grant an install permission.
8062                        if (permissionsState.grantInstallPermission(bp) !=
8063                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8064                            changedInstallPermission = true;
8065                        }
8066                    } break;
8067
8068                    case GRANT_INSTALL_LEGACY: {
8069                        // Grant an install permission.
8070                        if (permissionsState.grantInstallPermission(bp) !=
8071                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8072                            changedInstallPermission = true;
8073                        }
8074                    } break;
8075
8076                    case GRANT_RUNTIME: {
8077                        // Grant previously granted runtime permissions.
8078                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8079                            PermissionState permissionState = origPermissions
8080                                    .getRuntimePermissionState(bp.name, userId);
8081                            final int flags = permissionState != null
8082                                    ? permissionState.getFlags() : 0;
8083                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8084                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8085                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8086                                    // If we cannot put the permission as it was, we have to write.
8087                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8088                                            changedRuntimePermissionUserIds, userId);
8089                                }
8090                            }
8091                            // Propagate the permission flags.
8092                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8093                        }
8094                    } break;
8095
8096                    case GRANT_UPGRADE: {
8097                        // Grant runtime permissions for a previously held install permission.
8098                        PermissionState permissionState = origPermissions
8099                                .getInstallPermissionState(bp.name);
8100                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8101
8102                        if (origPermissions.revokeInstallPermission(bp)
8103                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8104                            // We will be transferring the permission flags, so clear them.
8105                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8106                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8107                            changedInstallPermission = true;
8108                        }
8109
8110                        // If the permission is not to be promoted to runtime we ignore it and
8111                        // also its other flags as they are not applicable to install permissions.
8112                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8113                            for (int userId : currentUserIds) {
8114                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8115                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8116                                    // Transfer the permission flags.
8117                                    permissionsState.updatePermissionFlags(bp, userId,
8118                                            flags, flags);
8119                                    // If we granted the permission, we have to write.
8120                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8121                                            changedRuntimePermissionUserIds, userId);
8122                                }
8123                            }
8124                        }
8125                    } break;
8126
8127                    default: {
8128                        if (packageOfInterest == null
8129                                || packageOfInterest.equals(pkg.packageName)) {
8130                            Slog.w(TAG, "Not granting permission " + perm
8131                                    + " to package " + pkg.packageName
8132                                    + " because it was previously installed without");
8133                        }
8134                    } break;
8135                }
8136            } else {
8137                if (permissionsState.revokeInstallPermission(bp) !=
8138                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8139                    // Also drop the permission flags.
8140                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8141                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8142                    changedInstallPermission = true;
8143                    Slog.i(TAG, "Un-granting permission " + perm
8144                            + " from package " + pkg.packageName
8145                            + " (protectionLevel=" + bp.protectionLevel
8146                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8147                            + ")");
8148                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8149                    // Don't print warning for app op permissions, since it is fine for them
8150                    // not to be granted, there is a UI for the user to decide.
8151                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8152                        Slog.w(TAG, "Not granting permission " + perm
8153                                + " to package " + pkg.packageName
8154                                + " (protectionLevel=" + bp.protectionLevel
8155                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8156                                + ")");
8157                    }
8158                }
8159            }
8160        }
8161
8162        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8163                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8164            // This is the first that we have heard about this package, so the
8165            // permissions we have now selected are fixed until explicitly
8166            // changed.
8167            ps.installPermissionsFixed = true;
8168        }
8169
8170        // Persist the runtime permissions state for users with changes.
8171        for (int userId : changedRuntimePermissionUserIds) {
8172            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
8173        }
8174    }
8175
8176    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8177        boolean allowed = false;
8178        final int NP = PackageParser.NEW_PERMISSIONS.length;
8179        for (int ip=0; ip<NP; ip++) {
8180            final PackageParser.NewPermissionInfo npi
8181                    = PackageParser.NEW_PERMISSIONS[ip];
8182            if (npi.name.equals(perm)
8183                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8184                allowed = true;
8185                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8186                        + pkg.packageName);
8187                break;
8188            }
8189        }
8190        return allowed;
8191    }
8192
8193    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8194            BasePermission bp, PermissionsState origPermissions) {
8195        boolean allowed;
8196        allowed = (compareSignatures(
8197                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8198                        == PackageManager.SIGNATURE_MATCH)
8199                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8200                        == PackageManager.SIGNATURE_MATCH);
8201        if (!allowed && (bp.protectionLevel
8202                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
8203            if (isSystemApp(pkg)) {
8204                // For updated system applications, a system permission
8205                // is granted only if it had been defined by the original application.
8206                if (pkg.isUpdatedSystemApp()) {
8207                    final PackageSetting sysPs = mSettings
8208                            .getDisabledSystemPkgLPr(pkg.packageName);
8209                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8210                        // If the original was granted this permission, we take
8211                        // that grant decision as read and propagate it to the
8212                        // update.
8213                        if (sysPs.isPrivileged()) {
8214                            allowed = true;
8215                        }
8216                    } else {
8217                        // The system apk may have been updated with an older
8218                        // version of the one on the data partition, but which
8219                        // granted a new system permission that it didn't have
8220                        // before.  In this case we do want to allow the app to
8221                        // now get the new permission if the ancestral apk is
8222                        // privileged to get it.
8223                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
8224                            for (int j=0;
8225                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
8226                                if (perm.equals(
8227                                        sysPs.pkg.requestedPermissions.get(j))) {
8228                                    allowed = true;
8229                                    break;
8230                                }
8231                            }
8232                        }
8233                    }
8234                } else {
8235                    allowed = isPrivilegedApp(pkg);
8236                }
8237            }
8238        }
8239        if (!allowed && (bp.protectionLevel
8240                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8241            // For development permissions, a development permission
8242            // is granted only if it was already granted.
8243            allowed = origPermissions.hasInstallPermission(perm);
8244        }
8245        return allowed;
8246    }
8247
8248    final class ActivityIntentResolver
8249            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8250        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8251                boolean defaultOnly, int userId) {
8252            if (!sUserManager.exists(userId)) return null;
8253            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8254            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8255        }
8256
8257        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8258                int userId) {
8259            if (!sUserManager.exists(userId)) return null;
8260            mFlags = flags;
8261            return super.queryIntent(intent, resolvedType,
8262                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8263        }
8264
8265        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8266                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8267            if (!sUserManager.exists(userId)) return null;
8268            if (packageActivities == null) {
8269                return null;
8270            }
8271            mFlags = flags;
8272            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8273            final int N = packageActivities.size();
8274            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8275                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8276
8277            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8278            for (int i = 0; i < N; ++i) {
8279                intentFilters = packageActivities.get(i).intents;
8280                if (intentFilters != null && intentFilters.size() > 0) {
8281                    PackageParser.ActivityIntentInfo[] array =
8282                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
8283                    intentFilters.toArray(array);
8284                    listCut.add(array);
8285                }
8286            }
8287            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8288        }
8289
8290        public final void addActivity(PackageParser.Activity a, String type) {
8291            final boolean systemApp = a.info.applicationInfo.isSystemApp();
8292            mActivities.put(a.getComponentName(), a);
8293            if (DEBUG_SHOW_INFO)
8294                Log.v(
8295                TAG, "  " + type + " " +
8296                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8297            if (DEBUG_SHOW_INFO)
8298                Log.v(TAG, "    Class=" + a.info.name);
8299            final int NI = a.intents.size();
8300            for (int j=0; j<NI; j++) {
8301                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8302                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
8303                    intent.setPriority(0);
8304                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
8305                            + a.className + " with priority > 0, forcing to 0");
8306                }
8307                if (DEBUG_SHOW_INFO) {
8308                    Log.v(TAG, "    IntentFilter:");
8309                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8310                }
8311                if (!intent.debugCheck()) {
8312                    Log.w(TAG, "==> For Activity " + a.info.name);
8313                }
8314                addFilter(intent);
8315            }
8316        }
8317
8318        public final void removeActivity(PackageParser.Activity a, String type) {
8319            mActivities.remove(a.getComponentName());
8320            if (DEBUG_SHOW_INFO) {
8321                Log.v(TAG, "  " + type + " "
8322                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
8323                                : a.info.name) + ":");
8324                Log.v(TAG, "    Class=" + a.info.name);
8325            }
8326            final int NI = a.intents.size();
8327            for (int j=0; j<NI; j++) {
8328                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8329                if (DEBUG_SHOW_INFO) {
8330                    Log.v(TAG, "    IntentFilter:");
8331                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8332                }
8333                removeFilter(intent);
8334            }
8335        }
8336
8337        @Override
8338        protected boolean allowFilterResult(
8339                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
8340            ActivityInfo filterAi = filter.activity.info;
8341            for (int i=dest.size()-1; i>=0; i--) {
8342                ActivityInfo destAi = dest.get(i).activityInfo;
8343                if (destAi.name == filterAi.name
8344                        && destAi.packageName == filterAi.packageName) {
8345                    return false;
8346                }
8347            }
8348            return true;
8349        }
8350
8351        @Override
8352        protected ActivityIntentInfo[] newArray(int size) {
8353            return new ActivityIntentInfo[size];
8354        }
8355
8356        @Override
8357        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
8358            if (!sUserManager.exists(userId)) return true;
8359            PackageParser.Package p = filter.activity.owner;
8360            if (p != null) {
8361                PackageSetting ps = (PackageSetting)p.mExtras;
8362                if (ps != null) {
8363                    // System apps are never considered stopped for purposes of
8364                    // filtering, because there may be no way for the user to
8365                    // actually re-launch them.
8366                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
8367                            && ps.getStopped(userId);
8368                }
8369            }
8370            return false;
8371        }
8372
8373        @Override
8374        protected boolean isPackageForFilter(String packageName,
8375                PackageParser.ActivityIntentInfo info) {
8376            return packageName.equals(info.activity.owner.packageName);
8377        }
8378
8379        @Override
8380        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
8381                int match, int userId) {
8382            if (!sUserManager.exists(userId)) return null;
8383            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
8384                return null;
8385            }
8386            final PackageParser.Activity activity = info.activity;
8387            if (mSafeMode && (activity.info.applicationInfo.flags
8388                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8389                return null;
8390            }
8391            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
8392            if (ps == null) {
8393                return null;
8394            }
8395            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
8396                    ps.readUserState(userId), userId);
8397            if (ai == null) {
8398                return null;
8399            }
8400            final ResolveInfo res = new ResolveInfo();
8401            res.activityInfo = ai;
8402            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8403                res.filter = info;
8404            }
8405            if (info != null) {
8406                res.handleAllWebDataURI = info.handleAllWebDataURI();
8407            }
8408            res.priority = info.getPriority();
8409            res.preferredOrder = activity.owner.mPreferredOrder;
8410            //System.out.println("Result: " + res.activityInfo.className +
8411            //                   " = " + res.priority);
8412            res.match = match;
8413            res.isDefault = info.hasDefault;
8414            res.labelRes = info.labelRes;
8415            res.nonLocalizedLabel = info.nonLocalizedLabel;
8416            if (userNeedsBadging(userId)) {
8417                res.noResourceId = true;
8418            } else {
8419                res.icon = info.icon;
8420            }
8421            res.iconResourceId = info.icon;
8422            res.system = res.activityInfo.applicationInfo.isSystemApp();
8423            return res;
8424        }
8425
8426        @Override
8427        protected void sortResults(List<ResolveInfo> results) {
8428            Collections.sort(results, mResolvePrioritySorter);
8429        }
8430
8431        @Override
8432        protected void dumpFilter(PrintWriter out, String prefix,
8433                PackageParser.ActivityIntentInfo filter) {
8434            out.print(prefix); out.print(
8435                    Integer.toHexString(System.identityHashCode(filter.activity)));
8436                    out.print(' ');
8437                    filter.activity.printComponentShortName(out);
8438                    out.print(" filter ");
8439                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8440        }
8441
8442        @Override
8443        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
8444            return filter.activity;
8445        }
8446
8447        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8448            PackageParser.Activity activity = (PackageParser.Activity)label;
8449            out.print(prefix); out.print(
8450                    Integer.toHexString(System.identityHashCode(activity)));
8451                    out.print(' ');
8452                    activity.printComponentShortName(out);
8453            if (count > 1) {
8454                out.print(" ("); out.print(count); out.print(" filters)");
8455            }
8456            out.println();
8457        }
8458
8459//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8460//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8461//            final List<ResolveInfo> retList = Lists.newArrayList();
8462//            while (i.hasNext()) {
8463//                final ResolveInfo resolveInfo = i.next();
8464//                if (isEnabledLP(resolveInfo.activityInfo)) {
8465//                    retList.add(resolveInfo);
8466//                }
8467//            }
8468//            return retList;
8469//        }
8470
8471        // Keys are String (activity class name), values are Activity.
8472        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
8473                = new ArrayMap<ComponentName, PackageParser.Activity>();
8474        private int mFlags;
8475    }
8476
8477    private final class ServiceIntentResolver
8478            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
8479        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8480                boolean defaultOnly, int userId) {
8481            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8482            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8483        }
8484
8485        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8486                int userId) {
8487            if (!sUserManager.exists(userId)) return null;
8488            mFlags = flags;
8489            return super.queryIntent(intent, resolvedType,
8490                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8491        }
8492
8493        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8494                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
8495            if (!sUserManager.exists(userId)) return null;
8496            if (packageServices == null) {
8497                return null;
8498            }
8499            mFlags = flags;
8500            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8501            final int N = packageServices.size();
8502            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
8503                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
8504
8505            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
8506            for (int i = 0; i < N; ++i) {
8507                intentFilters = packageServices.get(i).intents;
8508                if (intentFilters != null && intentFilters.size() > 0) {
8509                    PackageParser.ServiceIntentInfo[] array =
8510                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
8511                    intentFilters.toArray(array);
8512                    listCut.add(array);
8513                }
8514            }
8515            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8516        }
8517
8518        public final void addService(PackageParser.Service s) {
8519            mServices.put(s.getComponentName(), s);
8520            if (DEBUG_SHOW_INFO) {
8521                Log.v(TAG, "  "
8522                        + (s.info.nonLocalizedLabel != null
8523                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8524                Log.v(TAG, "    Class=" + s.info.name);
8525            }
8526            final int NI = s.intents.size();
8527            int j;
8528            for (j=0; j<NI; j++) {
8529                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8530                if (DEBUG_SHOW_INFO) {
8531                    Log.v(TAG, "    IntentFilter:");
8532                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8533                }
8534                if (!intent.debugCheck()) {
8535                    Log.w(TAG, "==> For Service " + s.info.name);
8536                }
8537                addFilter(intent);
8538            }
8539        }
8540
8541        public final void removeService(PackageParser.Service s) {
8542            mServices.remove(s.getComponentName());
8543            if (DEBUG_SHOW_INFO) {
8544                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
8545                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8546                Log.v(TAG, "    Class=" + s.info.name);
8547            }
8548            final int NI = s.intents.size();
8549            int j;
8550            for (j=0; j<NI; j++) {
8551                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8552                if (DEBUG_SHOW_INFO) {
8553                    Log.v(TAG, "    IntentFilter:");
8554                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8555                }
8556                removeFilter(intent);
8557            }
8558        }
8559
8560        @Override
8561        protected boolean allowFilterResult(
8562                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
8563            ServiceInfo filterSi = filter.service.info;
8564            for (int i=dest.size()-1; i>=0; i--) {
8565                ServiceInfo destAi = dest.get(i).serviceInfo;
8566                if (destAi.name == filterSi.name
8567                        && destAi.packageName == filterSi.packageName) {
8568                    return false;
8569                }
8570            }
8571            return true;
8572        }
8573
8574        @Override
8575        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
8576            return new PackageParser.ServiceIntentInfo[size];
8577        }
8578
8579        @Override
8580        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
8581            if (!sUserManager.exists(userId)) return true;
8582            PackageParser.Package p = filter.service.owner;
8583            if (p != null) {
8584                PackageSetting ps = (PackageSetting)p.mExtras;
8585                if (ps != null) {
8586                    // System apps are never considered stopped for purposes of
8587                    // filtering, because there may be no way for the user to
8588                    // actually re-launch them.
8589                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8590                            && ps.getStopped(userId);
8591                }
8592            }
8593            return false;
8594        }
8595
8596        @Override
8597        protected boolean isPackageForFilter(String packageName,
8598                PackageParser.ServiceIntentInfo info) {
8599            return packageName.equals(info.service.owner.packageName);
8600        }
8601
8602        @Override
8603        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
8604                int match, int userId) {
8605            if (!sUserManager.exists(userId)) return null;
8606            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
8607            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
8608                return null;
8609            }
8610            final PackageParser.Service service = info.service;
8611            if (mSafeMode && (service.info.applicationInfo.flags
8612                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8613                return null;
8614            }
8615            PackageSetting ps = (PackageSetting) service.owner.mExtras;
8616            if (ps == null) {
8617                return null;
8618            }
8619            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
8620                    ps.readUserState(userId), userId);
8621            if (si == null) {
8622                return null;
8623            }
8624            final ResolveInfo res = new ResolveInfo();
8625            res.serviceInfo = si;
8626            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8627                res.filter = filter;
8628            }
8629            res.priority = info.getPriority();
8630            res.preferredOrder = service.owner.mPreferredOrder;
8631            res.match = match;
8632            res.isDefault = info.hasDefault;
8633            res.labelRes = info.labelRes;
8634            res.nonLocalizedLabel = info.nonLocalizedLabel;
8635            res.icon = info.icon;
8636            res.system = res.serviceInfo.applicationInfo.isSystemApp();
8637            return res;
8638        }
8639
8640        @Override
8641        protected void sortResults(List<ResolveInfo> results) {
8642            Collections.sort(results, mResolvePrioritySorter);
8643        }
8644
8645        @Override
8646        protected void dumpFilter(PrintWriter out, String prefix,
8647                PackageParser.ServiceIntentInfo filter) {
8648            out.print(prefix); out.print(
8649                    Integer.toHexString(System.identityHashCode(filter.service)));
8650                    out.print(' ');
8651                    filter.service.printComponentShortName(out);
8652                    out.print(" filter ");
8653                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8654        }
8655
8656        @Override
8657        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
8658            return filter.service;
8659        }
8660
8661        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8662            PackageParser.Service service = (PackageParser.Service)label;
8663            out.print(prefix); out.print(
8664                    Integer.toHexString(System.identityHashCode(service)));
8665                    out.print(' ');
8666                    service.printComponentShortName(out);
8667            if (count > 1) {
8668                out.print(" ("); out.print(count); out.print(" filters)");
8669            }
8670            out.println();
8671        }
8672
8673//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8674//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8675//            final List<ResolveInfo> retList = Lists.newArrayList();
8676//            while (i.hasNext()) {
8677//                final ResolveInfo resolveInfo = (ResolveInfo) i;
8678//                if (isEnabledLP(resolveInfo.serviceInfo)) {
8679//                    retList.add(resolveInfo);
8680//                }
8681//            }
8682//            return retList;
8683//        }
8684
8685        // Keys are String (activity class name), values are Activity.
8686        private final ArrayMap<ComponentName, PackageParser.Service> mServices
8687                = new ArrayMap<ComponentName, PackageParser.Service>();
8688        private int mFlags;
8689    };
8690
8691    private final class ProviderIntentResolver
8692            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
8693        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8694                boolean defaultOnly, int userId) {
8695            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8696            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8697        }
8698
8699        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8700                int userId) {
8701            if (!sUserManager.exists(userId))
8702                return null;
8703            mFlags = flags;
8704            return super.queryIntent(intent, resolvedType,
8705                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8706        }
8707
8708        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8709                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
8710            if (!sUserManager.exists(userId))
8711                return null;
8712            if (packageProviders == null) {
8713                return null;
8714            }
8715            mFlags = flags;
8716            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
8717            final int N = packageProviders.size();
8718            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
8719                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
8720
8721            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
8722            for (int i = 0; i < N; ++i) {
8723                intentFilters = packageProviders.get(i).intents;
8724                if (intentFilters != null && intentFilters.size() > 0) {
8725                    PackageParser.ProviderIntentInfo[] array =
8726                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
8727                    intentFilters.toArray(array);
8728                    listCut.add(array);
8729                }
8730            }
8731            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8732        }
8733
8734        public final void addProvider(PackageParser.Provider p) {
8735            if (mProviders.containsKey(p.getComponentName())) {
8736                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
8737                return;
8738            }
8739
8740            mProviders.put(p.getComponentName(), p);
8741            if (DEBUG_SHOW_INFO) {
8742                Log.v(TAG, "  "
8743                        + (p.info.nonLocalizedLabel != null
8744                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
8745                Log.v(TAG, "    Class=" + p.info.name);
8746            }
8747            final int NI = p.intents.size();
8748            int j;
8749            for (j = 0; j < NI; j++) {
8750                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
8751                if (DEBUG_SHOW_INFO) {
8752                    Log.v(TAG, "    IntentFilter:");
8753                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8754                }
8755                if (!intent.debugCheck()) {
8756                    Log.w(TAG, "==> For Provider " + p.info.name);
8757                }
8758                addFilter(intent);
8759            }
8760        }
8761
8762        public final void removeProvider(PackageParser.Provider p) {
8763            mProviders.remove(p.getComponentName());
8764            if (DEBUG_SHOW_INFO) {
8765                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
8766                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
8767                Log.v(TAG, "    Class=" + p.info.name);
8768            }
8769            final int NI = p.intents.size();
8770            int j;
8771            for (j = 0; j < NI; j++) {
8772                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
8773                if (DEBUG_SHOW_INFO) {
8774                    Log.v(TAG, "    IntentFilter:");
8775                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8776                }
8777                removeFilter(intent);
8778            }
8779        }
8780
8781        @Override
8782        protected boolean allowFilterResult(
8783                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
8784            ProviderInfo filterPi = filter.provider.info;
8785            for (int i = dest.size() - 1; i >= 0; i--) {
8786                ProviderInfo destPi = dest.get(i).providerInfo;
8787                if (destPi.name == filterPi.name
8788                        && destPi.packageName == filterPi.packageName) {
8789                    return false;
8790                }
8791            }
8792            return true;
8793        }
8794
8795        @Override
8796        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
8797            return new PackageParser.ProviderIntentInfo[size];
8798        }
8799
8800        @Override
8801        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
8802            if (!sUserManager.exists(userId))
8803                return true;
8804            PackageParser.Package p = filter.provider.owner;
8805            if (p != null) {
8806                PackageSetting ps = (PackageSetting) p.mExtras;
8807                if (ps != null) {
8808                    // System apps are never considered stopped for purposes of
8809                    // filtering, because there may be no way for the user to
8810                    // actually re-launch them.
8811                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8812                            && ps.getStopped(userId);
8813                }
8814            }
8815            return false;
8816        }
8817
8818        @Override
8819        protected boolean isPackageForFilter(String packageName,
8820                PackageParser.ProviderIntentInfo info) {
8821            return packageName.equals(info.provider.owner.packageName);
8822        }
8823
8824        @Override
8825        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
8826                int match, int userId) {
8827            if (!sUserManager.exists(userId))
8828                return null;
8829            final PackageParser.ProviderIntentInfo info = filter;
8830            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
8831                return null;
8832            }
8833            final PackageParser.Provider provider = info.provider;
8834            if (mSafeMode && (provider.info.applicationInfo.flags
8835                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
8836                return null;
8837            }
8838            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
8839            if (ps == null) {
8840                return null;
8841            }
8842            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
8843                    ps.readUserState(userId), userId);
8844            if (pi == null) {
8845                return null;
8846            }
8847            final ResolveInfo res = new ResolveInfo();
8848            res.providerInfo = pi;
8849            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
8850                res.filter = filter;
8851            }
8852            res.priority = info.getPriority();
8853            res.preferredOrder = provider.owner.mPreferredOrder;
8854            res.match = match;
8855            res.isDefault = info.hasDefault;
8856            res.labelRes = info.labelRes;
8857            res.nonLocalizedLabel = info.nonLocalizedLabel;
8858            res.icon = info.icon;
8859            res.system = res.providerInfo.applicationInfo.isSystemApp();
8860            return res;
8861        }
8862
8863        @Override
8864        protected void sortResults(List<ResolveInfo> results) {
8865            Collections.sort(results, mResolvePrioritySorter);
8866        }
8867
8868        @Override
8869        protected void dumpFilter(PrintWriter out, String prefix,
8870                PackageParser.ProviderIntentInfo filter) {
8871            out.print(prefix);
8872            out.print(
8873                    Integer.toHexString(System.identityHashCode(filter.provider)));
8874            out.print(' ');
8875            filter.provider.printComponentShortName(out);
8876            out.print(" filter ");
8877            out.println(Integer.toHexString(System.identityHashCode(filter)));
8878        }
8879
8880        @Override
8881        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
8882            return filter.provider;
8883        }
8884
8885        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8886            PackageParser.Provider provider = (PackageParser.Provider)label;
8887            out.print(prefix); out.print(
8888                    Integer.toHexString(System.identityHashCode(provider)));
8889                    out.print(' ');
8890                    provider.printComponentShortName(out);
8891            if (count > 1) {
8892                out.print(" ("); out.print(count); out.print(" filters)");
8893            }
8894            out.println();
8895        }
8896
8897        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
8898                = new ArrayMap<ComponentName, PackageParser.Provider>();
8899        private int mFlags;
8900    };
8901
8902    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
8903            new Comparator<ResolveInfo>() {
8904        public int compare(ResolveInfo r1, ResolveInfo r2) {
8905            int v1 = r1.priority;
8906            int v2 = r2.priority;
8907            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
8908            if (v1 != v2) {
8909                return (v1 > v2) ? -1 : 1;
8910            }
8911            v1 = r1.preferredOrder;
8912            v2 = r2.preferredOrder;
8913            if (v1 != v2) {
8914                return (v1 > v2) ? -1 : 1;
8915            }
8916            if (r1.isDefault != r2.isDefault) {
8917                return r1.isDefault ? -1 : 1;
8918            }
8919            v1 = r1.match;
8920            v2 = r2.match;
8921            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
8922            if (v1 != v2) {
8923                return (v1 > v2) ? -1 : 1;
8924            }
8925            if (r1.system != r2.system) {
8926                return r1.system ? -1 : 1;
8927            }
8928            return 0;
8929        }
8930    };
8931
8932    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
8933            new Comparator<ProviderInfo>() {
8934        public int compare(ProviderInfo p1, ProviderInfo p2) {
8935            final int v1 = p1.initOrder;
8936            final int v2 = p2.initOrder;
8937            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
8938        }
8939    };
8940
8941    final void sendPackageBroadcast(final String action, final String pkg,
8942            final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
8943            final int[] userIds) {
8944        mHandler.post(new Runnable() {
8945            @Override
8946            public void run() {
8947                try {
8948                    final IActivityManager am = ActivityManagerNative.getDefault();
8949                    if (am == null) return;
8950                    final int[] resolvedUserIds;
8951                    if (userIds == null) {
8952                        resolvedUserIds = am.getRunningUserIds();
8953                    } else {
8954                        resolvedUserIds = userIds;
8955                    }
8956                    for (int id : resolvedUserIds) {
8957                        final Intent intent = new Intent(action,
8958                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
8959                        if (extras != null) {
8960                            intent.putExtras(extras);
8961                        }
8962                        if (targetPkg != null) {
8963                            intent.setPackage(targetPkg);
8964                        }
8965                        // Modify the UID when posting to other users
8966                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
8967                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
8968                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
8969                            intent.putExtra(Intent.EXTRA_UID, uid);
8970                        }
8971                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
8972                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
8973                        if (DEBUG_BROADCASTS) {
8974                            RuntimeException here = new RuntimeException("here");
8975                            here.fillInStackTrace();
8976                            Slog.d(TAG, "Sending to user " + id + ": "
8977                                    + intent.toShortString(false, true, false, false)
8978                                    + " " + intent.getExtras(), here);
8979                        }
8980                        am.broadcastIntent(null, intent, null, finishedReceiver,
8981                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
8982                                null, finishedReceiver != null, false, id);
8983                    }
8984                } catch (RemoteException ex) {
8985                }
8986            }
8987        });
8988    }
8989
8990    /**
8991     * Check if the external storage media is available. This is true if there
8992     * is a mounted external storage medium or if the external storage is
8993     * emulated.
8994     */
8995    private boolean isExternalMediaAvailable() {
8996        return mMediaMounted || Environment.isExternalStorageEmulated();
8997    }
8998
8999    @Override
9000    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9001        // writer
9002        synchronized (mPackages) {
9003            if (!isExternalMediaAvailable()) {
9004                // If the external storage is no longer mounted at this point,
9005                // the caller may not have been able to delete all of this
9006                // packages files and can not delete any more.  Bail.
9007                return null;
9008            }
9009            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9010            if (lastPackage != null) {
9011                pkgs.remove(lastPackage);
9012            }
9013            if (pkgs.size() > 0) {
9014                return pkgs.get(0);
9015            }
9016        }
9017        return null;
9018    }
9019
9020    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9021        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9022                userId, andCode ? 1 : 0, packageName);
9023        if (mSystemReady) {
9024            msg.sendToTarget();
9025        } else {
9026            if (mPostSystemReadyMessages == null) {
9027                mPostSystemReadyMessages = new ArrayList<>();
9028            }
9029            mPostSystemReadyMessages.add(msg);
9030        }
9031    }
9032
9033    void startCleaningPackages() {
9034        // reader
9035        synchronized (mPackages) {
9036            if (!isExternalMediaAvailable()) {
9037                return;
9038            }
9039            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9040                return;
9041            }
9042        }
9043        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9044        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9045        IActivityManager am = ActivityManagerNative.getDefault();
9046        if (am != null) {
9047            try {
9048                am.startService(null, intent, null, UserHandle.USER_OWNER);
9049            } catch (RemoteException e) {
9050            }
9051        }
9052    }
9053
9054    @Override
9055    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9056            int installFlags, String installerPackageName, VerificationParams verificationParams,
9057            String packageAbiOverride) {
9058        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9059                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9060    }
9061
9062    @Override
9063    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9064            int installFlags, String installerPackageName, VerificationParams verificationParams,
9065            String packageAbiOverride, int userId) {
9066        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9067
9068        final int callingUid = Binder.getCallingUid();
9069        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9070
9071        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9072            try {
9073                if (observer != null) {
9074                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9075                }
9076            } catch (RemoteException re) {
9077            }
9078            return;
9079        }
9080
9081        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9082            installFlags |= PackageManager.INSTALL_FROM_ADB;
9083
9084        } else {
9085            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9086            // about installerPackageName.
9087
9088            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9089            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9090        }
9091
9092        UserHandle user;
9093        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9094            user = UserHandle.ALL;
9095        } else {
9096            user = new UserHandle(userId);
9097        }
9098
9099        // Only system components can circumvent runtime permissions when installing.
9100        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9101                && mContext.checkCallingOrSelfPermission(Manifest.permission
9102                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9103            throw new SecurityException("You need the "
9104                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9105                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9106        }
9107
9108        verificationParams.setInstallerUid(callingUid);
9109
9110        final File originFile = new File(originPath);
9111        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9112
9113        final Message msg = mHandler.obtainMessage(INIT_COPY);
9114        msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName,
9115                null, verificationParams, user, packageAbiOverride);
9116        mHandler.sendMessage(msg);
9117    }
9118
9119    void installStage(String packageName, File stagedDir, String stagedCid,
9120            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
9121            String installerPackageName, int installerUid, UserHandle user) {
9122        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
9123                params.referrerUri, installerUid, null);
9124        verifParams.setInstallerUid(installerUid);
9125
9126        final OriginInfo origin;
9127        if (stagedDir != null) {
9128            origin = OriginInfo.fromStagedFile(stagedDir);
9129        } else {
9130            origin = OriginInfo.fromStagedContainer(stagedCid);
9131        }
9132
9133        final Message msg = mHandler.obtainMessage(INIT_COPY);
9134        msg.obj = new InstallParams(origin, null, observer, params.installFlags,
9135                installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride);
9136        mHandler.sendMessage(msg);
9137    }
9138
9139    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
9140        Bundle extras = new Bundle(1);
9141        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
9142
9143        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
9144                packageName, extras, null, null, new int[] {userId});
9145        try {
9146            IActivityManager am = ActivityManagerNative.getDefault();
9147            final boolean isSystem =
9148                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
9149            if (isSystem && am.isUserRunning(userId, false)) {
9150                // The just-installed/enabled app is bundled on the system, so presumed
9151                // to be able to run automatically without needing an explicit launch.
9152                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
9153                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
9154                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
9155                        .setPackage(packageName);
9156                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
9157                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
9158            }
9159        } catch (RemoteException e) {
9160            // shouldn't happen
9161            Slog.w(TAG, "Unable to bootstrap installed package", e);
9162        }
9163    }
9164
9165    @Override
9166    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9167            int userId) {
9168        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9169        PackageSetting pkgSetting;
9170        final int uid = Binder.getCallingUid();
9171        enforceCrossUserPermission(uid, userId, true, true,
9172                "setApplicationHiddenSetting for user " + userId);
9173
9174        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9175            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9176            return false;
9177        }
9178
9179        long callingId = Binder.clearCallingIdentity();
9180        try {
9181            boolean sendAdded = false;
9182            boolean sendRemoved = false;
9183            // writer
9184            synchronized (mPackages) {
9185                pkgSetting = mSettings.mPackages.get(packageName);
9186                if (pkgSetting == null) {
9187                    return false;
9188                }
9189                if (pkgSetting.getHidden(userId) != hidden) {
9190                    pkgSetting.setHidden(hidden, userId);
9191                    mSettings.writePackageRestrictionsLPr(userId);
9192                    if (hidden) {
9193                        sendRemoved = true;
9194                    } else {
9195                        sendAdded = true;
9196                    }
9197                }
9198            }
9199            if (sendAdded) {
9200                sendPackageAddedForUser(packageName, pkgSetting, userId);
9201                return true;
9202            }
9203            if (sendRemoved) {
9204                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
9205                        "hiding pkg");
9206                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
9207            }
9208        } finally {
9209            Binder.restoreCallingIdentity(callingId);
9210        }
9211        return false;
9212    }
9213
9214    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9215            int userId) {
9216        final PackageRemovedInfo info = new PackageRemovedInfo();
9217        info.removedPackage = packageName;
9218        info.removedUsers = new int[] {userId};
9219        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9220        info.sendBroadcast(false, false, false);
9221    }
9222
9223    /**
9224     * Returns true if application is not found or there was an error. Otherwise it returns
9225     * the hidden state of the package for the given user.
9226     */
9227    @Override
9228    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9229        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9230        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9231                false, "getApplicationHidden for user " + userId);
9232        PackageSetting pkgSetting;
9233        long callingId = Binder.clearCallingIdentity();
9234        try {
9235            // writer
9236            synchronized (mPackages) {
9237                pkgSetting = mSettings.mPackages.get(packageName);
9238                if (pkgSetting == null) {
9239                    return true;
9240                }
9241                return pkgSetting.getHidden(userId);
9242            }
9243        } finally {
9244            Binder.restoreCallingIdentity(callingId);
9245        }
9246    }
9247
9248    /**
9249     * @hide
9250     */
9251    @Override
9252    public int installExistingPackageAsUser(String packageName, int userId) {
9253        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9254                null);
9255        PackageSetting pkgSetting;
9256        final int uid = Binder.getCallingUid();
9257        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9258                + userId);
9259        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9260            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9261        }
9262
9263        long callingId = Binder.clearCallingIdentity();
9264        try {
9265            boolean sendAdded = false;
9266
9267            // writer
9268            synchronized (mPackages) {
9269                pkgSetting = mSettings.mPackages.get(packageName);
9270                if (pkgSetting == null) {
9271                    return PackageManager.INSTALL_FAILED_INVALID_URI;
9272                }
9273                if (!pkgSetting.getInstalled(userId)) {
9274                    pkgSetting.setInstalled(true, userId);
9275                    pkgSetting.setHidden(false, userId);
9276                    mSettings.writePackageRestrictionsLPr(userId);
9277                    sendAdded = true;
9278                }
9279            }
9280
9281            if (sendAdded) {
9282                sendPackageAddedForUser(packageName, pkgSetting, userId);
9283            }
9284        } finally {
9285            Binder.restoreCallingIdentity(callingId);
9286        }
9287
9288        return PackageManager.INSTALL_SUCCEEDED;
9289    }
9290
9291    boolean isUserRestricted(int userId, String restrictionKey) {
9292        Bundle restrictions = sUserManager.getUserRestrictions(userId);
9293        if (restrictions.getBoolean(restrictionKey, false)) {
9294            Log.w(TAG, "User is restricted: " + restrictionKey);
9295            return true;
9296        }
9297        return false;
9298    }
9299
9300    @Override
9301    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
9302        mContext.enforceCallingOrSelfPermission(
9303                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9304                "Only package verification agents can verify applications");
9305
9306        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9307        final PackageVerificationResponse response = new PackageVerificationResponse(
9308                verificationCode, Binder.getCallingUid());
9309        msg.arg1 = id;
9310        msg.obj = response;
9311        mHandler.sendMessage(msg);
9312    }
9313
9314    @Override
9315    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
9316            long millisecondsToDelay) {
9317        mContext.enforceCallingOrSelfPermission(
9318                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9319                "Only package verification agents can extend verification timeouts");
9320
9321        final PackageVerificationState state = mPendingVerification.get(id);
9322        final PackageVerificationResponse response = new PackageVerificationResponse(
9323                verificationCodeAtTimeout, Binder.getCallingUid());
9324
9325        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
9326            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
9327        }
9328        if (millisecondsToDelay < 0) {
9329            millisecondsToDelay = 0;
9330        }
9331        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9332                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9333            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9334        }
9335
9336        if ((state != null) && !state.timeoutExtended()) {
9337            state.extendTimeout();
9338
9339            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9340            msg.arg1 = id;
9341            msg.obj = response;
9342            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
9343        }
9344    }
9345
9346    private void broadcastPackageVerified(int verificationId, Uri packageUri,
9347            int verificationCode, UserHandle user) {
9348        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
9349        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
9350        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9351        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9352        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
9353
9354        mContext.sendBroadcastAsUser(intent, user,
9355                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
9356    }
9357
9358    private ComponentName matchComponentForVerifier(String packageName,
9359            List<ResolveInfo> receivers) {
9360        ActivityInfo targetReceiver = null;
9361
9362        final int NR = receivers.size();
9363        for (int i = 0; i < NR; i++) {
9364            final ResolveInfo info = receivers.get(i);
9365            if (info.activityInfo == null) {
9366                continue;
9367            }
9368
9369            if (packageName.equals(info.activityInfo.packageName)) {
9370                targetReceiver = info.activityInfo;
9371                break;
9372            }
9373        }
9374
9375        if (targetReceiver == null) {
9376            return null;
9377        }
9378
9379        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
9380    }
9381
9382    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
9383            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
9384        if (pkgInfo.verifiers.length == 0) {
9385            return null;
9386        }
9387
9388        final int N = pkgInfo.verifiers.length;
9389        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
9390        for (int i = 0; i < N; i++) {
9391            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
9392
9393            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
9394                    receivers);
9395            if (comp == null) {
9396                continue;
9397            }
9398
9399            final int verifierUid = getUidForVerifier(verifierInfo);
9400            if (verifierUid == -1) {
9401                continue;
9402            }
9403
9404            if (DEBUG_VERIFY) {
9405                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
9406                        + " with the correct signature");
9407            }
9408            sufficientVerifiers.add(comp);
9409            verificationState.addSufficientVerifier(verifierUid);
9410        }
9411
9412        return sufficientVerifiers;
9413    }
9414
9415    private int getUidForVerifier(VerifierInfo verifierInfo) {
9416        synchronized (mPackages) {
9417            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
9418            if (pkg == null) {
9419                return -1;
9420            } else if (pkg.mSignatures.length != 1) {
9421                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9422                        + " has more than one signature; ignoring");
9423                return -1;
9424            }
9425
9426            /*
9427             * If the public key of the package's signature does not match
9428             * our expected public key, then this is a different package and
9429             * we should skip.
9430             */
9431
9432            final byte[] expectedPublicKey;
9433            try {
9434                final Signature verifierSig = pkg.mSignatures[0];
9435                final PublicKey publicKey = verifierSig.getPublicKey();
9436                expectedPublicKey = publicKey.getEncoded();
9437            } catch (CertificateException e) {
9438                return -1;
9439            }
9440
9441            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
9442
9443            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
9444                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9445                        + " does not have the expected public key; ignoring");
9446                return -1;
9447            }
9448
9449            return pkg.applicationInfo.uid;
9450        }
9451    }
9452
9453    @Override
9454    public void finishPackageInstall(int token) {
9455        enforceSystemOrRoot("Only the system is allowed to finish installs");
9456
9457        if (DEBUG_INSTALL) {
9458            Slog.v(TAG, "BM finishing package install for " + token);
9459        }
9460
9461        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9462        mHandler.sendMessage(msg);
9463    }
9464
9465    /**
9466     * Get the verification agent timeout.
9467     *
9468     * @return verification timeout in milliseconds
9469     */
9470    private long getVerificationTimeout() {
9471        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
9472                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
9473                DEFAULT_VERIFICATION_TIMEOUT);
9474    }
9475
9476    /**
9477     * Get the default verification agent response code.
9478     *
9479     * @return default verification response code
9480     */
9481    private int getDefaultVerificationResponse() {
9482        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9483                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
9484                DEFAULT_VERIFICATION_RESPONSE);
9485    }
9486
9487    /**
9488     * Check whether or not package verification has been enabled.
9489     *
9490     * @return true if verification should be performed
9491     */
9492    private boolean isVerificationEnabled(int userId, int installFlags) {
9493        if (!DEFAULT_VERIFY_ENABLE) {
9494            return false;
9495        }
9496
9497        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
9498
9499        // Check if installing from ADB
9500        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
9501            // Do not run verification in a test harness environment
9502            if (ActivityManager.isRunningInTestHarness()) {
9503                return false;
9504            }
9505            if (ensureVerifyAppsEnabled) {
9506                return true;
9507            }
9508            // Check if the developer does not want package verification for ADB installs
9509            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9510                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
9511                return false;
9512            }
9513        }
9514
9515        if (ensureVerifyAppsEnabled) {
9516            return true;
9517        }
9518
9519        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9520                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9521    }
9522
9523    @Override
9524    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9525            throws RemoteException {
9526        mContext.enforceCallingOrSelfPermission(
9527                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9528                "Only intentfilter verification agents can verify applications");
9529
9530        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9531        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9532                Binder.getCallingUid(), verificationCode, failedDomains);
9533        msg.arg1 = id;
9534        msg.obj = response;
9535        mHandler.sendMessage(msg);
9536    }
9537
9538    @Override
9539    public int getIntentVerificationStatus(String packageName, int userId) {
9540        synchronized (mPackages) {
9541            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
9542        }
9543    }
9544
9545    @Override
9546    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
9547        boolean result = false;
9548        synchronized (mPackages) {
9549            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
9550        }
9551        if (result) {
9552            scheduleWritePackageRestrictionsLocked(userId);
9553        }
9554        return result;
9555    }
9556
9557    @Override
9558    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
9559        synchronized (mPackages) {
9560            return mSettings.getIntentFilterVerificationsLPr(packageName);
9561        }
9562    }
9563
9564    @Override
9565    public List<IntentFilter> getAllIntentFilters(String packageName) {
9566        if (TextUtils.isEmpty(packageName)) {
9567            return Collections.<IntentFilter>emptyList();
9568        }
9569        synchronized (mPackages) {
9570            PackageParser.Package pkg = mPackages.get(packageName);
9571            if (pkg == null || pkg.activities == null) {
9572                return Collections.<IntentFilter>emptyList();
9573            }
9574            final int count = pkg.activities.size();
9575            ArrayList<IntentFilter> result = new ArrayList<>();
9576            for (int n=0; n<count; n++) {
9577                PackageParser.Activity activity = pkg.activities.get(n);
9578                if (activity.intents != null || activity.intents.size() > 0) {
9579                    result.addAll(activity.intents);
9580                }
9581            }
9582            return result;
9583        }
9584    }
9585
9586    @Override
9587    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
9588        synchronized (mPackages) {
9589            boolean result = mSettings.setDefaultBrowserPackageNameLPr(packageName, userId);
9590            if (packageName != null) {
9591                result |= updateIntentVerificationStatus(packageName,
9592                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
9593                        UserHandle.myUserId());
9594            }
9595            return result;
9596        }
9597    }
9598
9599    @Override
9600    public String getDefaultBrowserPackageName(int userId) {
9601        synchronized (mPackages) {
9602            return mSettings.getDefaultBrowserPackageNameLPw(userId);
9603        }
9604    }
9605
9606    /**
9607     * Get the "allow unknown sources" setting.
9608     *
9609     * @return the current "allow unknown sources" setting
9610     */
9611    private int getUnknownSourcesSettings() {
9612        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9613                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
9614                -1);
9615    }
9616
9617    @Override
9618    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
9619        final int uid = Binder.getCallingUid();
9620        // writer
9621        synchronized (mPackages) {
9622            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
9623            if (targetPackageSetting == null) {
9624                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
9625            }
9626
9627            PackageSetting installerPackageSetting;
9628            if (installerPackageName != null) {
9629                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
9630                if (installerPackageSetting == null) {
9631                    throw new IllegalArgumentException("Unknown installer package: "
9632                            + installerPackageName);
9633                }
9634            } else {
9635                installerPackageSetting = null;
9636            }
9637
9638            Signature[] callerSignature;
9639            Object obj = mSettings.getUserIdLPr(uid);
9640            if (obj != null) {
9641                if (obj instanceof SharedUserSetting) {
9642                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
9643                } else if (obj instanceof PackageSetting) {
9644                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
9645                } else {
9646                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
9647                }
9648            } else {
9649                throw new SecurityException("Unknown calling uid " + uid);
9650            }
9651
9652            // Verify: can't set installerPackageName to a package that is
9653            // not signed with the same cert as the caller.
9654            if (installerPackageSetting != null) {
9655                if (compareSignatures(callerSignature,
9656                        installerPackageSetting.signatures.mSignatures)
9657                        != PackageManager.SIGNATURE_MATCH) {
9658                    throw new SecurityException(
9659                            "Caller does not have same cert as new installer package "
9660                            + installerPackageName);
9661                }
9662            }
9663
9664            // Verify: if target already has an installer package, it must
9665            // be signed with the same cert as the caller.
9666            if (targetPackageSetting.installerPackageName != null) {
9667                PackageSetting setting = mSettings.mPackages.get(
9668                        targetPackageSetting.installerPackageName);
9669                // If the currently set package isn't valid, then it's always
9670                // okay to change it.
9671                if (setting != null) {
9672                    if (compareSignatures(callerSignature,
9673                            setting.signatures.mSignatures)
9674                            != PackageManager.SIGNATURE_MATCH) {
9675                        throw new SecurityException(
9676                                "Caller does not have same cert as old installer package "
9677                                + targetPackageSetting.installerPackageName);
9678                    }
9679                }
9680            }
9681
9682            // Okay!
9683            targetPackageSetting.installerPackageName = installerPackageName;
9684            scheduleWriteSettingsLocked();
9685        }
9686    }
9687
9688    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
9689        // Queue up an async operation since the package installation may take a little while.
9690        mHandler.post(new Runnable() {
9691            public void run() {
9692                mHandler.removeCallbacks(this);
9693                 // Result object to be returned
9694                PackageInstalledInfo res = new PackageInstalledInfo();
9695                res.returnCode = currentStatus;
9696                res.uid = -1;
9697                res.pkg = null;
9698                res.removedInfo = new PackageRemovedInfo();
9699                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
9700                    args.doPreInstall(res.returnCode);
9701                    synchronized (mInstallLock) {
9702                        installPackageLI(args, res);
9703                    }
9704                    args.doPostInstall(res.returnCode, res.uid);
9705                }
9706
9707                // A restore should be performed at this point if (a) the install
9708                // succeeded, (b) the operation is not an update, and (c) the new
9709                // package has not opted out of backup participation.
9710                final boolean update = res.removedInfo.removedPackage != null;
9711                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
9712                boolean doRestore = !update
9713                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
9714
9715                // Set up the post-install work request bookkeeping.  This will be used
9716                // and cleaned up by the post-install event handling regardless of whether
9717                // there's a restore pass performed.  Token values are >= 1.
9718                int token;
9719                if (mNextInstallToken < 0) mNextInstallToken = 1;
9720                token = mNextInstallToken++;
9721
9722                PostInstallData data = new PostInstallData(args, res);
9723                mRunningInstalls.put(token, data);
9724                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
9725
9726                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
9727                    // Pass responsibility to the Backup Manager.  It will perform a
9728                    // restore if appropriate, then pass responsibility back to the
9729                    // Package Manager to run the post-install observer callbacks
9730                    // and broadcasts.
9731                    IBackupManager bm = IBackupManager.Stub.asInterface(
9732                            ServiceManager.getService(Context.BACKUP_SERVICE));
9733                    if (bm != null) {
9734                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
9735                                + " to BM for possible restore");
9736                        try {
9737                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
9738                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
9739                            } else {
9740                                doRestore = false;
9741                            }
9742                        } catch (RemoteException e) {
9743                            // can't happen; the backup manager is local
9744                        } catch (Exception e) {
9745                            Slog.e(TAG, "Exception trying to enqueue restore", e);
9746                            doRestore = false;
9747                        }
9748                    } else {
9749                        Slog.e(TAG, "Backup Manager not found!");
9750                        doRestore = false;
9751                    }
9752                }
9753
9754                if (!doRestore) {
9755                    // No restore possible, or the Backup Manager was mysteriously not
9756                    // available -- just fire the post-install work request directly.
9757                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
9758                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9759                    mHandler.sendMessage(msg);
9760                }
9761            }
9762        });
9763    }
9764
9765    private abstract class HandlerParams {
9766        private static final int MAX_RETRIES = 4;
9767
9768        /**
9769         * Number of times startCopy() has been attempted and had a non-fatal
9770         * error.
9771         */
9772        private int mRetries = 0;
9773
9774        /** User handle for the user requesting the information or installation. */
9775        private final UserHandle mUser;
9776
9777        HandlerParams(UserHandle user) {
9778            mUser = user;
9779        }
9780
9781        UserHandle getUser() {
9782            return mUser;
9783        }
9784
9785        final boolean startCopy() {
9786            boolean res;
9787            try {
9788                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
9789
9790                if (++mRetries > MAX_RETRIES) {
9791                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
9792                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
9793                    handleServiceError();
9794                    return false;
9795                } else {
9796                    handleStartCopy();
9797                    res = true;
9798                }
9799            } catch (RemoteException e) {
9800                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
9801                mHandler.sendEmptyMessage(MCS_RECONNECT);
9802                res = false;
9803            }
9804            handleReturnCode();
9805            return res;
9806        }
9807
9808        final void serviceError() {
9809            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
9810            handleServiceError();
9811            handleReturnCode();
9812        }
9813
9814        abstract void handleStartCopy() throws RemoteException;
9815        abstract void handleServiceError();
9816        abstract void handleReturnCode();
9817    }
9818
9819    class MeasureParams extends HandlerParams {
9820        private final PackageStats mStats;
9821        private boolean mSuccess;
9822
9823        private final IPackageStatsObserver mObserver;
9824
9825        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
9826            super(new UserHandle(stats.userHandle));
9827            mObserver = observer;
9828            mStats = stats;
9829        }
9830
9831        @Override
9832        public String toString() {
9833            return "MeasureParams{"
9834                + Integer.toHexString(System.identityHashCode(this))
9835                + " " + mStats.packageName + "}";
9836        }
9837
9838        @Override
9839        void handleStartCopy() throws RemoteException {
9840            synchronized (mInstallLock) {
9841                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
9842            }
9843
9844            if (mSuccess) {
9845                final boolean mounted;
9846                if (Environment.isExternalStorageEmulated()) {
9847                    mounted = true;
9848                } else {
9849                    final String status = Environment.getExternalStorageState();
9850                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
9851                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
9852                }
9853
9854                if (mounted) {
9855                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
9856
9857                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
9858                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
9859
9860                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
9861                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
9862
9863                    // Always subtract cache size, since it's a subdirectory
9864                    mStats.externalDataSize -= mStats.externalCacheSize;
9865
9866                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
9867                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
9868
9869                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
9870                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
9871                }
9872            }
9873        }
9874
9875        @Override
9876        void handleReturnCode() {
9877            if (mObserver != null) {
9878                try {
9879                    mObserver.onGetStatsCompleted(mStats, mSuccess);
9880                } catch (RemoteException e) {
9881                    Slog.i(TAG, "Observer no longer exists.");
9882                }
9883            }
9884        }
9885
9886        @Override
9887        void handleServiceError() {
9888            Slog.e(TAG, "Could not measure application " + mStats.packageName
9889                            + " external storage");
9890        }
9891    }
9892
9893    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
9894            throws RemoteException {
9895        long result = 0;
9896        for (File path : paths) {
9897            result += mcs.calculateDirectorySize(path.getAbsolutePath());
9898        }
9899        return result;
9900    }
9901
9902    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
9903        for (File path : paths) {
9904            try {
9905                mcs.clearDirectory(path.getAbsolutePath());
9906            } catch (RemoteException e) {
9907            }
9908        }
9909    }
9910
9911    static class OriginInfo {
9912        /**
9913         * Location where install is coming from, before it has been
9914         * copied/renamed into place. This could be a single monolithic APK
9915         * file, or a cluster directory. This location may be untrusted.
9916         */
9917        final File file;
9918        final String cid;
9919
9920        /**
9921         * Flag indicating that {@link #file} or {@link #cid} has already been
9922         * staged, meaning downstream users don't need to defensively copy the
9923         * contents.
9924         */
9925        final boolean staged;
9926
9927        /**
9928         * Flag indicating that {@link #file} or {@link #cid} is an already
9929         * installed app that is being moved.
9930         */
9931        final boolean existing;
9932
9933        final String resolvedPath;
9934        final File resolvedFile;
9935
9936        static OriginInfo fromNothing() {
9937            return new OriginInfo(null, null, false, false);
9938        }
9939
9940        static OriginInfo fromUntrustedFile(File file) {
9941            return new OriginInfo(file, null, false, false);
9942        }
9943
9944        static OriginInfo fromExistingFile(File file) {
9945            return new OriginInfo(file, null, false, true);
9946        }
9947
9948        static OriginInfo fromStagedFile(File file) {
9949            return new OriginInfo(file, null, true, false);
9950        }
9951
9952        static OriginInfo fromStagedContainer(String cid) {
9953            return new OriginInfo(null, cid, true, false);
9954        }
9955
9956        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
9957            this.file = file;
9958            this.cid = cid;
9959            this.staged = staged;
9960            this.existing = existing;
9961
9962            if (cid != null) {
9963                resolvedPath = PackageHelper.getSdDir(cid);
9964                resolvedFile = new File(resolvedPath);
9965            } else if (file != null) {
9966                resolvedPath = file.getAbsolutePath();
9967                resolvedFile = file;
9968            } else {
9969                resolvedPath = null;
9970                resolvedFile = null;
9971            }
9972        }
9973    }
9974
9975    class MoveInfo {
9976        final int moveId;
9977        final String fromUuid;
9978        final String toUuid;
9979        final String packageName;
9980        final String dataAppName;
9981        final int appId;
9982        final String seinfo;
9983
9984        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
9985                String dataAppName, int appId, String seinfo) {
9986            this.moveId = moveId;
9987            this.fromUuid = fromUuid;
9988            this.toUuid = toUuid;
9989            this.packageName = packageName;
9990            this.dataAppName = dataAppName;
9991            this.appId = appId;
9992            this.seinfo = seinfo;
9993        }
9994    }
9995
9996    class InstallParams extends HandlerParams {
9997        final OriginInfo origin;
9998        final MoveInfo move;
9999        final IPackageInstallObserver2 observer;
10000        int installFlags;
10001        final String installerPackageName;
10002        final String volumeUuid;
10003        final VerificationParams verificationParams;
10004        private InstallArgs mArgs;
10005        private int mRet;
10006        final String packageAbiOverride;
10007
10008        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10009                int installFlags, String installerPackageName, String volumeUuid,
10010                VerificationParams verificationParams, UserHandle user, String packageAbiOverride) {
10011            super(user);
10012            this.origin = origin;
10013            this.move = move;
10014            this.observer = observer;
10015            this.installFlags = installFlags;
10016            this.installerPackageName = installerPackageName;
10017            this.volumeUuid = volumeUuid;
10018            this.verificationParams = verificationParams;
10019            this.packageAbiOverride = packageAbiOverride;
10020        }
10021
10022        @Override
10023        public String toString() {
10024            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10025                    + " file=" + origin.file + " cid=" + origin.cid + "}";
10026        }
10027
10028        public ManifestDigest getManifestDigest() {
10029            if (verificationParams == null) {
10030                return null;
10031            }
10032            return verificationParams.getManifestDigest();
10033        }
10034
10035        private int installLocationPolicy(PackageInfoLite pkgLite) {
10036            String packageName = pkgLite.packageName;
10037            int installLocation = pkgLite.installLocation;
10038            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10039            // reader
10040            synchronized (mPackages) {
10041                PackageParser.Package pkg = mPackages.get(packageName);
10042                if (pkg != null) {
10043                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10044                        // Check for downgrading.
10045                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10046                            try {
10047                                checkDowngrade(pkg, pkgLite);
10048                            } catch (PackageManagerException e) {
10049                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10050                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
10051                            }
10052                        }
10053                        // Check for updated system application.
10054                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10055                            if (onSd) {
10056                                Slog.w(TAG, "Cannot install update to system app on sdcard");
10057                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
10058                            }
10059                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10060                        } else {
10061                            if (onSd) {
10062                                // Install flag overrides everything.
10063                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10064                            }
10065                            // If current upgrade specifies particular preference
10066                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
10067                                // Application explicitly specified internal.
10068                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10069                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
10070                                // App explictly prefers external. Let policy decide
10071                            } else {
10072                                // Prefer previous location
10073                                if (isExternal(pkg)) {
10074                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10075                                }
10076                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10077                            }
10078                        }
10079                    } else {
10080                        // Invalid install. Return error code
10081                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
10082                    }
10083                }
10084            }
10085            // All the special cases have been taken care of.
10086            // Return result based on recommended install location.
10087            if (onSd) {
10088                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10089            }
10090            return pkgLite.recommendedInstallLocation;
10091        }
10092
10093        /*
10094         * Invoke remote method to get package information and install
10095         * location values. Override install location based on default
10096         * policy if needed and then create install arguments based
10097         * on the install location.
10098         */
10099        public void handleStartCopy() throws RemoteException {
10100            int ret = PackageManager.INSTALL_SUCCEEDED;
10101
10102            // If we're already staged, we've firmly committed to an install location
10103            if (origin.staged) {
10104                if (origin.file != null) {
10105                    installFlags |= PackageManager.INSTALL_INTERNAL;
10106                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10107                } else if (origin.cid != null) {
10108                    installFlags |= PackageManager.INSTALL_EXTERNAL;
10109                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
10110                } else {
10111                    throw new IllegalStateException("Invalid stage location");
10112                }
10113            }
10114
10115            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10116            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
10117
10118            PackageInfoLite pkgLite = null;
10119
10120            if (onInt && onSd) {
10121                // Check if both bits are set.
10122                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
10123                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10124            } else {
10125                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
10126                        packageAbiOverride);
10127
10128                /*
10129                 * If we have too little free space, try to free cache
10130                 * before giving up.
10131                 */
10132                if (!origin.staged && pkgLite.recommendedInstallLocation
10133                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10134                    // TODO: focus freeing disk space on the target device
10135                    final StorageManager storage = StorageManager.from(mContext);
10136                    final long lowThreshold = storage.getStorageLowBytes(
10137                            Environment.getDataDirectory());
10138
10139                    final long sizeBytes = mContainerService.calculateInstalledSize(
10140                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
10141
10142                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
10143                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
10144                                installFlags, packageAbiOverride);
10145                    }
10146
10147                    /*
10148                     * The cache free must have deleted the file we
10149                     * downloaded to install.
10150                     *
10151                     * TODO: fix the "freeCache" call to not delete
10152                     *       the file we care about.
10153                     */
10154                    if (pkgLite.recommendedInstallLocation
10155                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10156                        pkgLite.recommendedInstallLocation
10157                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
10158                    }
10159                }
10160            }
10161
10162            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10163                int loc = pkgLite.recommendedInstallLocation;
10164                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
10165                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10166                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
10167                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
10168                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10169                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10170                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
10171                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
10172                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10173                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
10174                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
10175                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
10176                } else {
10177                    // Override with defaults if needed.
10178                    loc = installLocationPolicy(pkgLite);
10179                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
10180                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
10181                    } else if (!onSd && !onInt) {
10182                        // Override install location with flags
10183                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
10184                            // Set the flag to install on external media.
10185                            installFlags |= PackageManager.INSTALL_EXTERNAL;
10186                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
10187                        } else {
10188                            // Make sure the flag for installing on external
10189                            // media is unset
10190                            installFlags |= PackageManager.INSTALL_INTERNAL;
10191                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10192                        }
10193                    }
10194                }
10195            }
10196
10197            final InstallArgs args = createInstallArgs(this);
10198            mArgs = args;
10199
10200            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10201                 /*
10202                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
10203                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
10204                 */
10205                int userIdentifier = getUser().getIdentifier();
10206                if (userIdentifier == UserHandle.USER_ALL
10207                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
10208                    userIdentifier = UserHandle.USER_OWNER;
10209                }
10210
10211                /*
10212                 * Determine if we have any installed package verifiers. If we
10213                 * do, then we'll defer to them to verify the packages.
10214                 */
10215                final int requiredUid = mRequiredVerifierPackage == null ? -1
10216                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
10217                if (!origin.existing && requiredUid != -1
10218                        && isVerificationEnabled(userIdentifier, installFlags)) {
10219                    final Intent verification = new Intent(
10220                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
10221                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10222                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
10223                            PACKAGE_MIME_TYPE);
10224                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10225
10226                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
10227                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10228                            0 /* TODO: Which userId? */);
10229
10230                    if (DEBUG_VERIFY) {
10231                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10232                                + verification.toString() + " with " + pkgLite.verifiers.length
10233                                + " optional verifiers");
10234                    }
10235
10236                    final int verificationId = mPendingVerificationToken++;
10237
10238                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10239
10240                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10241                            installerPackageName);
10242
10243                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10244                            installFlags);
10245
10246                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10247                            pkgLite.packageName);
10248
10249                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10250                            pkgLite.versionCode);
10251
10252                    if (verificationParams != null) {
10253                        if (verificationParams.getVerificationURI() != null) {
10254                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10255                                 verificationParams.getVerificationURI());
10256                        }
10257                        if (verificationParams.getOriginatingURI() != null) {
10258                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10259                                  verificationParams.getOriginatingURI());
10260                        }
10261                        if (verificationParams.getReferrer() != null) {
10262                            verification.putExtra(Intent.EXTRA_REFERRER,
10263                                  verificationParams.getReferrer());
10264                        }
10265                        if (verificationParams.getOriginatingUid() >= 0) {
10266                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
10267                                  verificationParams.getOriginatingUid());
10268                        }
10269                        if (verificationParams.getInstallerUid() >= 0) {
10270                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
10271                                  verificationParams.getInstallerUid());
10272                        }
10273                    }
10274
10275                    final PackageVerificationState verificationState = new PackageVerificationState(
10276                            requiredUid, args);
10277
10278                    mPendingVerification.append(verificationId, verificationState);
10279
10280                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
10281                            receivers, verificationState);
10282
10283                    /*
10284                     * If any sufficient verifiers were listed in the package
10285                     * manifest, attempt to ask them.
10286                     */
10287                    if (sufficientVerifiers != null) {
10288                        final int N = sufficientVerifiers.size();
10289                        if (N == 0) {
10290                            Slog.i(TAG, "Additional verifiers required, but none installed.");
10291                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
10292                        } else {
10293                            for (int i = 0; i < N; i++) {
10294                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
10295
10296                                final Intent sufficientIntent = new Intent(verification);
10297                                sufficientIntent.setComponent(verifierComponent);
10298
10299                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
10300                            }
10301                        }
10302                    }
10303
10304                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
10305                            mRequiredVerifierPackage, receivers);
10306                    if (ret == PackageManager.INSTALL_SUCCEEDED
10307                            && mRequiredVerifierPackage != null) {
10308                        /*
10309                         * Send the intent to the required verification agent,
10310                         * but only start the verification timeout after the
10311                         * target BroadcastReceivers have run.
10312                         */
10313                        verification.setComponent(requiredVerifierComponent);
10314                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
10315                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10316                                new BroadcastReceiver() {
10317                                    @Override
10318                                    public void onReceive(Context context, Intent intent) {
10319                                        final Message msg = mHandler
10320                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
10321                                        msg.arg1 = verificationId;
10322                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
10323                                    }
10324                                }, null, 0, null, null);
10325
10326                        /*
10327                         * We don't want the copy to proceed until verification
10328                         * succeeds, so null out this field.
10329                         */
10330                        mArgs = null;
10331                    }
10332                } else {
10333                    /*
10334                     * No package verification is enabled, so immediately start
10335                     * the remote call to initiate copy using temporary file.
10336                     */
10337                    ret = args.copyApk(mContainerService, true);
10338                }
10339            }
10340
10341            mRet = ret;
10342        }
10343
10344        @Override
10345        void handleReturnCode() {
10346            // If mArgs is null, then MCS couldn't be reached. When it
10347            // reconnects, it will try again to install. At that point, this
10348            // will succeed.
10349            if (mArgs != null) {
10350                processPendingInstall(mArgs, mRet);
10351            }
10352        }
10353
10354        @Override
10355        void handleServiceError() {
10356            mArgs = createInstallArgs(this);
10357            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10358        }
10359
10360        public boolean isForwardLocked() {
10361            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10362        }
10363    }
10364
10365    /**
10366     * Used during creation of InstallArgs
10367     *
10368     * @param installFlags package installation flags
10369     * @return true if should be installed on external storage
10370     */
10371    private static boolean installOnExternalAsec(int installFlags) {
10372        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
10373            return false;
10374        }
10375        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
10376            return true;
10377        }
10378        return false;
10379    }
10380
10381    /**
10382     * Used during creation of InstallArgs
10383     *
10384     * @param installFlags package installation flags
10385     * @return true if should be installed as forward locked
10386     */
10387    private static boolean installForwardLocked(int installFlags) {
10388        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10389    }
10390
10391    private InstallArgs createInstallArgs(InstallParams params) {
10392        if (params.move != null) {
10393            return new MoveInstallArgs(params);
10394        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
10395            return new AsecInstallArgs(params);
10396        } else {
10397            return new FileInstallArgs(params);
10398        }
10399    }
10400
10401    /**
10402     * Create args that describe an existing installed package. Typically used
10403     * when cleaning up old installs, or used as a move source.
10404     */
10405    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
10406            String resourcePath, String[] instructionSets) {
10407        final boolean isInAsec;
10408        if (installOnExternalAsec(installFlags)) {
10409            /* Apps on SD card are always in ASEC containers. */
10410            isInAsec = true;
10411        } else if (installForwardLocked(installFlags)
10412                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
10413            /*
10414             * Forward-locked apps are only in ASEC containers if they're the
10415             * new style
10416             */
10417            isInAsec = true;
10418        } else {
10419            isInAsec = false;
10420        }
10421
10422        if (isInAsec) {
10423            return new AsecInstallArgs(codePath, instructionSets,
10424                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
10425        } else {
10426            return new FileInstallArgs(codePath, resourcePath, instructionSets);
10427        }
10428    }
10429
10430    static abstract class InstallArgs {
10431        /** @see InstallParams#origin */
10432        final OriginInfo origin;
10433        /** @see InstallParams#move */
10434        final MoveInfo move;
10435
10436        final IPackageInstallObserver2 observer;
10437        // Always refers to PackageManager flags only
10438        final int installFlags;
10439        final String installerPackageName;
10440        final String volumeUuid;
10441        final ManifestDigest manifestDigest;
10442        final UserHandle user;
10443        final String abiOverride;
10444
10445        // The list of instruction sets supported by this app. This is currently
10446        // only used during the rmdex() phase to clean up resources. We can get rid of this
10447        // if we move dex files under the common app path.
10448        /* nullable */ String[] instructionSets;
10449
10450        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10451                int installFlags, String installerPackageName, String volumeUuid,
10452                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
10453                String abiOverride) {
10454            this.origin = origin;
10455            this.move = move;
10456            this.installFlags = installFlags;
10457            this.observer = observer;
10458            this.installerPackageName = installerPackageName;
10459            this.volumeUuid = volumeUuid;
10460            this.manifestDigest = manifestDigest;
10461            this.user = user;
10462            this.instructionSets = instructionSets;
10463            this.abiOverride = abiOverride;
10464        }
10465
10466        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
10467        abstract int doPreInstall(int status);
10468
10469        /**
10470         * Rename package into final resting place. All paths on the given
10471         * scanned package should be updated to reflect the rename.
10472         */
10473        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
10474        abstract int doPostInstall(int status, int uid);
10475
10476        /** @see PackageSettingBase#codePathString */
10477        abstract String getCodePath();
10478        /** @see PackageSettingBase#resourcePathString */
10479        abstract String getResourcePath();
10480
10481        // Need installer lock especially for dex file removal.
10482        abstract void cleanUpResourcesLI();
10483        abstract boolean doPostDeleteLI(boolean delete);
10484
10485        /**
10486         * Called before the source arguments are copied. This is used mostly
10487         * for MoveParams when it needs to read the source file to put it in the
10488         * destination.
10489         */
10490        int doPreCopy() {
10491            return PackageManager.INSTALL_SUCCEEDED;
10492        }
10493
10494        /**
10495         * Called after the source arguments are copied. This is used mostly for
10496         * MoveParams when it needs to read the source file to put it in the
10497         * destination.
10498         *
10499         * @return
10500         */
10501        int doPostCopy(int uid) {
10502            return PackageManager.INSTALL_SUCCEEDED;
10503        }
10504
10505        protected boolean isFwdLocked() {
10506            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10507        }
10508
10509        protected boolean isExternalAsec() {
10510            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10511        }
10512
10513        UserHandle getUser() {
10514            return user;
10515        }
10516    }
10517
10518    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
10519        if (!allCodePaths.isEmpty()) {
10520            if (instructionSets == null) {
10521                throw new IllegalStateException("instructionSet == null");
10522            }
10523            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
10524            for (String codePath : allCodePaths) {
10525                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
10526                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
10527                    if (retCode < 0) {
10528                        Slog.w(TAG, "Couldn't remove dex file for package: "
10529                                + " at location " + codePath + ", retcode=" + retCode);
10530                        // we don't consider this to be a failure of the core package deletion
10531                    }
10532                }
10533            }
10534        }
10535    }
10536
10537    /**
10538     * Logic to handle installation of non-ASEC applications, including copying
10539     * and renaming logic.
10540     */
10541    class FileInstallArgs extends InstallArgs {
10542        private File codeFile;
10543        private File resourceFile;
10544
10545        // Example topology:
10546        // /data/app/com.example/base.apk
10547        // /data/app/com.example/split_foo.apk
10548        // /data/app/com.example/lib/arm/libfoo.so
10549        // /data/app/com.example/lib/arm64/libfoo.so
10550        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
10551
10552        /** New install */
10553        FileInstallArgs(InstallParams params) {
10554            super(params.origin, params.move, params.observer, params.installFlags,
10555                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10556                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10557            if (isFwdLocked()) {
10558                throw new IllegalArgumentException("Forward locking only supported in ASEC");
10559            }
10560        }
10561
10562        /** Existing install */
10563        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
10564            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
10565                    null);
10566            this.codeFile = (codePath != null) ? new File(codePath) : null;
10567            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
10568        }
10569
10570        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10571            if (origin.staged) {
10572                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
10573                codeFile = origin.file;
10574                resourceFile = origin.file;
10575                return PackageManager.INSTALL_SUCCEEDED;
10576            }
10577
10578            try {
10579                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
10580                codeFile = tempDir;
10581                resourceFile = tempDir;
10582            } catch (IOException e) {
10583                Slog.w(TAG, "Failed to create copy file: " + e);
10584                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10585            }
10586
10587            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
10588                @Override
10589                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
10590                    if (!FileUtils.isValidExtFilename(name)) {
10591                        throw new IllegalArgumentException("Invalid filename: " + name);
10592                    }
10593                    try {
10594                        final File file = new File(codeFile, name);
10595                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
10596                                O_RDWR | O_CREAT, 0644);
10597                        Os.chmod(file.getAbsolutePath(), 0644);
10598                        return new ParcelFileDescriptor(fd);
10599                    } catch (ErrnoException e) {
10600                        throw new RemoteException("Failed to open: " + e.getMessage());
10601                    }
10602                }
10603            };
10604
10605            int ret = PackageManager.INSTALL_SUCCEEDED;
10606            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
10607            if (ret != PackageManager.INSTALL_SUCCEEDED) {
10608                Slog.e(TAG, "Failed to copy package");
10609                return ret;
10610            }
10611
10612            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
10613            NativeLibraryHelper.Handle handle = null;
10614            try {
10615                handle = NativeLibraryHelper.Handle.create(codeFile);
10616                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
10617                        abiOverride);
10618            } catch (IOException e) {
10619                Slog.e(TAG, "Copying native libraries failed", e);
10620                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10621            } finally {
10622                IoUtils.closeQuietly(handle);
10623            }
10624
10625            return ret;
10626        }
10627
10628        int doPreInstall(int status) {
10629            if (status != PackageManager.INSTALL_SUCCEEDED) {
10630                cleanUp();
10631            }
10632            return status;
10633        }
10634
10635        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10636            if (status != PackageManager.INSTALL_SUCCEEDED) {
10637                cleanUp();
10638                return false;
10639            }
10640
10641            final File targetDir = codeFile.getParentFile();
10642            final File beforeCodeFile = codeFile;
10643            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
10644
10645            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
10646            try {
10647                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
10648            } catch (ErrnoException e) {
10649                Slog.w(TAG, "Failed to rename", e);
10650                return false;
10651            }
10652
10653            if (!SELinux.restoreconRecursive(afterCodeFile)) {
10654                Slog.w(TAG, "Failed to restorecon");
10655                return false;
10656            }
10657
10658            // Reflect the rename internally
10659            codeFile = afterCodeFile;
10660            resourceFile = afterCodeFile;
10661
10662            // Reflect the rename in scanned details
10663            pkg.codePath = afterCodeFile.getAbsolutePath();
10664            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10665                    pkg.baseCodePath);
10666            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10667                    pkg.splitCodePaths);
10668
10669            // Reflect the rename in app info
10670            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10671            pkg.applicationInfo.setCodePath(pkg.codePath);
10672            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10673            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10674            pkg.applicationInfo.setResourcePath(pkg.codePath);
10675            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10676            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10677
10678            return true;
10679        }
10680
10681        int doPostInstall(int status, int uid) {
10682            if (status != PackageManager.INSTALL_SUCCEEDED) {
10683                cleanUp();
10684            }
10685            return status;
10686        }
10687
10688        @Override
10689        String getCodePath() {
10690            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
10691        }
10692
10693        @Override
10694        String getResourcePath() {
10695            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
10696        }
10697
10698        private boolean cleanUp() {
10699            if (codeFile == null || !codeFile.exists()) {
10700                return false;
10701            }
10702
10703            if (codeFile.isDirectory()) {
10704                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
10705            } else {
10706                codeFile.delete();
10707            }
10708
10709            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
10710                resourceFile.delete();
10711            }
10712
10713            return true;
10714        }
10715
10716        void cleanUpResourcesLI() {
10717            // Try enumerating all code paths before deleting
10718            List<String> allCodePaths = Collections.EMPTY_LIST;
10719            if (codeFile != null && codeFile.exists()) {
10720                try {
10721                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
10722                    allCodePaths = pkg.getAllCodePaths();
10723                } catch (PackageParserException e) {
10724                    // Ignored; we tried our best
10725                }
10726            }
10727
10728            cleanUp();
10729            removeDexFiles(allCodePaths, instructionSets);
10730        }
10731
10732        boolean doPostDeleteLI(boolean delete) {
10733            // XXX err, shouldn't we respect the delete flag?
10734            cleanUpResourcesLI();
10735            return true;
10736        }
10737    }
10738
10739    private boolean isAsecExternal(String cid) {
10740        final String asecPath = PackageHelper.getSdFilesystem(cid);
10741        return !asecPath.startsWith(mAsecInternalPath);
10742    }
10743
10744    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
10745            PackageManagerException {
10746        if (copyRet < 0) {
10747            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
10748                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
10749                throw new PackageManagerException(copyRet, message);
10750            }
10751        }
10752    }
10753
10754    /**
10755     * Extract the MountService "container ID" from the full code path of an
10756     * .apk.
10757     */
10758    static String cidFromCodePath(String fullCodePath) {
10759        int eidx = fullCodePath.lastIndexOf("/");
10760        String subStr1 = fullCodePath.substring(0, eidx);
10761        int sidx = subStr1.lastIndexOf("/");
10762        return subStr1.substring(sidx+1, eidx);
10763    }
10764
10765    /**
10766     * Logic to handle installation of ASEC applications, including copying and
10767     * renaming logic.
10768     */
10769    class AsecInstallArgs extends InstallArgs {
10770        static final String RES_FILE_NAME = "pkg.apk";
10771        static final String PUBLIC_RES_FILE_NAME = "res.zip";
10772
10773        String cid;
10774        String packagePath;
10775        String resourcePath;
10776
10777        /** New install */
10778        AsecInstallArgs(InstallParams params) {
10779            super(params.origin, params.move, params.observer, params.installFlags,
10780                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10781                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10782        }
10783
10784        /** Existing install */
10785        AsecInstallArgs(String fullCodePath, String[] instructionSets,
10786                        boolean isExternal, boolean isForwardLocked) {
10787            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
10788                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
10789                    instructionSets, null);
10790            // Hackily pretend we're still looking at a full code path
10791            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
10792                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
10793            }
10794
10795            // Extract cid from fullCodePath
10796            int eidx = fullCodePath.lastIndexOf("/");
10797            String subStr1 = fullCodePath.substring(0, eidx);
10798            int sidx = subStr1.lastIndexOf("/");
10799            cid = subStr1.substring(sidx+1, eidx);
10800            setMountPath(subStr1);
10801        }
10802
10803        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
10804            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
10805                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
10806                    instructionSets, null);
10807            this.cid = cid;
10808            setMountPath(PackageHelper.getSdDir(cid));
10809        }
10810
10811        void createCopyFile() {
10812            cid = mInstallerService.allocateExternalStageCidLegacy();
10813        }
10814
10815        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10816            if (origin.staged) {
10817                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
10818                cid = origin.cid;
10819                setMountPath(PackageHelper.getSdDir(cid));
10820                return PackageManager.INSTALL_SUCCEEDED;
10821            }
10822
10823            if (temp) {
10824                createCopyFile();
10825            } else {
10826                /*
10827                 * Pre-emptively destroy the container since it's destroyed if
10828                 * copying fails due to it existing anyway.
10829                 */
10830                PackageHelper.destroySdDir(cid);
10831            }
10832
10833            final String newMountPath = imcs.copyPackageToContainer(
10834                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
10835                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
10836
10837            if (newMountPath != null) {
10838                setMountPath(newMountPath);
10839                return PackageManager.INSTALL_SUCCEEDED;
10840            } else {
10841                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10842            }
10843        }
10844
10845        @Override
10846        String getCodePath() {
10847            return packagePath;
10848        }
10849
10850        @Override
10851        String getResourcePath() {
10852            return resourcePath;
10853        }
10854
10855        int doPreInstall(int status) {
10856            if (status != PackageManager.INSTALL_SUCCEEDED) {
10857                // Destroy container
10858                PackageHelper.destroySdDir(cid);
10859            } else {
10860                boolean mounted = PackageHelper.isContainerMounted(cid);
10861                if (!mounted) {
10862                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
10863                            Process.SYSTEM_UID);
10864                    if (newMountPath != null) {
10865                        setMountPath(newMountPath);
10866                    } else {
10867                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10868                    }
10869                }
10870            }
10871            return status;
10872        }
10873
10874        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10875            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
10876            String newMountPath = null;
10877            if (PackageHelper.isContainerMounted(cid)) {
10878                // Unmount the container
10879                if (!PackageHelper.unMountSdDir(cid)) {
10880                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
10881                    return false;
10882                }
10883            }
10884            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
10885                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
10886                        " which might be stale. Will try to clean up.");
10887                // Clean up the stale container and proceed to recreate.
10888                if (!PackageHelper.destroySdDir(newCacheId)) {
10889                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
10890                    return false;
10891                }
10892                // Successfully cleaned up stale container. Try to rename again.
10893                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
10894                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
10895                            + " inspite of cleaning it up.");
10896                    return false;
10897                }
10898            }
10899            if (!PackageHelper.isContainerMounted(newCacheId)) {
10900                Slog.w(TAG, "Mounting container " + newCacheId);
10901                newMountPath = PackageHelper.mountSdDir(newCacheId,
10902                        getEncryptKey(), Process.SYSTEM_UID);
10903            } else {
10904                newMountPath = PackageHelper.getSdDir(newCacheId);
10905            }
10906            if (newMountPath == null) {
10907                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
10908                return false;
10909            }
10910            Log.i(TAG, "Succesfully renamed " + cid +
10911                    " to " + newCacheId +
10912                    " at new path: " + newMountPath);
10913            cid = newCacheId;
10914
10915            final File beforeCodeFile = new File(packagePath);
10916            setMountPath(newMountPath);
10917            final File afterCodeFile = new File(packagePath);
10918
10919            // Reflect the rename in scanned details
10920            pkg.codePath = afterCodeFile.getAbsolutePath();
10921            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10922                    pkg.baseCodePath);
10923            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10924                    pkg.splitCodePaths);
10925
10926            // Reflect the rename in app info
10927            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10928            pkg.applicationInfo.setCodePath(pkg.codePath);
10929            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10930            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10931            pkg.applicationInfo.setResourcePath(pkg.codePath);
10932            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10933            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10934
10935            return true;
10936        }
10937
10938        private void setMountPath(String mountPath) {
10939            final File mountFile = new File(mountPath);
10940
10941            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
10942            if (monolithicFile.exists()) {
10943                packagePath = monolithicFile.getAbsolutePath();
10944                if (isFwdLocked()) {
10945                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
10946                } else {
10947                    resourcePath = packagePath;
10948                }
10949            } else {
10950                packagePath = mountFile.getAbsolutePath();
10951                resourcePath = packagePath;
10952            }
10953        }
10954
10955        int doPostInstall(int status, int uid) {
10956            if (status != PackageManager.INSTALL_SUCCEEDED) {
10957                cleanUp();
10958            } else {
10959                final int groupOwner;
10960                final String protectedFile;
10961                if (isFwdLocked()) {
10962                    groupOwner = UserHandle.getSharedAppGid(uid);
10963                    protectedFile = RES_FILE_NAME;
10964                } else {
10965                    groupOwner = -1;
10966                    protectedFile = null;
10967                }
10968
10969                if (uid < Process.FIRST_APPLICATION_UID
10970                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
10971                    Slog.e(TAG, "Failed to finalize " + cid);
10972                    PackageHelper.destroySdDir(cid);
10973                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10974                }
10975
10976                boolean mounted = PackageHelper.isContainerMounted(cid);
10977                if (!mounted) {
10978                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
10979                }
10980            }
10981            return status;
10982        }
10983
10984        private void cleanUp() {
10985            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
10986
10987            // Destroy secure container
10988            PackageHelper.destroySdDir(cid);
10989        }
10990
10991        private List<String> getAllCodePaths() {
10992            final File codeFile = new File(getCodePath());
10993            if (codeFile != null && codeFile.exists()) {
10994                try {
10995                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
10996                    return pkg.getAllCodePaths();
10997                } catch (PackageParserException e) {
10998                    // Ignored; we tried our best
10999                }
11000            }
11001            return Collections.EMPTY_LIST;
11002        }
11003
11004        void cleanUpResourcesLI() {
11005            // Enumerate all code paths before deleting
11006            cleanUpResourcesLI(getAllCodePaths());
11007        }
11008
11009        private void cleanUpResourcesLI(List<String> allCodePaths) {
11010            cleanUp();
11011            removeDexFiles(allCodePaths, instructionSets);
11012        }
11013
11014        String getPackageName() {
11015            return getAsecPackageName(cid);
11016        }
11017
11018        boolean doPostDeleteLI(boolean delete) {
11019            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
11020            final List<String> allCodePaths = getAllCodePaths();
11021            boolean mounted = PackageHelper.isContainerMounted(cid);
11022            if (mounted) {
11023                // Unmount first
11024                if (PackageHelper.unMountSdDir(cid)) {
11025                    mounted = false;
11026                }
11027            }
11028            if (!mounted && delete) {
11029                cleanUpResourcesLI(allCodePaths);
11030            }
11031            return !mounted;
11032        }
11033
11034        @Override
11035        int doPreCopy() {
11036            if (isFwdLocked()) {
11037                if (!PackageHelper.fixSdPermissions(cid,
11038                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
11039                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11040                }
11041            }
11042
11043            return PackageManager.INSTALL_SUCCEEDED;
11044        }
11045
11046        @Override
11047        int doPostCopy(int uid) {
11048            if (isFwdLocked()) {
11049                if (uid < Process.FIRST_APPLICATION_UID
11050                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
11051                                RES_FILE_NAME)) {
11052                    Slog.e(TAG, "Failed to finalize " + cid);
11053                    PackageHelper.destroySdDir(cid);
11054                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11055                }
11056            }
11057
11058            return PackageManager.INSTALL_SUCCEEDED;
11059        }
11060    }
11061
11062    /**
11063     * Logic to handle movement of existing installed applications.
11064     */
11065    class MoveInstallArgs extends InstallArgs {
11066        private File codeFile;
11067        private File resourceFile;
11068
11069        /** New install */
11070        MoveInstallArgs(InstallParams params) {
11071            super(params.origin, params.move, params.observer, params.installFlags,
11072                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11073                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
11074        }
11075
11076        int copyApk(IMediaContainerService imcs, boolean temp) {
11077            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
11078                    + move.fromUuid + " to " + move.toUuid);
11079            synchronized (mInstaller) {
11080                if (mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
11081                        move.dataAppName, move.appId, move.seinfo) != 0) {
11082                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11083                }
11084            }
11085
11086            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
11087            resourceFile = codeFile;
11088            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
11089
11090            return PackageManager.INSTALL_SUCCEEDED;
11091        }
11092
11093        int doPreInstall(int status) {
11094            if (status != PackageManager.INSTALL_SUCCEEDED) {
11095                cleanUp();
11096            }
11097            return status;
11098        }
11099
11100        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11101            if (status != PackageManager.INSTALL_SUCCEEDED) {
11102                cleanUp();
11103                return false;
11104            }
11105
11106            // Reflect the move in app info
11107            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11108            pkg.applicationInfo.setCodePath(pkg.codePath);
11109            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11110            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11111            pkg.applicationInfo.setResourcePath(pkg.codePath);
11112            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11113            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11114
11115            return true;
11116        }
11117
11118        int doPostInstall(int status, int uid) {
11119            if (status != PackageManager.INSTALL_SUCCEEDED) {
11120                cleanUp();
11121            }
11122            return status;
11123        }
11124
11125        @Override
11126        String getCodePath() {
11127            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11128        }
11129
11130        @Override
11131        String getResourcePath() {
11132            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11133        }
11134
11135        private boolean cleanUp() {
11136            if (codeFile == null || !codeFile.exists()) {
11137                return false;
11138            }
11139
11140            if (codeFile.isDirectory()) {
11141                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11142            } else {
11143                codeFile.delete();
11144            }
11145
11146            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11147                resourceFile.delete();
11148            }
11149
11150            return true;
11151        }
11152
11153        void cleanUpResourcesLI() {
11154            cleanUp();
11155        }
11156
11157        boolean doPostDeleteLI(boolean delete) {
11158            // XXX err, shouldn't we respect the delete flag?
11159            cleanUpResourcesLI();
11160            return true;
11161        }
11162    }
11163
11164    static String getAsecPackageName(String packageCid) {
11165        int idx = packageCid.lastIndexOf("-");
11166        if (idx == -1) {
11167            return packageCid;
11168        }
11169        return packageCid.substring(0, idx);
11170    }
11171
11172    // Utility method used to create code paths based on package name and available index.
11173    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
11174        String idxStr = "";
11175        int idx = 1;
11176        // Fall back to default value of idx=1 if prefix is not
11177        // part of oldCodePath
11178        if (oldCodePath != null) {
11179            String subStr = oldCodePath;
11180            // Drop the suffix right away
11181            if (suffix != null && subStr.endsWith(suffix)) {
11182                subStr = subStr.substring(0, subStr.length() - suffix.length());
11183            }
11184            // If oldCodePath already contains prefix find out the
11185            // ending index to either increment or decrement.
11186            int sidx = subStr.lastIndexOf(prefix);
11187            if (sidx != -1) {
11188                subStr = subStr.substring(sidx + prefix.length());
11189                if (subStr != null) {
11190                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
11191                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
11192                    }
11193                    try {
11194                        idx = Integer.parseInt(subStr);
11195                        if (idx <= 1) {
11196                            idx++;
11197                        } else {
11198                            idx--;
11199                        }
11200                    } catch(NumberFormatException e) {
11201                    }
11202                }
11203            }
11204        }
11205        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
11206        return prefix + idxStr;
11207    }
11208
11209    private File getNextCodePath(File targetDir, String packageName) {
11210        int suffix = 1;
11211        File result;
11212        do {
11213            result = new File(targetDir, packageName + "-" + suffix);
11214            suffix++;
11215        } while (result.exists());
11216        return result;
11217    }
11218
11219    // Utility method that returns the relative package path with respect
11220    // to the installation directory. Like say for /data/data/com.test-1.apk
11221    // string com.test-1 is returned.
11222    static String deriveCodePathName(String codePath) {
11223        if (codePath == null) {
11224            return null;
11225        }
11226        final File codeFile = new File(codePath);
11227        final String name = codeFile.getName();
11228        if (codeFile.isDirectory()) {
11229            return name;
11230        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
11231            final int lastDot = name.lastIndexOf('.');
11232            return name.substring(0, lastDot);
11233        } else {
11234            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11235            return null;
11236        }
11237    }
11238
11239    class PackageInstalledInfo {
11240        String name;
11241        int uid;
11242        // The set of users that originally had this package installed.
11243        int[] origUsers;
11244        // The set of users that now have this package installed.
11245        int[] newUsers;
11246        PackageParser.Package pkg;
11247        int returnCode;
11248        String returnMsg;
11249        PackageRemovedInfo removedInfo;
11250
11251        public void setError(int code, String msg) {
11252            returnCode = code;
11253            returnMsg = msg;
11254            Slog.w(TAG, msg);
11255        }
11256
11257        public void setError(String msg, PackageParserException e) {
11258            returnCode = e.error;
11259            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11260            Slog.w(TAG, msg, e);
11261        }
11262
11263        public void setError(String msg, PackageManagerException e) {
11264            returnCode = e.error;
11265            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11266            Slog.w(TAG, msg, e);
11267        }
11268
11269        // In some error cases we want to convey more info back to the observer
11270        String origPackage;
11271        String origPermission;
11272    }
11273
11274    /*
11275     * Install a non-existing package.
11276     */
11277    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11278            UserHandle user, String installerPackageName, String volumeUuid,
11279            PackageInstalledInfo res) {
11280        // Remember this for later, in case we need to rollback this install
11281        String pkgName = pkg.packageName;
11282
11283        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
11284        final boolean dataDirExists = PackageManager.getDataDirForUser(volumeUuid, pkgName,
11285                UserHandle.USER_OWNER).exists();
11286        synchronized(mPackages) {
11287            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
11288                // A package with the same name is already installed, though
11289                // it has been renamed to an older name.  The package we
11290                // are trying to install should be installed as an update to
11291                // the existing one, but that has not been requested, so bail.
11292                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11293                        + " without first uninstalling package running as "
11294                        + mSettings.mRenamedPackages.get(pkgName));
11295                return;
11296            }
11297            if (mPackages.containsKey(pkgName)) {
11298                // Don't allow installation over an existing package with the same name.
11299                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11300                        + " without first uninstalling.");
11301                return;
11302            }
11303        }
11304
11305        try {
11306            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
11307                    System.currentTimeMillis(), user);
11308
11309            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
11310            // delete the partially installed application. the data directory will have to be
11311            // restored if it was already existing
11312            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11313                // remove package from internal structures.  Note that we want deletePackageX to
11314                // delete the package data and cache directories that it created in
11315                // scanPackageLocked, unless those directories existed before we even tried to
11316                // install.
11317                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
11318                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
11319                                res.removedInfo, true);
11320            }
11321
11322        } catch (PackageManagerException e) {
11323            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11324        }
11325    }
11326
11327    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
11328        // Can't rotate keys during boot or if sharedUser.
11329        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
11330                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
11331            return false;
11332        }
11333        // app is using upgradeKeySets; make sure all are valid
11334        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11335        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
11336        for (int i = 0; i < upgradeKeySets.length; i++) {
11337            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
11338                Slog.wtf(TAG, "Package "
11339                         + (oldPs.name != null ? oldPs.name : "<null>")
11340                         + " contains upgrade-key-set reference to unknown key-set: "
11341                         + upgradeKeySets[i]
11342                         + " reverting to signatures check.");
11343                return false;
11344            }
11345        }
11346        return true;
11347    }
11348
11349    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
11350        // Upgrade keysets are being used.  Determine if new package has a superset of the
11351        // required keys.
11352        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
11353        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11354        for (int i = 0; i < upgradeKeySets.length; i++) {
11355            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
11356            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
11357                return true;
11358            }
11359        }
11360        return false;
11361    }
11362
11363    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11364            UserHandle user, String installerPackageName, String volumeUuid,
11365            PackageInstalledInfo res) {
11366        final PackageParser.Package oldPackage;
11367        final String pkgName = pkg.packageName;
11368        final int[] allUsers;
11369        final boolean[] perUserInstalled;
11370        final boolean weFroze;
11371
11372        // First find the old package info and check signatures
11373        synchronized(mPackages) {
11374            oldPackage = mPackages.get(pkgName);
11375            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
11376            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11377            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11378                if(!checkUpgradeKeySetLP(ps, pkg)) {
11379                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11380                            "New package not signed by keys specified by upgrade-keysets: "
11381                            + pkgName);
11382                    return;
11383                }
11384            } else {
11385                // default to original signature matching
11386                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
11387                    != PackageManager.SIGNATURE_MATCH) {
11388                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11389                            "New package has a different signature: " + pkgName);
11390                    return;
11391                }
11392            }
11393
11394            // In case of rollback, remember per-user/profile install state
11395            allUsers = sUserManager.getUserIds();
11396            perUserInstalled = new boolean[allUsers.length];
11397            for (int i = 0; i < allUsers.length; i++) {
11398                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11399            }
11400
11401            // Mark the app as frozen to prevent launching during the upgrade
11402            // process, and then kill all running instances
11403            if (!ps.frozen) {
11404                ps.frozen = true;
11405                weFroze = true;
11406            } else {
11407                weFroze = false;
11408            }
11409        }
11410
11411        // Now that we're guarded by frozen state, kill app during upgrade
11412        killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg");
11413
11414        try {
11415            boolean sysPkg = (isSystemApp(oldPackage));
11416            if (sysPkg) {
11417                replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11418                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11419            } else {
11420                replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11421                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11422            }
11423        } finally {
11424            // Regardless of success or failure of upgrade steps above, always
11425            // unfreeze the package if we froze it
11426            if (weFroze) {
11427                unfreezePackage(pkgName);
11428            }
11429        }
11430    }
11431
11432    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
11433            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11434            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11435            String volumeUuid, PackageInstalledInfo res) {
11436        String pkgName = deletedPackage.packageName;
11437        boolean deletedPkg = true;
11438        boolean updatedSettings = false;
11439
11440        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
11441                + deletedPackage);
11442        long origUpdateTime;
11443        if (pkg.mExtras != null) {
11444            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
11445        } else {
11446            origUpdateTime = 0;
11447        }
11448
11449        // First delete the existing package while retaining the data directory
11450        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
11451                res.removedInfo, true)) {
11452            // If the existing package wasn't successfully deleted
11453            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
11454            deletedPkg = false;
11455        } else {
11456            // Successfully deleted the old package; proceed with replace.
11457
11458            // If deleted package lived in a container, give users a chance to
11459            // relinquish resources before killing.
11460            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
11461                if (DEBUG_INSTALL) {
11462                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
11463                }
11464                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
11465                final ArrayList<String> pkgList = new ArrayList<String>(1);
11466                pkgList.add(deletedPackage.applicationInfo.packageName);
11467                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
11468            }
11469
11470            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
11471            try {
11472                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
11473                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
11474                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11475                        perUserInstalled, res, user);
11476                updatedSettings = true;
11477            } catch (PackageManagerException e) {
11478                res.setError("Package couldn't be installed in " + pkg.codePath, e);
11479            }
11480        }
11481
11482        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11483            // remove package from internal structures.  Note that we want deletePackageX to
11484            // delete the package data and cache directories that it created in
11485            // scanPackageLocked, unless those directories existed before we even tried to
11486            // install.
11487            if(updatedSettings) {
11488                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
11489                deletePackageLI(
11490                        pkgName, null, true, allUsers, perUserInstalled,
11491                        PackageManager.DELETE_KEEP_DATA,
11492                                res.removedInfo, true);
11493            }
11494            // Since we failed to install the new package we need to restore the old
11495            // package that we deleted.
11496            if (deletedPkg) {
11497                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
11498                File restoreFile = new File(deletedPackage.codePath);
11499                // Parse old package
11500                boolean oldExternal = isExternal(deletedPackage);
11501                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
11502                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
11503                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11504                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
11505                try {
11506                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
11507                } catch (PackageManagerException e) {
11508                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
11509                            + e.getMessage());
11510                    return;
11511                }
11512                // Restore of old package succeeded. Update permissions.
11513                // writer
11514                synchronized (mPackages) {
11515                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
11516                            UPDATE_PERMISSIONS_ALL);
11517                    // can downgrade to reader
11518                    mSettings.writeLPr();
11519                }
11520                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
11521            }
11522        }
11523    }
11524
11525    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
11526            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11527            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11528            String volumeUuid, PackageInstalledInfo res) {
11529        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
11530                + ", old=" + deletedPackage);
11531        boolean disabledSystem = false;
11532        boolean updatedSettings = false;
11533        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
11534        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
11535                != 0) {
11536            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11537        }
11538        String packageName = deletedPackage.packageName;
11539        if (packageName == null) {
11540            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11541                    "Attempt to delete null packageName.");
11542            return;
11543        }
11544        PackageParser.Package oldPkg;
11545        PackageSetting oldPkgSetting;
11546        // reader
11547        synchronized (mPackages) {
11548            oldPkg = mPackages.get(packageName);
11549            oldPkgSetting = mSettings.mPackages.get(packageName);
11550            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
11551                    (oldPkgSetting == null)) {
11552                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11553                        "Couldn't find package:" + packageName + " information");
11554                return;
11555            }
11556        }
11557
11558        res.removedInfo.uid = oldPkg.applicationInfo.uid;
11559        res.removedInfo.removedPackage = packageName;
11560        // Remove existing system package
11561        removePackageLI(oldPkgSetting, true);
11562        // writer
11563        synchronized (mPackages) {
11564            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
11565            if (!disabledSystem && deletedPackage != null) {
11566                // We didn't need to disable the .apk as a current system package,
11567                // which means we are replacing another update that is already
11568                // installed.  We need to make sure to delete the older one's .apk.
11569                res.removedInfo.args = createInstallArgsForExisting(0,
11570                        deletedPackage.applicationInfo.getCodePath(),
11571                        deletedPackage.applicationInfo.getResourcePath(),
11572                        getAppDexInstructionSets(deletedPackage.applicationInfo));
11573            } else {
11574                res.removedInfo.args = null;
11575            }
11576        }
11577
11578        // Successfully disabled the old package. Now proceed with re-installation
11579        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
11580
11581        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11582        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
11583
11584        PackageParser.Package newPackage = null;
11585        try {
11586            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
11587            if (newPackage.mExtras != null) {
11588                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
11589                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
11590                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
11591
11592                // is the update attempting to change shared user? that isn't going to work...
11593                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
11594                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
11595                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
11596                            + " to " + newPkgSetting.sharedUser);
11597                    updatedSettings = true;
11598                }
11599            }
11600
11601            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11602                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11603                        perUserInstalled, res, user);
11604                updatedSettings = true;
11605            }
11606
11607        } catch (PackageManagerException e) {
11608            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11609        }
11610
11611        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11612            // Re installation failed. Restore old information
11613            // Remove new pkg information
11614            if (newPackage != null) {
11615                removeInstalledPackageLI(newPackage, true);
11616            }
11617            // Add back the old system package
11618            try {
11619                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
11620            } catch (PackageManagerException e) {
11621                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
11622            }
11623            // Restore the old system information in Settings
11624            synchronized (mPackages) {
11625                if (disabledSystem) {
11626                    mSettings.enableSystemPackageLPw(packageName);
11627                }
11628                if (updatedSettings) {
11629                    mSettings.setInstallerPackageName(packageName,
11630                            oldPkgSetting.installerPackageName);
11631                }
11632                mSettings.writeLPr();
11633            }
11634        }
11635    }
11636
11637    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
11638            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
11639            UserHandle user) {
11640        String pkgName = newPackage.packageName;
11641        synchronized (mPackages) {
11642            //write settings. the installStatus will be incomplete at this stage.
11643            //note that the new package setting would have already been
11644            //added to mPackages. It hasn't been persisted yet.
11645            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
11646            mSettings.writeLPr();
11647        }
11648
11649        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
11650
11651        synchronized (mPackages) {
11652            updatePermissionsLPw(newPackage.packageName, newPackage,
11653                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
11654                            ? UPDATE_PERMISSIONS_ALL : 0));
11655            // For system-bundled packages, we assume that installing an upgraded version
11656            // of the package implies that the user actually wants to run that new code,
11657            // so we enable the package.
11658            PackageSetting ps = mSettings.mPackages.get(pkgName);
11659            if (ps != null) {
11660                if (isSystemApp(newPackage)) {
11661                    // NB: implicit assumption that system package upgrades apply to all users
11662                    if (DEBUG_INSTALL) {
11663                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
11664                    }
11665                    if (res.origUsers != null) {
11666                        for (int userHandle : res.origUsers) {
11667                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
11668                                    userHandle, installerPackageName);
11669                        }
11670                    }
11671                    // Also convey the prior install/uninstall state
11672                    if (allUsers != null && perUserInstalled != null) {
11673                        for (int i = 0; i < allUsers.length; i++) {
11674                            if (DEBUG_INSTALL) {
11675                                Slog.d(TAG, "    user " + allUsers[i]
11676                                        + " => " + perUserInstalled[i]);
11677                            }
11678                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
11679                        }
11680                        // these install state changes will be persisted in the
11681                        // upcoming call to mSettings.writeLPr().
11682                    }
11683                }
11684                // It's implied that when a user requests installation, they want the app to be
11685                // installed and enabled.
11686                int userId = user.getIdentifier();
11687                if (userId != UserHandle.USER_ALL) {
11688                    ps.setInstalled(true, userId);
11689                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
11690                }
11691            }
11692            res.name = pkgName;
11693            res.uid = newPackage.applicationInfo.uid;
11694            res.pkg = newPackage;
11695            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
11696            mSettings.setInstallerPackageName(pkgName, installerPackageName);
11697            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11698            //to update install status
11699            mSettings.writeLPr();
11700        }
11701    }
11702
11703    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
11704        final int installFlags = args.installFlags;
11705        final String installerPackageName = args.installerPackageName;
11706        final String volumeUuid = args.volumeUuid;
11707        final File tmpPackageFile = new File(args.getCodePath());
11708        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
11709        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
11710                || (args.volumeUuid != null));
11711        boolean replace = false;
11712        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
11713        if (args.move != null) {
11714            // moving a complete application; perfom an initial scan on the new install location
11715            scanFlags |= SCAN_INITIAL;
11716        }
11717        // Result object to be returned
11718        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11719
11720        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
11721        // Retrieve PackageSettings and parse package
11722        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
11723                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
11724                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11725        PackageParser pp = new PackageParser();
11726        pp.setSeparateProcesses(mSeparateProcesses);
11727        pp.setDisplayMetrics(mMetrics);
11728
11729        final PackageParser.Package pkg;
11730        try {
11731            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
11732        } catch (PackageParserException e) {
11733            res.setError("Failed parse during installPackageLI", e);
11734            return;
11735        }
11736
11737        // Mark that we have an install time CPU ABI override.
11738        pkg.cpuAbiOverride = args.abiOverride;
11739
11740        String pkgName = res.name = pkg.packageName;
11741        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
11742            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
11743                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
11744                return;
11745            }
11746        }
11747
11748        try {
11749            pp.collectCertificates(pkg, parseFlags);
11750            pp.collectManifestDigest(pkg);
11751        } catch (PackageParserException e) {
11752            res.setError("Failed collect during installPackageLI", e);
11753            return;
11754        }
11755
11756        /* If the installer passed in a manifest digest, compare it now. */
11757        if (args.manifestDigest != null) {
11758            if (DEBUG_INSTALL) {
11759                final String parsedManifest = pkg.manifestDigest == null ? "null"
11760                        : pkg.manifestDigest.toString();
11761                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
11762                        + parsedManifest);
11763            }
11764
11765            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
11766                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
11767                return;
11768            }
11769        } else if (DEBUG_INSTALL) {
11770            final String parsedManifest = pkg.manifestDigest == null
11771                    ? "null" : pkg.manifestDigest.toString();
11772            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
11773        }
11774
11775        // Get rid of all references to package scan path via parser.
11776        pp = null;
11777        String oldCodePath = null;
11778        boolean systemApp = false;
11779        synchronized (mPackages) {
11780            // Check if installing already existing package
11781            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
11782                String oldName = mSettings.mRenamedPackages.get(pkgName);
11783                if (pkg.mOriginalPackages != null
11784                        && pkg.mOriginalPackages.contains(oldName)
11785                        && mPackages.containsKey(oldName)) {
11786                    // This package is derived from an original package,
11787                    // and this device has been updating from that original
11788                    // name.  We must continue using the original name, so
11789                    // rename the new package here.
11790                    pkg.setPackageName(oldName);
11791                    pkgName = pkg.packageName;
11792                    replace = true;
11793                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
11794                            + oldName + " pkgName=" + pkgName);
11795                } else if (mPackages.containsKey(pkgName)) {
11796                    // This package, under its official name, already exists
11797                    // on the device; we should replace it.
11798                    replace = true;
11799                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
11800                }
11801
11802                // Prevent apps opting out from runtime permissions
11803                if (replace) {
11804                    PackageParser.Package oldPackage = mPackages.get(pkgName);
11805                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
11806                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
11807                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
11808                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
11809                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
11810                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
11811                                        + " doesn't support runtime permissions but the old"
11812                                        + " target SDK " + oldTargetSdk + " does.");
11813                        return;
11814                    }
11815                }
11816            }
11817
11818            PackageSetting ps = mSettings.mPackages.get(pkgName);
11819            if (ps != null) {
11820                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
11821
11822                // Quick sanity check that we're signed correctly if updating;
11823                // we'll check this again later when scanning, but we want to
11824                // bail early here before tripping over redefined permissions.
11825                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11826                    if (!checkUpgradeKeySetLP(ps, pkg)) {
11827                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
11828                                + pkg.packageName + " upgrade keys do not match the "
11829                                + "previously installed version");
11830                        return;
11831                    }
11832                } else {
11833                    try {
11834                        verifySignaturesLP(ps, pkg);
11835                    } catch (PackageManagerException e) {
11836                        res.setError(e.error, e.getMessage());
11837                        return;
11838                    }
11839                }
11840
11841                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
11842                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
11843                    systemApp = (ps.pkg.applicationInfo.flags &
11844                            ApplicationInfo.FLAG_SYSTEM) != 0;
11845                }
11846                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
11847            }
11848
11849            // Check whether the newly-scanned package wants to define an already-defined perm
11850            int N = pkg.permissions.size();
11851            for (int i = N-1; i >= 0; i--) {
11852                PackageParser.Permission perm = pkg.permissions.get(i);
11853                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
11854                if (bp != null) {
11855                    // If the defining package is signed with our cert, it's okay.  This
11856                    // also includes the "updating the same package" case, of course.
11857                    // "updating same package" could also involve key-rotation.
11858                    final boolean sigsOk;
11859                    if (bp.sourcePackage.equals(pkg.packageName)
11860                            && (bp.packageSetting instanceof PackageSetting)
11861                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
11862                                    scanFlags))) {
11863                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
11864                    } else {
11865                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
11866                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
11867                    }
11868                    if (!sigsOk) {
11869                        // If the owning package is the system itself, we log but allow
11870                        // install to proceed; we fail the install on all other permission
11871                        // redefinitions.
11872                        if (!bp.sourcePackage.equals("android")) {
11873                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
11874                                    + pkg.packageName + " attempting to redeclare permission "
11875                                    + perm.info.name + " already owned by " + bp.sourcePackage);
11876                            res.origPermission = perm.info.name;
11877                            res.origPackage = bp.sourcePackage;
11878                            return;
11879                        } else {
11880                            Slog.w(TAG, "Package " + pkg.packageName
11881                                    + " attempting to redeclare system permission "
11882                                    + perm.info.name + "; ignoring new declaration");
11883                            pkg.permissions.remove(i);
11884                        }
11885                    }
11886                }
11887            }
11888
11889        }
11890
11891        if (systemApp && onExternal) {
11892            // Disable updates to system apps on sdcard
11893            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
11894                    "Cannot install updates to system apps on sdcard");
11895            return;
11896        }
11897
11898        if (args.move != null) {
11899            // We did an in-place move, so dex is ready to roll
11900            scanFlags |= SCAN_NO_DEX;
11901            scanFlags |= SCAN_MOVE;
11902        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
11903            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
11904            scanFlags |= SCAN_NO_DEX;
11905
11906            try {
11907                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
11908                        true /* extract libs */);
11909            } catch (PackageManagerException pme) {
11910                Slog.e(TAG, "Error deriving application ABI", pme);
11911                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
11912                return;
11913            }
11914
11915            // Run dexopt before old package gets removed, to minimize time when app is unavailable
11916            int result = mPackageDexOptimizer
11917                    .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */,
11918                            false /* defer */, false /* inclDependencies */);
11919            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
11920                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
11921                return;
11922            }
11923        }
11924
11925        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
11926            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
11927            return;
11928        }
11929
11930        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
11931
11932        if (replace) {
11933            replacePackageLI(pkg, parseFlags, scanFlags, args.user,
11934                    installerPackageName, volumeUuid, res);
11935        } else {
11936            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
11937                    args.user, installerPackageName, volumeUuid, res);
11938        }
11939        synchronized (mPackages) {
11940            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11941            if (ps != null) {
11942                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
11943            }
11944        }
11945    }
11946
11947    private void startIntentFilterVerifications(int userId, boolean replacing,
11948            PackageParser.Package pkg) {
11949        if (mIntentFilterVerifierComponent == null) {
11950            Slog.w(TAG, "No IntentFilter verification will not be done as "
11951                    + "there is no IntentFilterVerifier available!");
11952            return;
11953        }
11954
11955        final int verifierUid = getPackageUid(
11956                mIntentFilterVerifierComponent.getPackageName(),
11957                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
11958
11959        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
11960        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
11961        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
11962        mHandler.sendMessage(msg);
11963    }
11964
11965    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
11966            PackageParser.Package pkg) {
11967        int size = pkg.activities.size();
11968        if (size == 0) {
11969            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
11970                    "No activity, so no need to verify any IntentFilter!");
11971            return;
11972        }
11973
11974        final boolean hasDomainURLs = hasDomainURLs(pkg);
11975        if (!hasDomainURLs) {
11976            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
11977                    "No domain URLs, so no need to verify any IntentFilter!");
11978            return;
11979        }
11980
11981        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
11982                + " if any IntentFilter from the " + size
11983                + " Activities needs verification ...");
11984
11985        int count = 0;
11986        final String packageName = pkg.packageName;
11987
11988        synchronized (mPackages) {
11989            // If this is a new install and we see that we've already run verification for this
11990            // package, we have nothing to do: it means the state was restored from backup.
11991            if (!replacing) {
11992                IntentFilterVerificationInfo ivi =
11993                        mSettings.getIntentFilterVerificationLPr(packageName);
11994                if (ivi != null) {
11995                    if (DEBUG_DOMAIN_VERIFICATION) {
11996                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
11997                                + ivi.getStatusString());
11998                    }
11999                    return;
12000                }
12001            }
12002
12003            // If any filters need to be verified, then all need to be.
12004            boolean needToVerify = false;
12005            for (PackageParser.Activity a : pkg.activities) {
12006                for (ActivityIntentInfo filter : a.intents) {
12007                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
12008                        if (DEBUG_DOMAIN_VERIFICATION) {
12009                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
12010                        }
12011                        needToVerify = true;
12012                        break;
12013                    }
12014                }
12015            }
12016
12017            if (needToVerify) {
12018                final int verificationId = mIntentFilterVerificationToken++;
12019                for (PackageParser.Activity a : pkg.activities) {
12020                    for (ActivityIntentInfo filter : a.intents) {
12021                        boolean needsFilterVerification = filter.hasWebDataURI();
12022                        if (needsFilterVerification && needsNetworkVerificationLPr(filter)) {
12023                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12024                                    "Verification needed for IntentFilter:" + filter.toString());
12025                            mIntentFilterVerifier.addOneIntentFilterVerification(
12026                                    verifierUid, userId, verificationId, filter, packageName);
12027                            count++;
12028                        }
12029                    }
12030                }
12031            }
12032        }
12033
12034        if (count > 0) {
12035            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
12036                    + " IntentFilter verification" + (count > 1 ? "s" : "")
12037                    +  " for userId:" + userId);
12038            mIntentFilterVerifier.startVerifications(userId);
12039        } else {
12040            if (DEBUG_DOMAIN_VERIFICATION) {
12041                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
12042            }
12043        }
12044    }
12045
12046    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
12047        final ComponentName cn  = filter.activity.getComponentName();
12048        final String packageName = cn.getPackageName();
12049
12050        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
12051                packageName);
12052        if (ivi == null) {
12053            return true;
12054        }
12055        int status = ivi.getStatus();
12056        switch (status) {
12057            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
12058            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
12059                return true;
12060
12061            default:
12062                // Nothing to do
12063                return false;
12064        }
12065    }
12066
12067    private static boolean isMultiArch(PackageSetting ps) {
12068        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12069    }
12070
12071    private static boolean isMultiArch(ApplicationInfo info) {
12072        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12073    }
12074
12075    private static boolean isExternal(PackageParser.Package pkg) {
12076        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12077    }
12078
12079    private static boolean isExternal(PackageSetting ps) {
12080        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12081    }
12082
12083    private static boolean isExternal(ApplicationInfo info) {
12084        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12085    }
12086
12087    private static boolean isSystemApp(PackageParser.Package pkg) {
12088        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
12089    }
12090
12091    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
12092        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
12093    }
12094
12095    private static boolean hasDomainURLs(PackageParser.Package pkg) {
12096        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
12097    }
12098
12099    private static boolean isSystemApp(PackageSetting ps) {
12100        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
12101    }
12102
12103    private static boolean isUpdatedSystemApp(PackageSetting ps) {
12104        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
12105    }
12106
12107    private int packageFlagsToInstallFlags(PackageSetting ps) {
12108        int installFlags = 0;
12109        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
12110            // This existing package was an external ASEC install when we have
12111            // the external flag without a UUID
12112            installFlags |= PackageManager.INSTALL_EXTERNAL;
12113        }
12114        if (ps.isForwardLocked()) {
12115            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12116        }
12117        return installFlags;
12118    }
12119
12120    private void deleteTempPackageFiles() {
12121        final FilenameFilter filter = new FilenameFilter() {
12122            public boolean accept(File dir, String name) {
12123                return name.startsWith("vmdl") && name.endsWith(".tmp");
12124            }
12125        };
12126        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
12127            file.delete();
12128        }
12129    }
12130
12131    @Override
12132    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
12133            int flags) {
12134        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
12135                flags);
12136    }
12137
12138    @Override
12139    public void deletePackage(final String packageName,
12140            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
12141        mContext.enforceCallingOrSelfPermission(
12142                android.Manifest.permission.DELETE_PACKAGES, null);
12143        final int uid = Binder.getCallingUid();
12144        if (UserHandle.getUserId(uid) != userId) {
12145            mContext.enforceCallingPermission(
12146                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
12147                    "deletePackage for user " + userId);
12148        }
12149        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
12150            try {
12151                observer.onPackageDeleted(packageName,
12152                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
12153            } catch (RemoteException re) {
12154            }
12155            return;
12156        }
12157
12158        boolean uninstallBlocked = false;
12159        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
12160            int[] users = sUserManager.getUserIds();
12161            for (int i = 0; i < users.length; ++i) {
12162                if (getBlockUninstallForUser(packageName, users[i])) {
12163                    uninstallBlocked = true;
12164                    break;
12165                }
12166            }
12167        } else {
12168            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
12169        }
12170        if (uninstallBlocked) {
12171            try {
12172                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
12173                        null);
12174            } catch (RemoteException re) {
12175            }
12176            return;
12177        }
12178
12179        if (DEBUG_REMOVE) {
12180            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
12181        }
12182        // Queue up an async operation since the package deletion may take a little while.
12183        mHandler.post(new Runnable() {
12184            public void run() {
12185                mHandler.removeCallbacks(this);
12186                final int returnCode = deletePackageX(packageName, userId, flags);
12187                if (observer != null) {
12188                    try {
12189                        observer.onPackageDeleted(packageName, returnCode, null);
12190                    } catch (RemoteException e) {
12191                        Log.i(TAG, "Observer no longer exists.");
12192                    } //end catch
12193                } //end if
12194            } //end run
12195        });
12196    }
12197
12198    private boolean isPackageDeviceAdmin(String packageName, int userId) {
12199        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12200                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12201        try {
12202            if (dpm != null) {
12203                if (dpm.isDeviceOwner(packageName)) {
12204                    return true;
12205                }
12206                int[] users;
12207                if (userId == UserHandle.USER_ALL) {
12208                    users = sUserManager.getUserIds();
12209                } else {
12210                    users = new int[]{userId};
12211                }
12212                for (int i = 0; i < users.length; ++i) {
12213                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
12214                        return true;
12215                    }
12216                }
12217            }
12218        } catch (RemoteException e) {
12219        }
12220        return false;
12221    }
12222
12223    /**
12224     *  This method is an internal method that could be get invoked either
12225     *  to delete an installed package or to clean up a failed installation.
12226     *  After deleting an installed package, a broadcast is sent to notify any
12227     *  listeners that the package has been installed. For cleaning up a failed
12228     *  installation, the broadcast is not necessary since the package's
12229     *  installation wouldn't have sent the initial broadcast either
12230     *  The key steps in deleting a package are
12231     *  deleting the package information in internal structures like mPackages,
12232     *  deleting the packages base directories through installd
12233     *  updating mSettings to reflect current status
12234     *  persisting settings for later use
12235     *  sending a broadcast if necessary
12236     */
12237    private int deletePackageX(String packageName, int userId, int flags) {
12238        final PackageRemovedInfo info = new PackageRemovedInfo();
12239        final boolean res;
12240
12241        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
12242                ? UserHandle.ALL : new UserHandle(userId);
12243
12244        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
12245            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
12246            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
12247        }
12248
12249        boolean removedForAllUsers = false;
12250        boolean systemUpdate = false;
12251
12252        // for the uninstall-updates case and restricted profiles, remember the per-
12253        // userhandle installed state
12254        int[] allUsers;
12255        boolean[] perUserInstalled;
12256        synchronized (mPackages) {
12257            PackageSetting ps = mSettings.mPackages.get(packageName);
12258            allUsers = sUserManager.getUserIds();
12259            perUserInstalled = new boolean[allUsers.length];
12260            for (int i = 0; i < allUsers.length; i++) {
12261                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12262            }
12263        }
12264
12265        synchronized (mInstallLock) {
12266            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
12267            res = deletePackageLI(packageName, removeForUser,
12268                    true, allUsers, perUserInstalled,
12269                    flags | REMOVE_CHATTY, info, true);
12270            systemUpdate = info.isRemovedPackageSystemUpdate;
12271            if (res && !systemUpdate && mPackages.get(packageName) == null) {
12272                removedForAllUsers = true;
12273            }
12274            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
12275                    + " removedForAllUsers=" + removedForAllUsers);
12276        }
12277
12278        if (res) {
12279            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
12280
12281            // If the removed package was a system update, the old system package
12282            // was re-enabled; we need to broadcast this information
12283            if (systemUpdate) {
12284                Bundle extras = new Bundle(1);
12285                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
12286                        ? info.removedAppId : info.uid);
12287                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12288
12289                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
12290                        extras, null, null, null);
12291                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
12292                        extras, null, null, null);
12293                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
12294                        null, packageName, null, null);
12295            }
12296        }
12297        // Force a gc here.
12298        Runtime.getRuntime().gc();
12299        // Delete the resources here after sending the broadcast to let
12300        // other processes clean up before deleting resources.
12301        if (info.args != null) {
12302            synchronized (mInstallLock) {
12303                info.args.doPostDeleteLI(true);
12304            }
12305        }
12306
12307        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
12308    }
12309
12310    class PackageRemovedInfo {
12311        String removedPackage;
12312        int uid = -1;
12313        int removedAppId = -1;
12314        int[] removedUsers = null;
12315        boolean isRemovedPackageSystemUpdate = false;
12316        // Clean up resources deleted packages.
12317        InstallArgs args = null;
12318
12319        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
12320            Bundle extras = new Bundle(1);
12321            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
12322            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
12323            if (replacing) {
12324                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12325            }
12326            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
12327            if (removedPackage != null) {
12328                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
12329                        extras, null, null, removedUsers);
12330                if (fullRemove && !replacing) {
12331                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
12332                            extras, null, null, removedUsers);
12333                }
12334            }
12335            if (removedAppId >= 0) {
12336                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
12337                        removedUsers);
12338            }
12339        }
12340    }
12341
12342    /*
12343     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
12344     * flag is not set, the data directory is removed as well.
12345     * make sure this flag is set for partially installed apps. If not its meaningless to
12346     * delete a partially installed application.
12347     */
12348    private void removePackageDataLI(PackageSetting ps,
12349            int[] allUserHandles, boolean[] perUserInstalled,
12350            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
12351        String packageName = ps.name;
12352        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
12353        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
12354        // Retrieve object to delete permissions for shared user later on
12355        final PackageSetting deletedPs;
12356        // reader
12357        synchronized (mPackages) {
12358            deletedPs = mSettings.mPackages.get(packageName);
12359            if (outInfo != null) {
12360                outInfo.removedPackage = packageName;
12361                outInfo.removedUsers = deletedPs != null
12362                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
12363                        : null;
12364            }
12365        }
12366        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12367            removeDataDirsLI(ps.volumeUuid, packageName);
12368            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
12369        }
12370        // writer
12371        synchronized (mPackages) {
12372            if (deletedPs != null) {
12373                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12374                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
12375                    clearDefaultBrowserIfNeeded(packageName);
12376                    if (outInfo != null) {
12377                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
12378                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
12379                    }
12380                    updatePermissionsLPw(deletedPs.name, null, 0);
12381                    if (deletedPs.sharedUser != null) {
12382                        // Remove permissions associated with package. Since runtime
12383                        // permissions are per user we have to kill the removed package
12384                        // or packages running under the shared user of the removed
12385                        // package if revoking the permissions requested only by the removed
12386                        // package is successful and this causes a change in gids.
12387                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12388                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
12389                                    userId);
12390                            if (userIdToKill == UserHandle.USER_ALL
12391                                    || userIdToKill >= UserHandle.USER_OWNER) {
12392                                // If gids changed for this user, kill all affected packages.
12393                                mHandler.post(new Runnable() {
12394                                    @Override
12395                                    public void run() {
12396                                        // This has to happen with no lock held.
12397                                        killSettingPackagesForUser(deletedPs, userIdToKill,
12398                                                KILL_APP_REASON_GIDS_CHANGED);
12399                                    }
12400                                });
12401                            break;
12402                            }
12403                        }
12404                    }
12405                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
12406                }
12407                // make sure to preserve per-user disabled state if this removal was just
12408                // a downgrade of a system app to the factory package
12409                if (allUserHandles != null && perUserInstalled != null) {
12410                    if (DEBUG_REMOVE) {
12411                        Slog.d(TAG, "Propagating install state across downgrade");
12412                    }
12413                    for (int i = 0; i < allUserHandles.length; i++) {
12414                        if (DEBUG_REMOVE) {
12415                            Slog.d(TAG, "    user " + allUserHandles[i]
12416                                    + " => " + perUserInstalled[i]);
12417                        }
12418                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12419                    }
12420                }
12421            }
12422            // can downgrade to reader
12423            if (writeSettings) {
12424                // Save settings now
12425                mSettings.writeLPr();
12426            }
12427        }
12428        if (outInfo != null) {
12429            // A user ID was deleted here. Go through all users and remove it
12430            // from KeyStore.
12431            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
12432        }
12433    }
12434
12435    static boolean locationIsPrivileged(File path) {
12436        try {
12437            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
12438                    .getCanonicalPath();
12439            return path.getCanonicalPath().startsWith(privilegedAppDir);
12440        } catch (IOException e) {
12441            Slog.e(TAG, "Unable to access code path " + path);
12442        }
12443        return false;
12444    }
12445
12446    /*
12447     * Tries to delete system package.
12448     */
12449    private boolean deleteSystemPackageLI(PackageSetting newPs,
12450            int[] allUserHandles, boolean[] perUserInstalled,
12451            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
12452        final boolean applyUserRestrictions
12453                = (allUserHandles != null) && (perUserInstalled != null);
12454        PackageSetting disabledPs = null;
12455        // Confirm if the system package has been updated
12456        // An updated system app can be deleted. This will also have to restore
12457        // the system pkg from system partition
12458        // reader
12459        synchronized (mPackages) {
12460            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
12461        }
12462        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
12463                + " disabledPs=" + disabledPs);
12464        if (disabledPs == null) {
12465            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
12466            return false;
12467        } else if (DEBUG_REMOVE) {
12468            Slog.d(TAG, "Deleting system pkg from data partition");
12469        }
12470        if (DEBUG_REMOVE) {
12471            if (applyUserRestrictions) {
12472                Slog.d(TAG, "Remembering install states:");
12473                for (int i = 0; i < allUserHandles.length; i++) {
12474                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
12475                }
12476            }
12477        }
12478        // Delete the updated package
12479        outInfo.isRemovedPackageSystemUpdate = true;
12480        if (disabledPs.versionCode < newPs.versionCode) {
12481            // Delete data for downgrades
12482            flags &= ~PackageManager.DELETE_KEEP_DATA;
12483        } else {
12484            // Preserve data by setting flag
12485            flags |= PackageManager.DELETE_KEEP_DATA;
12486        }
12487        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
12488                allUserHandles, perUserInstalled, outInfo, writeSettings);
12489        if (!ret) {
12490            return false;
12491        }
12492        // writer
12493        synchronized (mPackages) {
12494            // Reinstate the old system package
12495            mSettings.enableSystemPackageLPw(newPs.name);
12496            // Remove any native libraries from the upgraded package.
12497            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
12498        }
12499        // Install the system package
12500        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
12501        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
12502        if (locationIsPrivileged(disabledPs.codePath)) {
12503            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12504        }
12505
12506        final PackageParser.Package newPkg;
12507        try {
12508            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
12509        } catch (PackageManagerException e) {
12510            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
12511            return false;
12512        }
12513
12514        // writer
12515        synchronized (mPackages) {
12516            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
12517            updatePermissionsLPw(newPkg.packageName, newPkg,
12518                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
12519            if (applyUserRestrictions) {
12520                if (DEBUG_REMOVE) {
12521                    Slog.d(TAG, "Propagating install state across reinstall");
12522                }
12523                for (int i = 0; i < allUserHandles.length; i++) {
12524                    if (DEBUG_REMOVE) {
12525                        Slog.d(TAG, "    user " + allUserHandles[i]
12526                                + " => " + perUserInstalled[i]);
12527                    }
12528                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12529                }
12530                // Regardless of writeSettings we need to ensure that this restriction
12531                // state propagation is persisted
12532                mSettings.writeAllUsersPackageRestrictionsLPr();
12533            }
12534            // can downgrade to reader here
12535            if (writeSettings) {
12536                mSettings.writeLPr();
12537            }
12538        }
12539        return true;
12540    }
12541
12542    private boolean deleteInstalledPackageLI(PackageSetting ps,
12543            boolean deleteCodeAndResources, int flags,
12544            int[] allUserHandles, boolean[] perUserInstalled,
12545            PackageRemovedInfo outInfo, boolean writeSettings) {
12546        if (outInfo != null) {
12547            outInfo.uid = ps.appId;
12548        }
12549
12550        // Delete package data from internal structures and also remove data if flag is set
12551        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
12552
12553        // Delete application code and resources
12554        if (deleteCodeAndResources && (outInfo != null)) {
12555            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
12556                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
12557            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
12558        }
12559        return true;
12560    }
12561
12562    @Override
12563    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
12564            int userId) {
12565        mContext.enforceCallingOrSelfPermission(
12566                android.Manifest.permission.DELETE_PACKAGES, null);
12567        synchronized (mPackages) {
12568            PackageSetting ps = mSettings.mPackages.get(packageName);
12569            if (ps == null) {
12570                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
12571                return false;
12572            }
12573            if (!ps.getInstalled(userId)) {
12574                // Can't block uninstall for an app that is not installed or enabled.
12575                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
12576                return false;
12577            }
12578            ps.setBlockUninstall(blockUninstall, userId);
12579            mSettings.writePackageRestrictionsLPr(userId);
12580        }
12581        return true;
12582    }
12583
12584    @Override
12585    public boolean getBlockUninstallForUser(String packageName, int userId) {
12586        synchronized (mPackages) {
12587            PackageSetting ps = mSettings.mPackages.get(packageName);
12588            if (ps == null) {
12589                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
12590                return false;
12591            }
12592            return ps.getBlockUninstall(userId);
12593        }
12594    }
12595
12596    /*
12597     * This method handles package deletion in general
12598     */
12599    private boolean deletePackageLI(String packageName, UserHandle user,
12600            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
12601            int flags, PackageRemovedInfo outInfo,
12602            boolean writeSettings) {
12603        if (packageName == null) {
12604            Slog.w(TAG, "Attempt to delete null packageName.");
12605            return false;
12606        }
12607        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
12608        PackageSetting ps;
12609        boolean dataOnly = false;
12610        int removeUser = -1;
12611        int appId = -1;
12612        synchronized (mPackages) {
12613            ps = mSettings.mPackages.get(packageName);
12614            if (ps == null) {
12615                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12616                return false;
12617            }
12618            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
12619                    && user.getIdentifier() != UserHandle.USER_ALL) {
12620                // The caller is asking that the package only be deleted for a single
12621                // user.  To do this, we just mark its uninstalled state and delete
12622                // its data.  If this is a system app, we only allow this to happen if
12623                // they have set the special DELETE_SYSTEM_APP which requests different
12624                // semantics than normal for uninstalling system apps.
12625                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
12626                ps.setUserState(user.getIdentifier(),
12627                        COMPONENT_ENABLED_STATE_DEFAULT,
12628                        false, //installed
12629                        true,  //stopped
12630                        true,  //notLaunched
12631                        false, //hidden
12632                        null, null, null,
12633                        false, // blockUninstall
12634                        INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
12635                if (!isSystemApp(ps)) {
12636                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
12637                        // Other user still have this package installed, so all
12638                        // we need to do is clear this user's data and save that
12639                        // it is uninstalled.
12640                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
12641                        removeUser = user.getIdentifier();
12642                        appId = ps.appId;
12643                        scheduleWritePackageRestrictionsLocked(removeUser);
12644                    } else {
12645                        // We need to set it back to 'installed' so the uninstall
12646                        // broadcasts will be sent correctly.
12647                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
12648                        ps.setInstalled(true, user.getIdentifier());
12649                    }
12650                } else {
12651                    // This is a system app, so we assume that the
12652                    // other users still have this package installed, so all
12653                    // we need to do is clear this user's data and save that
12654                    // it is uninstalled.
12655                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
12656                    removeUser = user.getIdentifier();
12657                    appId = ps.appId;
12658                    scheduleWritePackageRestrictionsLocked(removeUser);
12659                }
12660            }
12661        }
12662
12663        if (removeUser >= 0) {
12664            // From above, we determined that we are deleting this only
12665            // for a single user.  Continue the work here.
12666            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
12667            if (outInfo != null) {
12668                outInfo.removedPackage = packageName;
12669                outInfo.removedAppId = appId;
12670                outInfo.removedUsers = new int[] {removeUser};
12671            }
12672            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
12673            removeKeystoreDataIfNeeded(removeUser, appId);
12674            schedulePackageCleaning(packageName, removeUser, false);
12675            synchronized (mPackages) {
12676                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
12677                    scheduleWritePackageRestrictionsLocked(removeUser);
12678                }
12679                revokeRuntimePermissionsAndClearAllFlagsLocked(ps.getPermissionsState(),
12680                        removeUser);
12681            }
12682            return true;
12683        }
12684
12685        if (dataOnly) {
12686            // Delete application data first
12687            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
12688            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
12689            return true;
12690        }
12691
12692        boolean ret = false;
12693        if (isSystemApp(ps)) {
12694            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
12695            // When an updated system application is deleted we delete the existing resources as well and
12696            // fall back to existing code in system partition
12697            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
12698                    flags, outInfo, writeSettings);
12699        } else {
12700            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
12701            // Kill application pre-emptively especially for apps on sd.
12702            killApplication(packageName, ps.appId, "uninstall pkg");
12703            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
12704                    allUserHandles, perUserInstalled,
12705                    outInfo, writeSettings);
12706        }
12707
12708        return ret;
12709    }
12710
12711    private final class ClearStorageConnection implements ServiceConnection {
12712        IMediaContainerService mContainerService;
12713
12714        @Override
12715        public void onServiceConnected(ComponentName name, IBinder service) {
12716            synchronized (this) {
12717                mContainerService = IMediaContainerService.Stub.asInterface(service);
12718                notifyAll();
12719            }
12720        }
12721
12722        @Override
12723        public void onServiceDisconnected(ComponentName name) {
12724        }
12725    }
12726
12727    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
12728        final boolean mounted;
12729        if (Environment.isExternalStorageEmulated()) {
12730            mounted = true;
12731        } else {
12732            final String status = Environment.getExternalStorageState();
12733
12734            mounted = status.equals(Environment.MEDIA_MOUNTED)
12735                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
12736        }
12737
12738        if (!mounted) {
12739            return;
12740        }
12741
12742        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
12743        int[] users;
12744        if (userId == UserHandle.USER_ALL) {
12745            users = sUserManager.getUserIds();
12746        } else {
12747            users = new int[] { userId };
12748        }
12749        final ClearStorageConnection conn = new ClearStorageConnection();
12750        if (mContext.bindServiceAsUser(
12751                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
12752            try {
12753                for (int curUser : users) {
12754                    long timeout = SystemClock.uptimeMillis() + 5000;
12755                    synchronized (conn) {
12756                        long now = SystemClock.uptimeMillis();
12757                        while (conn.mContainerService == null && now < timeout) {
12758                            try {
12759                                conn.wait(timeout - now);
12760                            } catch (InterruptedException e) {
12761                            }
12762                        }
12763                    }
12764                    if (conn.mContainerService == null) {
12765                        return;
12766                    }
12767
12768                    final UserEnvironment userEnv = new UserEnvironment(curUser);
12769                    clearDirectory(conn.mContainerService,
12770                            userEnv.buildExternalStorageAppCacheDirs(packageName));
12771                    if (allData) {
12772                        clearDirectory(conn.mContainerService,
12773                                userEnv.buildExternalStorageAppDataDirs(packageName));
12774                        clearDirectory(conn.mContainerService,
12775                                userEnv.buildExternalStorageAppMediaDirs(packageName));
12776                    }
12777                }
12778            } finally {
12779                mContext.unbindService(conn);
12780            }
12781        }
12782    }
12783
12784    @Override
12785    public void clearApplicationUserData(final String packageName,
12786            final IPackageDataObserver observer, final int userId) {
12787        mContext.enforceCallingOrSelfPermission(
12788                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
12789        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
12790        // Queue up an async operation since the package deletion may take a little while.
12791        mHandler.post(new Runnable() {
12792            public void run() {
12793                mHandler.removeCallbacks(this);
12794                final boolean succeeded;
12795                synchronized (mInstallLock) {
12796                    succeeded = clearApplicationUserDataLI(packageName, userId);
12797                }
12798                clearExternalStorageDataSync(packageName, userId, true);
12799                if (succeeded) {
12800                    // invoke DeviceStorageMonitor's update method to clear any notifications
12801                    DeviceStorageMonitorInternal
12802                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
12803                    if (dsm != null) {
12804                        dsm.checkMemory();
12805                    }
12806                }
12807                if(observer != null) {
12808                    try {
12809                        observer.onRemoveCompleted(packageName, succeeded);
12810                    } catch (RemoteException e) {
12811                        Log.i(TAG, "Observer no longer exists.");
12812                    }
12813                } //end if observer
12814            } //end run
12815        });
12816    }
12817
12818    private boolean clearApplicationUserDataLI(String packageName, int userId) {
12819        if (packageName == null) {
12820            Slog.w(TAG, "Attempt to delete null packageName.");
12821            return false;
12822        }
12823
12824        // Try finding details about the requested package
12825        PackageParser.Package pkg;
12826        synchronized (mPackages) {
12827            pkg = mPackages.get(packageName);
12828            if (pkg == null) {
12829                final PackageSetting ps = mSettings.mPackages.get(packageName);
12830                if (ps != null) {
12831                    pkg = ps.pkg;
12832                }
12833            }
12834
12835            if (pkg == null) {
12836                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12837                return false;
12838            }
12839
12840            PackageSetting ps = (PackageSetting) pkg.mExtras;
12841            PermissionsState permissionsState = ps.getPermissionsState();
12842            revokeRuntimePermissionsAndClearUserSetFlagsLocked(permissionsState, userId);
12843        }
12844
12845        // Always delete data directories for package, even if we found no other
12846        // record of app. This helps users recover from UID mismatches without
12847        // resorting to a full data wipe.
12848        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
12849        if (retCode < 0) {
12850            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
12851            return false;
12852        }
12853
12854        final int appId = pkg.applicationInfo.uid;
12855        removeKeystoreDataIfNeeded(userId, appId);
12856
12857        // Create a native library symlink only if we have native libraries
12858        // and if the native libraries are 32 bit libraries. We do not provide
12859        // this symlink for 64 bit libraries.
12860        if (pkg.applicationInfo.primaryCpuAbi != null &&
12861                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
12862            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
12863            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
12864                    nativeLibPath, userId) < 0) {
12865                Slog.w(TAG, "Failed linking native library dir");
12866                return false;
12867            }
12868        }
12869
12870        return true;
12871    }
12872
12873
12874    /**
12875     * Revokes granted runtime permissions and clears resettable flags
12876     * which are flags that can be set by a user interaction.
12877     *
12878     * @param permissionsState The permission state to reset.
12879     * @param userId The device user for which to do a reset.
12880     */
12881    private void revokeRuntimePermissionsAndClearUserSetFlagsLocked(
12882            PermissionsState permissionsState, int userId) {
12883        final int userSetFlags = PackageManager.FLAG_PERMISSION_USER_SET
12884                | PackageManager.FLAG_PERMISSION_USER_FIXED
12885                | PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
12886
12887        revokeRuntimePermissionsAndClearFlagsLocked(permissionsState, userId, userSetFlags);
12888    }
12889
12890    /**
12891     * Revokes granted runtime permissions and clears all flags.
12892     *
12893     * @param permissionsState The permission state to reset.
12894     * @param userId The device user for which to do a reset.
12895     */
12896    private void revokeRuntimePermissionsAndClearAllFlagsLocked(
12897            PermissionsState permissionsState, int userId) {
12898        revokeRuntimePermissionsAndClearFlagsLocked(permissionsState, userId,
12899                PackageManager.MASK_PERMISSION_FLAGS);
12900    }
12901
12902    /**
12903     * Revokes granted runtime permissions and clears certain flags.
12904     *
12905     * @param permissionsState The permission state to reset.
12906     * @param userId The device user for which to do a reset.
12907     * @param flags The flags that is going to be reset.
12908     */
12909    private void revokeRuntimePermissionsAndClearFlagsLocked(
12910            PermissionsState permissionsState, int userId, int flags) {
12911        boolean needsWrite = false;
12912
12913        for (PermissionState state : permissionsState.getRuntimePermissionStates(userId)) {
12914            BasePermission bp = mSettings.mPermissions.get(state.getName());
12915            if (bp != null) {
12916                permissionsState.revokeRuntimePermission(bp, userId);
12917                permissionsState.updatePermissionFlags(bp, userId, flags, 0);
12918                needsWrite = true;
12919            }
12920        }
12921
12922        // Ensure default permissions are never cleared.
12923        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
12924
12925        if (needsWrite) {
12926            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
12927        }
12928    }
12929
12930    /**
12931     * Remove entries from the keystore daemon. Will only remove it if the
12932     * {@code appId} is valid.
12933     */
12934    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
12935        if (appId < 0) {
12936            return;
12937        }
12938
12939        final KeyStore keyStore = KeyStore.getInstance();
12940        if (keyStore != null) {
12941            if (userId == UserHandle.USER_ALL) {
12942                for (final int individual : sUserManager.getUserIds()) {
12943                    keyStore.clearUid(UserHandle.getUid(individual, appId));
12944                }
12945            } else {
12946                keyStore.clearUid(UserHandle.getUid(userId, appId));
12947            }
12948        } else {
12949            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
12950        }
12951    }
12952
12953    @Override
12954    public void deleteApplicationCacheFiles(final String packageName,
12955            final IPackageDataObserver observer) {
12956        mContext.enforceCallingOrSelfPermission(
12957                android.Manifest.permission.DELETE_CACHE_FILES, null);
12958        // Queue up an async operation since the package deletion may take a little while.
12959        final int userId = UserHandle.getCallingUserId();
12960        mHandler.post(new Runnable() {
12961            public void run() {
12962                mHandler.removeCallbacks(this);
12963                final boolean succeded;
12964                synchronized (mInstallLock) {
12965                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
12966                }
12967                clearExternalStorageDataSync(packageName, userId, false);
12968                if (observer != null) {
12969                    try {
12970                        observer.onRemoveCompleted(packageName, succeded);
12971                    } catch (RemoteException e) {
12972                        Log.i(TAG, "Observer no longer exists.");
12973                    }
12974                } //end if observer
12975            } //end run
12976        });
12977    }
12978
12979    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
12980        if (packageName == null) {
12981            Slog.w(TAG, "Attempt to delete null packageName.");
12982            return false;
12983        }
12984        PackageParser.Package p;
12985        synchronized (mPackages) {
12986            p = mPackages.get(packageName);
12987        }
12988        if (p == null) {
12989            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
12990            return false;
12991        }
12992        final ApplicationInfo applicationInfo = p.applicationInfo;
12993        if (applicationInfo == null) {
12994            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
12995            return false;
12996        }
12997        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
12998        if (retCode < 0) {
12999            Slog.w(TAG, "Couldn't remove cache files for package: "
13000                       + packageName + " u" + userId);
13001            return false;
13002        }
13003        return true;
13004    }
13005
13006    @Override
13007    public void getPackageSizeInfo(final String packageName, int userHandle,
13008            final IPackageStatsObserver observer) {
13009        mContext.enforceCallingOrSelfPermission(
13010                android.Manifest.permission.GET_PACKAGE_SIZE, null);
13011        if (packageName == null) {
13012            throw new IllegalArgumentException("Attempt to get size of null packageName");
13013        }
13014
13015        PackageStats stats = new PackageStats(packageName, userHandle);
13016
13017        /*
13018         * Queue up an async operation since the package measurement may take a
13019         * little while.
13020         */
13021        Message msg = mHandler.obtainMessage(INIT_COPY);
13022        msg.obj = new MeasureParams(stats, observer);
13023        mHandler.sendMessage(msg);
13024    }
13025
13026    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
13027            PackageStats pStats) {
13028        if (packageName == null) {
13029            Slog.w(TAG, "Attempt to get size of null packageName.");
13030            return false;
13031        }
13032        PackageParser.Package p;
13033        boolean dataOnly = false;
13034        String libDirRoot = null;
13035        String asecPath = null;
13036        PackageSetting ps = null;
13037        synchronized (mPackages) {
13038            p = mPackages.get(packageName);
13039            ps = mSettings.mPackages.get(packageName);
13040            if(p == null) {
13041                dataOnly = true;
13042                if((ps == null) || (ps.pkg == null)) {
13043                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13044                    return false;
13045                }
13046                p = ps.pkg;
13047            }
13048            if (ps != null) {
13049                libDirRoot = ps.legacyNativeLibraryPathString;
13050            }
13051            if (p != null && (isExternal(p) || p.isForwardLocked())) {
13052                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
13053                if (secureContainerId != null) {
13054                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
13055                }
13056            }
13057        }
13058        String publicSrcDir = null;
13059        if(!dataOnly) {
13060            final ApplicationInfo applicationInfo = p.applicationInfo;
13061            if (applicationInfo == null) {
13062                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13063                return false;
13064            }
13065            if (p.isForwardLocked()) {
13066                publicSrcDir = applicationInfo.getBaseResourcePath();
13067            }
13068        }
13069        // TODO: extend to measure size of split APKs
13070        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
13071        // not just the first level.
13072        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
13073        // just the primary.
13074        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
13075        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath,
13076                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
13077        if (res < 0) {
13078            return false;
13079        }
13080
13081        // Fix-up for forward-locked applications in ASEC containers.
13082        if (!isExternal(p)) {
13083            pStats.codeSize += pStats.externalCodeSize;
13084            pStats.externalCodeSize = 0L;
13085        }
13086
13087        return true;
13088    }
13089
13090
13091    @Override
13092    public void addPackageToPreferred(String packageName) {
13093        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
13094    }
13095
13096    @Override
13097    public void removePackageFromPreferred(String packageName) {
13098        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
13099    }
13100
13101    @Override
13102    public List<PackageInfo> getPreferredPackages(int flags) {
13103        return new ArrayList<PackageInfo>();
13104    }
13105
13106    private int getUidTargetSdkVersionLockedLPr(int uid) {
13107        Object obj = mSettings.getUserIdLPr(uid);
13108        if (obj instanceof SharedUserSetting) {
13109            final SharedUserSetting sus = (SharedUserSetting) obj;
13110            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
13111            final Iterator<PackageSetting> it = sus.packages.iterator();
13112            while (it.hasNext()) {
13113                final PackageSetting ps = it.next();
13114                if (ps.pkg != null) {
13115                    int v = ps.pkg.applicationInfo.targetSdkVersion;
13116                    if (v < vers) vers = v;
13117                }
13118            }
13119            return vers;
13120        } else if (obj instanceof PackageSetting) {
13121            final PackageSetting ps = (PackageSetting) obj;
13122            if (ps.pkg != null) {
13123                return ps.pkg.applicationInfo.targetSdkVersion;
13124            }
13125        }
13126        return Build.VERSION_CODES.CUR_DEVELOPMENT;
13127    }
13128
13129    @Override
13130    public void addPreferredActivity(IntentFilter filter, int match,
13131            ComponentName[] set, ComponentName activity, int userId) {
13132        addPreferredActivityInternal(filter, match, set, activity, true, userId,
13133                "Adding preferred");
13134    }
13135
13136    private void addPreferredActivityInternal(IntentFilter filter, int match,
13137            ComponentName[] set, ComponentName activity, boolean always, int userId,
13138            String opname) {
13139        // writer
13140        int callingUid = Binder.getCallingUid();
13141        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
13142        if (filter.countActions() == 0) {
13143            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13144            return;
13145        }
13146        synchronized (mPackages) {
13147            if (mContext.checkCallingOrSelfPermission(
13148                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13149                    != PackageManager.PERMISSION_GRANTED) {
13150                if (getUidTargetSdkVersionLockedLPr(callingUid)
13151                        < Build.VERSION_CODES.FROYO) {
13152                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
13153                            + callingUid);
13154                    return;
13155                }
13156                mContext.enforceCallingOrSelfPermission(
13157                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13158            }
13159
13160            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
13161            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
13162                    + userId + ":");
13163            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13164            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
13165            scheduleWritePackageRestrictionsLocked(userId);
13166        }
13167    }
13168
13169    @Override
13170    public void replacePreferredActivity(IntentFilter filter, int match,
13171            ComponentName[] set, ComponentName activity, int userId) {
13172        if (filter.countActions() != 1) {
13173            throw new IllegalArgumentException(
13174                    "replacePreferredActivity expects filter to have only 1 action.");
13175        }
13176        if (filter.countDataAuthorities() != 0
13177                || filter.countDataPaths() != 0
13178                || filter.countDataSchemes() > 1
13179                || filter.countDataTypes() != 0) {
13180            throw new IllegalArgumentException(
13181                    "replacePreferredActivity expects filter to have no data authorities, " +
13182                    "paths, or types; and at most one scheme.");
13183        }
13184
13185        final int callingUid = Binder.getCallingUid();
13186        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
13187        synchronized (mPackages) {
13188            if (mContext.checkCallingOrSelfPermission(
13189                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13190                    != PackageManager.PERMISSION_GRANTED) {
13191                if (getUidTargetSdkVersionLockedLPr(callingUid)
13192                        < Build.VERSION_CODES.FROYO) {
13193                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
13194                            + Binder.getCallingUid());
13195                    return;
13196                }
13197                mContext.enforceCallingOrSelfPermission(
13198                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13199            }
13200
13201            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13202            if (pir != null) {
13203                // Get all of the existing entries that exactly match this filter.
13204                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
13205                if (existing != null && existing.size() == 1) {
13206                    PreferredActivity cur = existing.get(0);
13207                    if (DEBUG_PREFERRED) {
13208                        Slog.i(TAG, "Checking replace of preferred:");
13209                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13210                        if (!cur.mPref.mAlways) {
13211                            Slog.i(TAG, "  -- CUR; not mAlways!");
13212                        } else {
13213                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
13214                            Slog.i(TAG, "  -- CUR: mSet="
13215                                    + Arrays.toString(cur.mPref.mSetComponents));
13216                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
13217                            Slog.i(TAG, "  -- NEW: mMatch="
13218                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
13219                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
13220                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
13221                        }
13222                    }
13223                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
13224                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
13225                            && cur.mPref.sameSet(set)) {
13226                        // Setting the preferred activity to what it happens to be already
13227                        if (DEBUG_PREFERRED) {
13228                            Slog.i(TAG, "Replacing with same preferred activity "
13229                                    + cur.mPref.mShortComponent + " for user "
13230                                    + userId + ":");
13231                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13232                        }
13233                        return;
13234                    }
13235                }
13236
13237                if (existing != null) {
13238                    if (DEBUG_PREFERRED) {
13239                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
13240                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13241                    }
13242                    for (int i = 0; i < existing.size(); i++) {
13243                        PreferredActivity pa = existing.get(i);
13244                        if (DEBUG_PREFERRED) {
13245                            Slog.i(TAG, "Removing existing preferred activity "
13246                                    + pa.mPref.mComponent + ":");
13247                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
13248                        }
13249                        pir.removeFilter(pa);
13250                    }
13251                }
13252            }
13253            addPreferredActivityInternal(filter, match, set, activity, true, userId,
13254                    "Replacing preferred");
13255        }
13256    }
13257
13258    @Override
13259    public void clearPackagePreferredActivities(String packageName) {
13260        final int uid = Binder.getCallingUid();
13261        // writer
13262        synchronized (mPackages) {
13263            PackageParser.Package pkg = mPackages.get(packageName);
13264            if (pkg == null || pkg.applicationInfo.uid != uid) {
13265                if (mContext.checkCallingOrSelfPermission(
13266                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13267                        != PackageManager.PERMISSION_GRANTED) {
13268                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
13269                            < Build.VERSION_CODES.FROYO) {
13270                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
13271                                + Binder.getCallingUid());
13272                        return;
13273                    }
13274                    mContext.enforceCallingOrSelfPermission(
13275                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13276                }
13277            }
13278
13279            int user = UserHandle.getCallingUserId();
13280            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
13281                scheduleWritePackageRestrictionsLocked(user);
13282            }
13283        }
13284    }
13285
13286    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13287    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
13288        ArrayList<PreferredActivity> removed = null;
13289        boolean changed = false;
13290        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13291            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
13292            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13293            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
13294                continue;
13295            }
13296            Iterator<PreferredActivity> it = pir.filterIterator();
13297            while (it.hasNext()) {
13298                PreferredActivity pa = it.next();
13299                // Mark entry for removal only if it matches the package name
13300                // and the entry is of type "always".
13301                if (packageName == null ||
13302                        (pa.mPref.mComponent.getPackageName().equals(packageName)
13303                                && pa.mPref.mAlways)) {
13304                    if (removed == null) {
13305                        removed = new ArrayList<PreferredActivity>();
13306                    }
13307                    removed.add(pa);
13308                }
13309            }
13310            if (removed != null) {
13311                for (int j=0; j<removed.size(); j++) {
13312                    PreferredActivity pa = removed.get(j);
13313                    pir.removeFilter(pa);
13314                }
13315                changed = true;
13316            }
13317        }
13318        return changed;
13319    }
13320
13321    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13322    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
13323        if (userId == UserHandle.USER_ALL) {
13324            if (mSettings.removeIntentFilterVerificationLPw(packageName,
13325                    sUserManager.getUserIds())) {
13326                for (int oneUserId : sUserManager.getUserIds()) {
13327                    scheduleWritePackageRestrictionsLocked(oneUserId);
13328                }
13329            }
13330        } else {
13331            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
13332                scheduleWritePackageRestrictionsLocked(userId);
13333            }
13334        }
13335    }
13336
13337
13338    void clearDefaultBrowserIfNeeded(String packageName) {
13339        for (int oneUserId : sUserManager.getUserIds()) {
13340            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
13341            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
13342            if (packageName.equals(defaultBrowserPackageName)) {
13343                setDefaultBrowserPackageName(null, oneUserId);
13344            }
13345        }
13346    }
13347
13348    @Override
13349    public void resetPreferredActivities(int userId) {
13350        /* TODO: Actually use userId. Why is it being passed in? */
13351        mContext.enforceCallingOrSelfPermission(
13352                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13353        // writer
13354        synchronized (mPackages) {
13355            int user = UserHandle.getCallingUserId();
13356            clearPackagePreferredActivitiesLPw(null, user);
13357            mSettings.readDefaultPreferredAppsLPw(this, user);
13358            scheduleWritePackageRestrictionsLocked(user);
13359        }
13360    }
13361
13362    @Override
13363    public int getPreferredActivities(List<IntentFilter> outFilters,
13364            List<ComponentName> outActivities, String packageName) {
13365
13366        int num = 0;
13367        final int userId = UserHandle.getCallingUserId();
13368        // reader
13369        synchronized (mPackages) {
13370            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13371            if (pir != null) {
13372                final Iterator<PreferredActivity> it = pir.filterIterator();
13373                while (it.hasNext()) {
13374                    final PreferredActivity pa = it.next();
13375                    if (packageName == null
13376                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
13377                                    && pa.mPref.mAlways)) {
13378                        if (outFilters != null) {
13379                            outFilters.add(new IntentFilter(pa));
13380                        }
13381                        if (outActivities != null) {
13382                            outActivities.add(pa.mPref.mComponent);
13383                        }
13384                    }
13385                }
13386            }
13387        }
13388
13389        return num;
13390    }
13391
13392    @Override
13393    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
13394            int userId) {
13395        int callingUid = Binder.getCallingUid();
13396        if (callingUid != Process.SYSTEM_UID) {
13397            throw new SecurityException(
13398                    "addPersistentPreferredActivity can only be run by the system");
13399        }
13400        if (filter.countActions() == 0) {
13401            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13402            return;
13403        }
13404        synchronized (mPackages) {
13405            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
13406                    " :");
13407            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13408            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
13409                    new PersistentPreferredActivity(filter, activity));
13410            scheduleWritePackageRestrictionsLocked(userId);
13411        }
13412    }
13413
13414    @Override
13415    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
13416        int callingUid = Binder.getCallingUid();
13417        if (callingUid != Process.SYSTEM_UID) {
13418            throw new SecurityException(
13419                    "clearPackagePersistentPreferredActivities can only be run by the system");
13420        }
13421        ArrayList<PersistentPreferredActivity> removed = null;
13422        boolean changed = false;
13423        synchronized (mPackages) {
13424            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
13425                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
13426                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
13427                        .valueAt(i);
13428                if (userId != thisUserId) {
13429                    continue;
13430                }
13431                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
13432                while (it.hasNext()) {
13433                    PersistentPreferredActivity ppa = it.next();
13434                    // Mark entry for removal only if it matches the package name.
13435                    if (ppa.mComponent.getPackageName().equals(packageName)) {
13436                        if (removed == null) {
13437                            removed = new ArrayList<PersistentPreferredActivity>();
13438                        }
13439                        removed.add(ppa);
13440                    }
13441                }
13442                if (removed != null) {
13443                    for (int j=0; j<removed.size(); j++) {
13444                        PersistentPreferredActivity ppa = removed.get(j);
13445                        ppir.removeFilter(ppa);
13446                    }
13447                    changed = true;
13448                }
13449            }
13450
13451            if (changed) {
13452                scheduleWritePackageRestrictionsLocked(userId);
13453            }
13454        }
13455    }
13456
13457    /**
13458     * Common machinery for picking apart a restored XML blob and passing
13459     * it to a caller-supplied functor to be applied to the running system.
13460     */
13461    private void restoreFromXml(XmlPullParser parser, int userId,
13462            String expectedStartTag, BlobXmlRestorer functor)
13463            throws IOException, XmlPullParserException {
13464        int type;
13465        while ((type = parser.next()) != XmlPullParser.START_TAG
13466                && type != XmlPullParser.END_DOCUMENT) {
13467        }
13468        if (type != XmlPullParser.START_TAG) {
13469            // oops didn't find a start tag?!
13470            if (DEBUG_BACKUP) {
13471                Slog.e(TAG, "Didn't find start tag during restore");
13472            }
13473            return;
13474        }
13475
13476        // this is supposed to be TAG_PREFERRED_BACKUP
13477        if (!expectedStartTag.equals(parser.getName())) {
13478            if (DEBUG_BACKUP) {
13479                Slog.e(TAG, "Found unexpected tag " + parser.getName());
13480            }
13481            return;
13482        }
13483
13484        // skip interfering stuff, then we're aligned with the backing implementation
13485        while ((type = parser.next()) == XmlPullParser.TEXT) { }
13486        functor.apply(parser, userId);
13487    }
13488
13489    private interface BlobXmlRestorer {
13490        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
13491    }
13492
13493    /**
13494     * Non-Binder method, support for the backup/restore mechanism: write the
13495     * full set of preferred activities in its canonical XML format.  Returns the
13496     * XML output as a byte array, or null if there is none.
13497     */
13498    @Override
13499    public byte[] getPreferredActivityBackup(int userId) {
13500        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13501            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
13502        }
13503
13504        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13505        try {
13506            final XmlSerializer serializer = new FastXmlSerializer();
13507            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13508            serializer.startDocument(null, true);
13509            serializer.startTag(null, TAG_PREFERRED_BACKUP);
13510
13511            synchronized (mPackages) {
13512                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
13513            }
13514
13515            serializer.endTag(null, TAG_PREFERRED_BACKUP);
13516            serializer.endDocument();
13517            serializer.flush();
13518        } catch (Exception e) {
13519            if (DEBUG_BACKUP) {
13520                Slog.e(TAG, "Unable to write preferred activities for backup", e);
13521            }
13522            return null;
13523        }
13524
13525        return dataStream.toByteArray();
13526    }
13527
13528    @Override
13529    public void restorePreferredActivities(byte[] backup, int userId) {
13530        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13531            throw new SecurityException("Only the system may call restorePreferredActivities()");
13532        }
13533
13534        try {
13535            final XmlPullParser parser = Xml.newPullParser();
13536            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13537            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
13538                    new BlobXmlRestorer() {
13539                        @Override
13540                        public void apply(XmlPullParser parser, int userId)
13541                                throws XmlPullParserException, IOException {
13542                            synchronized (mPackages) {
13543                                mSettings.readPreferredActivitiesLPw(parser, userId);
13544                            }
13545                        }
13546                    } );
13547        } catch (Exception e) {
13548            if (DEBUG_BACKUP) {
13549                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
13550            }
13551        }
13552    }
13553
13554    /**
13555     * Non-Binder method, support for the backup/restore mechanism: write the
13556     * default browser (etc) settings in its canonical XML format.  Returns the default
13557     * browser XML representation as a byte array, or null if there is none.
13558     */
13559    @Override
13560    public byte[] getDefaultAppsBackup(int userId) {
13561        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13562            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
13563        }
13564
13565        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13566        try {
13567            final XmlSerializer serializer = new FastXmlSerializer();
13568            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13569            serializer.startDocument(null, true);
13570            serializer.startTag(null, TAG_DEFAULT_APPS);
13571
13572            synchronized (mPackages) {
13573                mSettings.writeDefaultAppsLPr(serializer, userId);
13574            }
13575
13576            serializer.endTag(null, TAG_DEFAULT_APPS);
13577            serializer.endDocument();
13578            serializer.flush();
13579        } catch (Exception e) {
13580            if (DEBUG_BACKUP) {
13581                Slog.e(TAG, "Unable to write default apps for backup", e);
13582            }
13583            return null;
13584        }
13585
13586        return dataStream.toByteArray();
13587    }
13588
13589    @Override
13590    public void restoreDefaultApps(byte[] backup, int userId) {
13591        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13592            throw new SecurityException("Only the system may call restoreDefaultApps()");
13593        }
13594
13595        try {
13596            final XmlPullParser parser = Xml.newPullParser();
13597            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13598            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
13599                    new BlobXmlRestorer() {
13600                        @Override
13601                        public void apply(XmlPullParser parser, int userId)
13602                                throws XmlPullParserException, IOException {
13603                            synchronized (mPackages) {
13604                                mSettings.readDefaultAppsLPw(parser, userId);
13605                            }
13606                        }
13607                    } );
13608        } catch (Exception e) {
13609            if (DEBUG_BACKUP) {
13610                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
13611            }
13612        }
13613    }
13614
13615    @Override
13616    public byte[] getIntentFilterVerificationBackup(int userId) {
13617        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13618            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
13619        }
13620
13621        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13622        try {
13623            final XmlSerializer serializer = new FastXmlSerializer();
13624            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13625            serializer.startDocument(null, true);
13626            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
13627
13628            synchronized (mPackages) {
13629                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
13630            }
13631
13632            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
13633            serializer.endDocument();
13634            serializer.flush();
13635        } catch (Exception e) {
13636            if (DEBUG_BACKUP) {
13637                Slog.e(TAG, "Unable to write default apps for backup", e);
13638            }
13639            return null;
13640        }
13641
13642        return dataStream.toByteArray();
13643    }
13644
13645    @Override
13646    public void restoreIntentFilterVerification(byte[] backup, int userId) {
13647        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13648            throw new SecurityException("Only the system may call restorePreferredActivities()");
13649        }
13650
13651        try {
13652            final XmlPullParser parser = Xml.newPullParser();
13653            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13654            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
13655                    new BlobXmlRestorer() {
13656                        @Override
13657                        public void apply(XmlPullParser parser, int userId)
13658                                throws XmlPullParserException, IOException {
13659                            synchronized (mPackages) {
13660                                mSettings.readAllDomainVerificationsLPr(parser, userId);
13661                                mSettings.writeLPr();
13662                            }
13663                        }
13664                    } );
13665        } catch (Exception e) {
13666            if (DEBUG_BACKUP) {
13667                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
13668            }
13669        }
13670    }
13671
13672    @Override
13673    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
13674            int sourceUserId, int targetUserId, int flags) {
13675        mContext.enforceCallingOrSelfPermission(
13676                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
13677        int callingUid = Binder.getCallingUid();
13678        enforceOwnerRights(ownerPackage, callingUid);
13679        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
13680        if (intentFilter.countActions() == 0) {
13681            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
13682            return;
13683        }
13684        synchronized (mPackages) {
13685            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
13686                    ownerPackage, targetUserId, flags);
13687            CrossProfileIntentResolver resolver =
13688                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
13689            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
13690            // We have all those whose filter is equal. Now checking if the rest is equal as well.
13691            if (existing != null) {
13692                int size = existing.size();
13693                for (int i = 0; i < size; i++) {
13694                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
13695                        return;
13696                    }
13697                }
13698            }
13699            resolver.addFilter(newFilter);
13700            scheduleWritePackageRestrictionsLocked(sourceUserId);
13701        }
13702    }
13703
13704    @Override
13705    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
13706        mContext.enforceCallingOrSelfPermission(
13707                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
13708        int callingUid = Binder.getCallingUid();
13709        enforceOwnerRights(ownerPackage, callingUid);
13710        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
13711        synchronized (mPackages) {
13712            CrossProfileIntentResolver resolver =
13713                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
13714            ArraySet<CrossProfileIntentFilter> set =
13715                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
13716            for (CrossProfileIntentFilter filter : set) {
13717                if (filter.getOwnerPackage().equals(ownerPackage)) {
13718                    resolver.removeFilter(filter);
13719                }
13720            }
13721            scheduleWritePackageRestrictionsLocked(sourceUserId);
13722        }
13723    }
13724
13725    // Enforcing that callingUid is owning pkg on userId
13726    private void enforceOwnerRights(String pkg, int callingUid) {
13727        // The system owns everything.
13728        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
13729            return;
13730        }
13731        int callingUserId = UserHandle.getUserId(callingUid);
13732        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
13733        if (pi == null) {
13734            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
13735                    + callingUserId);
13736        }
13737        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
13738            throw new SecurityException("Calling uid " + callingUid
13739                    + " does not own package " + pkg);
13740        }
13741    }
13742
13743    @Override
13744    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
13745        Intent intent = new Intent(Intent.ACTION_MAIN);
13746        intent.addCategory(Intent.CATEGORY_HOME);
13747
13748        final int callingUserId = UserHandle.getCallingUserId();
13749        List<ResolveInfo> list = queryIntentActivities(intent, null,
13750                PackageManager.GET_META_DATA, callingUserId);
13751        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
13752                true, false, false, callingUserId);
13753
13754        allHomeCandidates.clear();
13755        if (list != null) {
13756            for (ResolveInfo ri : list) {
13757                allHomeCandidates.add(ri);
13758            }
13759        }
13760        return (preferred == null || preferred.activityInfo == null)
13761                ? null
13762                : new ComponentName(preferred.activityInfo.packageName,
13763                        preferred.activityInfo.name);
13764    }
13765
13766    @Override
13767    public void setApplicationEnabledSetting(String appPackageName,
13768            int newState, int flags, int userId, String callingPackage) {
13769        if (!sUserManager.exists(userId)) return;
13770        if (callingPackage == null) {
13771            callingPackage = Integer.toString(Binder.getCallingUid());
13772        }
13773        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
13774    }
13775
13776    @Override
13777    public void setComponentEnabledSetting(ComponentName componentName,
13778            int newState, int flags, int userId) {
13779        if (!sUserManager.exists(userId)) return;
13780        setEnabledSetting(componentName.getPackageName(),
13781                componentName.getClassName(), newState, flags, userId, null);
13782    }
13783
13784    private void setEnabledSetting(final String packageName, String className, int newState,
13785            final int flags, int userId, String callingPackage) {
13786        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
13787              || newState == COMPONENT_ENABLED_STATE_ENABLED
13788              || newState == COMPONENT_ENABLED_STATE_DISABLED
13789              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
13790              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
13791            throw new IllegalArgumentException("Invalid new component state: "
13792                    + newState);
13793        }
13794        PackageSetting pkgSetting;
13795        final int uid = Binder.getCallingUid();
13796        final int permission = mContext.checkCallingOrSelfPermission(
13797                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
13798        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
13799        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
13800        boolean sendNow = false;
13801        boolean isApp = (className == null);
13802        String componentName = isApp ? packageName : className;
13803        int packageUid = -1;
13804        ArrayList<String> components;
13805
13806        // writer
13807        synchronized (mPackages) {
13808            pkgSetting = mSettings.mPackages.get(packageName);
13809            if (pkgSetting == null) {
13810                if (className == null) {
13811                    throw new IllegalArgumentException(
13812                            "Unknown package: " + packageName);
13813                }
13814                throw new IllegalArgumentException(
13815                        "Unknown component: " + packageName
13816                        + "/" + className);
13817            }
13818            // Allow root and verify that userId is not being specified by a different user
13819            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
13820                throw new SecurityException(
13821                        "Permission Denial: attempt to change component state from pid="
13822                        + Binder.getCallingPid()
13823                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
13824            }
13825            if (className == null) {
13826                // We're dealing with an application/package level state change
13827                if (pkgSetting.getEnabled(userId) == newState) {
13828                    // Nothing to do
13829                    return;
13830                }
13831                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
13832                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
13833                    // Don't care about who enables an app.
13834                    callingPackage = null;
13835                }
13836                pkgSetting.setEnabled(newState, userId, callingPackage);
13837                // pkgSetting.pkg.mSetEnabled = newState;
13838            } else {
13839                // We're dealing with a component level state change
13840                // First, verify that this is a valid class name.
13841                PackageParser.Package pkg = pkgSetting.pkg;
13842                if (pkg == null || !pkg.hasComponentClassName(className)) {
13843                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
13844                        throw new IllegalArgumentException("Component class " + className
13845                                + " does not exist in " + packageName);
13846                    } else {
13847                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
13848                                + className + " does not exist in " + packageName);
13849                    }
13850                }
13851                switch (newState) {
13852                case COMPONENT_ENABLED_STATE_ENABLED:
13853                    if (!pkgSetting.enableComponentLPw(className, userId)) {
13854                        return;
13855                    }
13856                    break;
13857                case COMPONENT_ENABLED_STATE_DISABLED:
13858                    if (!pkgSetting.disableComponentLPw(className, userId)) {
13859                        return;
13860                    }
13861                    break;
13862                case COMPONENT_ENABLED_STATE_DEFAULT:
13863                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
13864                        return;
13865                    }
13866                    break;
13867                default:
13868                    Slog.e(TAG, "Invalid new component state: " + newState);
13869                    return;
13870                }
13871            }
13872            scheduleWritePackageRestrictionsLocked(userId);
13873            components = mPendingBroadcasts.get(userId, packageName);
13874            final boolean newPackage = components == null;
13875            if (newPackage) {
13876                components = new ArrayList<String>();
13877            }
13878            if (!components.contains(componentName)) {
13879                components.add(componentName);
13880            }
13881            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
13882                sendNow = true;
13883                // Purge entry from pending broadcast list if another one exists already
13884                // since we are sending one right away.
13885                mPendingBroadcasts.remove(userId, packageName);
13886            } else {
13887                if (newPackage) {
13888                    mPendingBroadcasts.put(userId, packageName, components);
13889                }
13890                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
13891                    // Schedule a message
13892                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
13893                }
13894            }
13895        }
13896
13897        long callingId = Binder.clearCallingIdentity();
13898        try {
13899            if (sendNow) {
13900                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
13901                sendPackageChangedBroadcast(packageName,
13902                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
13903            }
13904        } finally {
13905            Binder.restoreCallingIdentity(callingId);
13906        }
13907    }
13908
13909    private void sendPackageChangedBroadcast(String packageName,
13910            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
13911        if (DEBUG_INSTALL)
13912            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
13913                    + componentNames);
13914        Bundle extras = new Bundle(4);
13915        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
13916        String nameList[] = new String[componentNames.size()];
13917        componentNames.toArray(nameList);
13918        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
13919        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
13920        extras.putInt(Intent.EXTRA_UID, packageUid);
13921        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
13922                new int[] {UserHandle.getUserId(packageUid)});
13923    }
13924
13925    @Override
13926    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
13927        if (!sUserManager.exists(userId)) return;
13928        final int uid = Binder.getCallingUid();
13929        final int permission = mContext.checkCallingOrSelfPermission(
13930                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
13931        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
13932        enforceCrossUserPermission(uid, userId, true, true, "stop package");
13933        // writer
13934        synchronized (mPackages) {
13935            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
13936                    allowedByPermission, uid, userId)) {
13937                scheduleWritePackageRestrictionsLocked(userId);
13938            }
13939        }
13940    }
13941
13942    @Override
13943    public String getInstallerPackageName(String packageName) {
13944        // reader
13945        synchronized (mPackages) {
13946            return mSettings.getInstallerPackageNameLPr(packageName);
13947        }
13948    }
13949
13950    @Override
13951    public int getApplicationEnabledSetting(String packageName, int userId) {
13952        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
13953        int uid = Binder.getCallingUid();
13954        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
13955        // reader
13956        synchronized (mPackages) {
13957            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
13958        }
13959    }
13960
13961    @Override
13962    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
13963        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
13964        int uid = Binder.getCallingUid();
13965        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
13966        // reader
13967        synchronized (mPackages) {
13968            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
13969        }
13970    }
13971
13972    @Override
13973    public void enterSafeMode() {
13974        enforceSystemOrRoot("Only the system can request entering safe mode");
13975
13976        if (!mSystemReady) {
13977            mSafeMode = true;
13978        }
13979    }
13980
13981    @Override
13982    public void systemReady() {
13983        mSystemReady = true;
13984
13985        // Read the compatibilty setting when the system is ready.
13986        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
13987                mContext.getContentResolver(),
13988                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
13989        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
13990        if (DEBUG_SETTINGS) {
13991            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
13992        }
13993
13994        synchronized (mPackages) {
13995            // Verify that all of the preferred activity components actually
13996            // exist.  It is possible for applications to be updated and at
13997            // that point remove a previously declared activity component that
13998            // had been set as a preferred activity.  We try to clean this up
13999            // the next time we encounter that preferred activity, but it is
14000            // possible for the user flow to never be able to return to that
14001            // situation so here we do a sanity check to make sure we haven't
14002            // left any junk around.
14003            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
14004            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14005                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14006                removed.clear();
14007                for (PreferredActivity pa : pir.filterSet()) {
14008                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
14009                        removed.add(pa);
14010                    }
14011                }
14012                if (removed.size() > 0) {
14013                    for (int r=0; r<removed.size(); r++) {
14014                        PreferredActivity pa = removed.get(r);
14015                        Slog.w(TAG, "Removing dangling preferred activity: "
14016                                + pa.mPref.mComponent);
14017                        pir.removeFilter(pa);
14018                    }
14019                    mSettings.writePackageRestrictionsLPr(
14020                            mSettings.mPreferredActivities.keyAt(i));
14021                }
14022            }
14023        }
14024        sUserManager.systemReady();
14025
14026        // If we upgraded grant all default permissions before kicking off.
14027        if (isFirstBoot() || (CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE && mIsUpgrade)) {
14028            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
14029            for (int userId : UserManagerService.getInstance().getUserIds()) {
14030                mDefaultPermissionPolicy.grantDefaultPermissions(userId);
14031            }
14032        }
14033
14034        // Kick off any messages waiting for system ready
14035        if (mPostSystemReadyMessages != null) {
14036            for (Message msg : mPostSystemReadyMessages) {
14037                msg.sendToTarget();
14038            }
14039            mPostSystemReadyMessages = null;
14040        }
14041
14042        // Watch for external volumes that come and go over time
14043        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14044        storage.registerListener(mStorageListener);
14045
14046        mInstallerService.systemReady();
14047        mPackageDexOptimizer.systemReady();
14048    }
14049
14050    @Override
14051    public boolean isSafeMode() {
14052        return mSafeMode;
14053    }
14054
14055    @Override
14056    public boolean hasSystemUidErrors() {
14057        return mHasSystemUidErrors;
14058    }
14059
14060    static String arrayToString(int[] array) {
14061        StringBuffer buf = new StringBuffer(128);
14062        buf.append('[');
14063        if (array != null) {
14064            for (int i=0; i<array.length; i++) {
14065                if (i > 0) buf.append(", ");
14066                buf.append(array[i]);
14067            }
14068        }
14069        buf.append(']');
14070        return buf.toString();
14071    }
14072
14073    static class DumpState {
14074        public static final int DUMP_LIBS = 1 << 0;
14075        public static final int DUMP_FEATURES = 1 << 1;
14076        public static final int DUMP_RESOLVERS = 1 << 2;
14077        public static final int DUMP_PERMISSIONS = 1 << 3;
14078        public static final int DUMP_PACKAGES = 1 << 4;
14079        public static final int DUMP_SHARED_USERS = 1 << 5;
14080        public static final int DUMP_MESSAGES = 1 << 6;
14081        public static final int DUMP_PROVIDERS = 1 << 7;
14082        public static final int DUMP_VERIFIERS = 1 << 8;
14083        public static final int DUMP_PREFERRED = 1 << 9;
14084        public static final int DUMP_PREFERRED_XML = 1 << 10;
14085        public static final int DUMP_KEYSETS = 1 << 11;
14086        public static final int DUMP_VERSION = 1 << 12;
14087        public static final int DUMP_INSTALLS = 1 << 13;
14088        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
14089        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
14090
14091        public static final int OPTION_SHOW_FILTERS = 1 << 0;
14092
14093        private int mTypes;
14094
14095        private int mOptions;
14096
14097        private boolean mTitlePrinted;
14098
14099        private SharedUserSetting mSharedUser;
14100
14101        public boolean isDumping(int type) {
14102            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
14103                return true;
14104            }
14105
14106            return (mTypes & type) != 0;
14107        }
14108
14109        public void setDump(int type) {
14110            mTypes |= type;
14111        }
14112
14113        public boolean isOptionEnabled(int option) {
14114            return (mOptions & option) != 0;
14115        }
14116
14117        public void setOptionEnabled(int option) {
14118            mOptions |= option;
14119        }
14120
14121        public boolean onTitlePrinted() {
14122            final boolean printed = mTitlePrinted;
14123            mTitlePrinted = true;
14124            return printed;
14125        }
14126
14127        public boolean getTitlePrinted() {
14128            return mTitlePrinted;
14129        }
14130
14131        public void setTitlePrinted(boolean enabled) {
14132            mTitlePrinted = enabled;
14133        }
14134
14135        public SharedUserSetting getSharedUser() {
14136            return mSharedUser;
14137        }
14138
14139        public void setSharedUser(SharedUserSetting user) {
14140            mSharedUser = user;
14141        }
14142    }
14143
14144    @Override
14145    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
14146        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
14147                != PackageManager.PERMISSION_GRANTED) {
14148            pw.println("Permission Denial: can't dump ActivityManager from from pid="
14149                    + Binder.getCallingPid()
14150                    + ", uid=" + Binder.getCallingUid()
14151                    + " without permission "
14152                    + android.Manifest.permission.DUMP);
14153            return;
14154        }
14155
14156        DumpState dumpState = new DumpState();
14157        boolean fullPreferred = false;
14158        boolean checkin = false;
14159
14160        String packageName = null;
14161
14162        int opti = 0;
14163        while (opti < args.length) {
14164            String opt = args[opti];
14165            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
14166                break;
14167            }
14168            opti++;
14169
14170            if ("-a".equals(opt)) {
14171                // Right now we only know how to print all.
14172            } else if ("-h".equals(opt)) {
14173                pw.println("Package manager dump options:");
14174                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
14175                pw.println("    --checkin: dump for a checkin");
14176                pw.println("    -f: print details of intent filters");
14177                pw.println("    -h: print this help");
14178                pw.println("  cmd may be one of:");
14179                pw.println("    l[ibraries]: list known shared libraries");
14180                pw.println("    f[ibraries]: list device features");
14181                pw.println("    k[eysets]: print known keysets");
14182                pw.println("    r[esolvers]: dump intent resolvers");
14183                pw.println("    perm[issions]: dump permissions");
14184                pw.println("    pref[erred]: print preferred package settings");
14185                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
14186                pw.println("    prov[iders]: dump content providers");
14187                pw.println("    p[ackages]: dump installed packages");
14188                pw.println("    s[hared-users]: dump shared user IDs");
14189                pw.println("    m[essages]: print collected runtime messages");
14190                pw.println("    v[erifiers]: print package verifier info");
14191                pw.println("    version: print database version info");
14192                pw.println("    write: write current settings now");
14193                pw.println("    <package.name>: info about given package");
14194                pw.println("    installs: details about install sessions");
14195                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
14196                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
14197                return;
14198            } else if ("--checkin".equals(opt)) {
14199                checkin = true;
14200            } else if ("-f".equals(opt)) {
14201                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14202            } else {
14203                pw.println("Unknown argument: " + opt + "; use -h for help");
14204            }
14205        }
14206
14207        // Is the caller requesting to dump a particular piece of data?
14208        if (opti < args.length) {
14209            String cmd = args[opti];
14210            opti++;
14211            // Is this a package name?
14212            if ("android".equals(cmd) || cmd.contains(".")) {
14213                packageName = cmd;
14214                // When dumping a single package, we always dump all of its
14215                // filter information since the amount of data will be reasonable.
14216                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14217            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
14218                dumpState.setDump(DumpState.DUMP_LIBS);
14219            } else if ("f".equals(cmd) || "features".equals(cmd)) {
14220                dumpState.setDump(DumpState.DUMP_FEATURES);
14221            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
14222                dumpState.setDump(DumpState.DUMP_RESOLVERS);
14223            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
14224                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
14225            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
14226                dumpState.setDump(DumpState.DUMP_PREFERRED);
14227            } else if ("preferred-xml".equals(cmd)) {
14228                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
14229                if (opti < args.length && "--full".equals(args[opti])) {
14230                    fullPreferred = true;
14231                    opti++;
14232                }
14233            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
14234                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
14235            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
14236                dumpState.setDump(DumpState.DUMP_PACKAGES);
14237            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
14238                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
14239            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
14240                dumpState.setDump(DumpState.DUMP_PROVIDERS);
14241            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
14242                dumpState.setDump(DumpState.DUMP_MESSAGES);
14243            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
14244                dumpState.setDump(DumpState.DUMP_VERIFIERS);
14245            } else if ("i".equals(cmd) || "ifv".equals(cmd)
14246                    || "intent-filter-verifiers".equals(cmd)) {
14247                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
14248            } else if ("version".equals(cmd)) {
14249                dumpState.setDump(DumpState.DUMP_VERSION);
14250            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
14251                dumpState.setDump(DumpState.DUMP_KEYSETS);
14252            } else if ("installs".equals(cmd)) {
14253                dumpState.setDump(DumpState.DUMP_INSTALLS);
14254            } else if ("write".equals(cmd)) {
14255                synchronized (mPackages) {
14256                    mSettings.writeLPr();
14257                    pw.println("Settings written.");
14258                    return;
14259                }
14260            }
14261        }
14262
14263        if (checkin) {
14264            pw.println("vers,1");
14265        }
14266
14267        // reader
14268        synchronized (mPackages) {
14269            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
14270                if (!checkin) {
14271                    if (dumpState.onTitlePrinted())
14272                        pw.println();
14273                    pw.println("Database versions:");
14274                    pw.print("  SDK Version:");
14275                    pw.print(" internal=");
14276                    pw.print(mSettings.mInternalSdkPlatform);
14277                    pw.print(" external=");
14278                    pw.println(mSettings.mExternalSdkPlatform);
14279                    pw.print("  DB Version:");
14280                    pw.print(" internal=");
14281                    pw.print(mSettings.mInternalDatabaseVersion);
14282                    pw.print(" external=");
14283                    pw.println(mSettings.mExternalDatabaseVersion);
14284                }
14285            }
14286
14287            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
14288                if (!checkin) {
14289                    if (dumpState.onTitlePrinted())
14290                        pw.println();
14291                    pw.println("Verifiers:");
14292                    pw.print("  Required: ");
14293                    pw.print(mRequiredVerifierPackage);
14294                    pw.print(" (uid=");
14295                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
14296                    pw.println(")");
14297                } else if (mRequiredVerifierPackage != null) {
14298                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
14299                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
14300                }
14301            }
14302
14303            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
14304                    packageName == null) {
14305                if (mIntentFilterVerifierComponent != null) {
14306                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
14307                    if (!checkin) {
14308                        if (dumpState.onTitlePrinted())
14309                            pw.println();
14310                        pw.println("Intent Filter Verifier:");
14311                        pw.print("  Using: ");
14312                        pw.print(verifierPackageName);
14313                        pw.print(" (uid=");
14314                        pw.print(getPackageUid(verifierPackageName, 0));
14315                        pw.println(")");
14316                    } else if (verifierPackageName != null) {
14317                        pw.print("ifv,"); pw.print(verifierPackageName);
14318                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
14319                    }
14320                } else {
14321                    pw.println();
14322                    pw.println("No Intent Filter Verifier available!");
14323                }
14324            }
14325
14326            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
14327                boolean printedHeader = false;
14328                final Iterator<String> it = mSharedLibraries.keySet().iterator();
14329                while (it.hasNext()) {
14330                    String name = it.next();
14331                    SharedLibraryEntry ent = mSharedLibraries.get(name);
14332                    if (!checkin) {
14333                        if (!printedHeader) {
14334                            if (dumpState.onTitlePrinted())
14335                                pw.println();
14336                            pw.println("Libraries:");
14337                            printedHeader = true;
14338                        }
14339                        pw.print("  ");
14340                    } else {
14341                        pw.print("lib,");
14342                    }
14343                    pw.print(name);
14344                    if (!checkin) {
14345                        pw.print(" -> ");
14346                    }
14347                    if (ent.path != null) {
14348                        if (!checkin) {
14349                            pw.print("(jar) ");
14350                            pw.print(ent.path);
14351                        } else {
14352                            pw.print(",jar,");
14353                            pw.print(ent.path);
14354                        }
14355                    } else {
14356                        if (!checkin) {
14357                            pw.print("(apk) ");
14358                            pw.print(ent.apk);
14359                        } else {
14360                            pw.print(",apk,");
14361                            pw.print(ent.apk);
14362                        }
14363                    }
14364                    pw.println();
14365                }
14366            }
14367
14368            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
14369                if (dumpState.onTitlePrinted())
14370                    pw.println();
14371                if (!checkin) {
14372                    pw.println("Features:");
14373                }
14374                Iterator<String> it = mAvailableFeatures.keySet().iterator();
14375                while (it.hasNext()) {
14376                    String name = it.next();
14377                    if (!checkin) {
14378                        pw.print("  ");
14379                    } else {
14380                        pw.print("feat,");
14381                    }
14382                    pw.println(name);
14383                }
14384            }
14385
14386            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
14387                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
14388                        : "Activity Resolver Table:", "  ", packageName,
14389                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14390                    dumpState.setTitlePrinted(true);
14391                }
14392                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
14393                        : "Receiver Resolver Table:", "  ", packageName,
14394                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14395                    dumpState.setTitlePrinted(true);
14396                }
14397                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
14398                        : "Service Resolver Table:", "  ", packageName,
14399                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14400                    dumpState.setTitlePrinted(true);
14401                }
14402                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
14403                        : "Provider Resolver Table:", "  ", packageName,
14404                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14405                    dumpState.setTitlePrinted(true);
14406                }
14407            }
14408
14409            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
14410                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14411                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14412                    int user = mSettings.mPreferredActivities.keyAt(i);
14413                    if (pir.dump(pw,
14414                            dumpState.getTitlePrinted()
14415                                ? "\nPreferred Activities User " + user + ":"
14416                                : "Preferred Activities User " + user + ":", "  ",
14417                            packageName, true, false)) {
14418                        dumpState.setTitlePrinted(true);
14419                    }
14420                }
14421            }
14422
14423            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
14424                pw.flush();
14425                FileOutputStream fout = new FileOutputStream(fd);
14426                BufferedOutputStream str = new BufferedOutputStream(fout);
14427                XmlSerializer serializer = new FastXmlSerializer();
14428                try {
14429                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
14430                    serializer.startDocument(null, true);
14431                    serializer.setFeature(
14432                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
14433                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
14434                    serializer.endDocument();
14435                    serializer.flush();
14436                } catch (IllegalArgumentException e) {
14437                    pw.println("Failed writing: " + e);
14438                } catch (IllegalStateException e) {
14439                    pw.println("Failed writing: " + e);
14440                } catch (IOException e) {
14441                    pw.println("Failed writing: " + e);
14442                }
14443            }
14444
14445            if (!checkin
14446                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
14447                    && packageName == null) {
14448                pw.println();
14449                int count = mSettings.mPackages.size();
14450                if (count == 0) {
14451                    pw.println("No domain preferred apps!");
14452                    pw.println();
14453                } else {
14454                    final String prefix = "  ";
14455                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
14456                    if (allPackageSettings.size() == 0) {
14457                        pw.println("No domain preferred apps!");
14458                        pw.println();
14459                    } else {
14460                        pw.println("Domain preferred apps status:");
14461                        pw.println();
14462                        count = 0;
14463                        for (PackageSetting ps : allPackageSettings) {
14464                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
14465                            if (ivi == null || ivi.getPackageName() == null) continue;
14466                            pw.println(prefix + "Package Name: " + ivi.getPackageName());
14467                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
14468                            pw.println(prefix + "Status: " + ivi.getStatusString());
14469                            pw.println();
14470                            count++;
14471                        }
14472                        if (count == 0) {
14473                            pw.println(prefix + "No domain preferred app status!");
14474                            pw.println();
14475                        }
14476                        for (int userId : sUserManager.getUserIds()) {
14477                            pw.println("Domain preferred apps for User " + userId + ":");
14478                            pw.println();
14479                            count = 0;
14480                            for (PackageSetting ps : allPackageSettings) {
14481                                IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
14482                                if (ivi == null || ivi.getPackageName() == null) {
14483                                    continue;
14484                                }
14485                                final int status = ps.getDomainVerificationStatusForUser(userId);
14486                                if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
14487                                    continue;
14488                                }
14489                                pw.println(prefix + "Package Name: " + ivi.getPackageName());
14490                                pw.println(prefix + "Domains: " + ivi.getDomainsString());
14491                                String statusStr = IntentFilterVerificationInfo.
14492                                        getStatusStringFromValue(status);
14493                                pw.println(prefix + "Status: " + statusStr);
14494                                pw.println();
14495                                count++;
14496                            }
14497                            if (count == 0) {
14498                                pw.println(prefix + "No domain preferred apps!");
14499                                pw.println();
14500                            }
14501                        }
14502                    }
14503                }
14504            }
14505
14506            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
14507                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
14508                if (packageName == null) {
14509                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
14510                        if (iperm == 0) {
14511                            if (dumpState.onTitlePrinted())
14512                                pw.println();
14513                            pw.println("AppOp Permissions:");
14514                        }
14515                        pw.print("  AppOp Permission ");
14516                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
14517                        pw.println(":");
14518                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
14519                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
14520                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
14521                        }
14522                    }
14523                }
14524            }
14525
14526            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
14527                boolean printedSomething = false;
14528                for (PackageParser.Provider p : mProviders.mProviders.values()) {
14529                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14530                        continue;
14531                    }
14532                    if (!printedSomething) {
14533                        if (dumpState.onTitlePrinted())
14534                            pw.println();
14535                        pw.println("Registered ContentProviders:");
14536                        printedSomething = true;
14537                    }
14538                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
14539                    pw.print("    "); pw.println(p.toString());
14540                }
14541                printedSomething = false;
14542                for (Map.Entry<String, PackageParser.Provider> entry :
14543                        mProvidersByAuthority.entrySet()) {
14544                    PackageParser.Provider p = entry.getValue();
14545                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14546                        continue;
14547                    }
14548                    if (!printedSomething) {
14549                        if (dumpState.onTitlePrinted())
14550                            pw.println();
14551                        pw.println("ContentProvider Authorities:");
14552                        printedSomething = true;
14553                    }
14554                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
14555                    pw.print("    "); pw.println(p.toString());
14556                    if (p.info != null && p.info.applicationInfo != null) {
14557                        final String appInfo = p.info.applicationInfo.toString();
14558                        pw.print("      applicationInfo="); pw.println(appInfo);
14559                    }
14560                }
14561            }
14562
14563            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
14564                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
14565            }
14566
14567            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
14568                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
14569            }
14570
14571            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
14572                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin);
14573            }
14574
14575            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
14576                // XXX should handle packageName != null by dumping only install data that
14577                // the given package is involved with.
14578                if (dumpState.onTitlePrinted()) pw.println();
14579                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
14580            }
14581
14582            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
14583                if (dumpState.onTitlePrinted()) pw.println();
14584                mSettings.dumpReadMessagesLPr(pw, dumpState);
14585
14586                pw.println();
14587                pw.println("Package warning messages:");
14588                BufferedReader in = null;
14589                String line = null;
14590                try {
14591                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
14592                    while ((line = in.readLine()) != null) {
14593                        if (line.contains("ignored: updated version")) continue;
14594                        pw.println(line);
14595                    }
14596                } catch (IOException ignored) {
14597                } finally {
14598                    IoUtils.closeQuietly(in);
14599                }
14600            }
14601
14602            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
14603                BufferedReader in = null;
14604                String line = null;
14605                try {
14606                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
14607                    while ((line = in.readLine()) != null) {
14608                        if (line.contains("ignored: updated version")) continue;
14609                        pw.print("msg,");
14610                        pw.println(line);
14611                    }
14612                } catch (IOException ignored) {
14613                } finally {
14614                    IoUtils.closeQuietly(in);
14615                }
14616            }
14617        }
14618    }
14619
14620    // ------- apps on sdcard specific code -------
14621    static final boolean DEBUG_SD_INSTALL = false;
14622
14623    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
14624
14625    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
14626
14627    private boolean mMediaMounted = false;
14628
14629    static String getEncryptKey() {
14630        try {
14631            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
14632                    SD_ENCRYPTION_KEYSTORE_NAME);
14633            if (sdEncKey == null) {
14634                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
14635                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
14636                if (sdEncKey == null) {
14637                    Slog.e(TAG, "Failed to create encryption keys");
14638                    return null;
14639                }
14640            }
14641            return sdEncKey;
14642        } catch (NoSuchAlgorithmException nsae) {
14643            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
14644            return null;
14645        } catch (IOException ioe) {
14646            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
14647            return null;
14648        }
14649    }
14650
14651    /*
14652     * Update media status on PackageManager.
14653     */
14654    @Override
14655    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
14656        int callingUid = Binder.getCallingUid();
14657        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
14658            throw new SecurityException("Media status can only be updated by the system");
14659        }
14660        // reader; this apparently protects mMediaMounted, but should probably
14661        // be a different lock in that case.
14662        synchronized (mPackages) {
14663            Log.i(TAG, "Updating external media status from "
14664                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
14665                    + (mediaStatus ? "mounted" : "unmounted"));
14666            if (DEBUG_SD_INSTALL)
14667                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
14668                        + ", mMediaMounted=" + mMediaMounted);
14669            if (mediaStatus == mMediaMounted) {
14670                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
14671                        : 0, -1);
14672                mHandler.sendMessage(msg);
14673                return;
14674            }
14675            mMediaMounted = mediaStatus;
14676        }
14677        // Queue up an async operation since the package installation may take a
14678        // little while.
14679        mHandler.post(new Runnable() {
14680            public void run() {
14681                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
14682            }
14683        });
14684    }
14685
14686    /**
14687     * Called by MountService when the initial ASECs to scan are available.
14688     * Should block until all the ASEC containers are finished being scanned.
14689     */
14690    public void scanAvailableAsecs() {
14691        updateExternalMediaStatusInner(true, false, false);
14692        if (mShouldRestoreconData) {
14693            SELinuxMMAC.setRestoreconDone();
14694            mShouldRestoreconData = false;
14695        }
14696    }
14697
14698    /*
14699     * Collect information of applications on external media, map them against
14700     * existing containers and update information based on current mount status.
14701     * Please note that we always have to report status if reportStatus has been
14702     * set to true especially when unloading packages.
14703     */
14704    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
14705            boolean externalStorage) {
14706        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
14707        int[] uidArr = EmptyArray.INT;
14708
14709        final String[] list = PackageHelper.getSecureContainerList();
14710        if (ArrayUtils.isEmpty(list)) {
14711            Log.i(TAG, "No secure containers found");
14712        } else {
14713            // Process list of secure containers and categorize them
14714            // as active or stale based on their package internal state.
14715
14716            // reader
14717            synchronized (mPackages) {
14718                for (String cid : list) {
14719                    // Leave stages untouched for now; installer service owns them
14720                    if (PackageInstallerService.isStageName(cid)) continue;
14721
14722                    if (DEBUG_SD_INSTALL)
14723                        Log.i(TAG, "Processing container " + cid);
14724                    String pkgName = getAsecPackageName(cid);
14725                    if (pkgName == null) {
14726                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
14727                        continue;
14728                    }
14729                    if (DEBUG_SD_INSTALL)
14730                        Log.i(TAG, "Looking for pkg : " + pkgName);
14731
14732                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
14733                    if (ps == null) {
14734                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
14735                        continue;
14736                    }
14737
14738                    /*
14739                     * Skip packages that are not external if we're unmounting
14740                     * external storage.
14741                     */
14742                    if (externalStorage && !isMounted && !isExternal(ps)) {
14743                        continue;
14744                    }
14745
14746                    final AsecInstallArgs args = new AsecInstallArgs(cid,
14747                            getAppDexInstructionSets(ps), ps.isForwardLocked());
14748                    // The package status is changed only if the code path
14749                    // matches between settings and the container id.
14750                    if (ps.codePathString != null
14751                            && ps.codePathString.startsWith(args.getCodePath())) {
14752                        if (DEBUG_SD_INSTALL) {
14753                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
14754                                    + " at code path: " + ps.codePathString);
14755                        }
14756
14757                        // We do have a valid package installed on sdcard
14758                        processCids.put(args, ps.codePathString);
14759                        final int uid = ps.appId;
14760                        if (uid != -1) {
14761                            uidArr = ArrayUtils.appendInt(uidArr, uid);
14762                        }
14763                    } else {
14764                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
14765                                + ps.codePathString);
14766                    }
14767                }
14768            }
14769
14770            Arrays.sort(uidArr);
14771        }
14772
14773        // Process packages with valid entries.
14774        if (isMounted) {
14775            if (DEBUG_SD_INSTALL)
14776                Log.i(TAG, "Loading packages");
14777            loadMediaPackages(processCids, uidArr);
14778            startCleaningPackages();
14779            mInstallerService.onSecureContainersAvailable();
14780        } else {
14781            if (DEBUG_SD_INSTALL)
14782                Log.i(TAG, "Unloading packages");
14783            unloadMediaPackages(processCids, uidArr, reportStatus);
14784        }
14785    }
14786
14787    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14788            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
14789        final int size = infos.size();
14790        final String[] packageNames = new String[size];
14791        final int[] packageUids = new int[size];
14792        for (int i = 0; i < size; i++) {
14793            final ApplicationInfo info = infos.get(i);
14794            packageNames[i] = info.packageName;
14795            packageUids[i] = info.uid;
14796        }
14797        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
14798                finishedReceiver);
14799    }
14800
14801    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14802            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
14803        sendResourcesChangedBroadcast(mediaStatus, replacing,
14804                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
14805    }
14806
14807    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14808            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
14809        int size = pkgList.length;
14810        if (size > 0) {
14811            // Send broadcasts here
14812            Bundle extras = new Bundle();
14813            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14814            if (uidArr != null) {
14815                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
14816            }
14817            if (replacing) {
14818                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
14819            }
14820            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
14821                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
14822            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
14823        }
14824    }
14825
14826   /*
14827     * Look at potentially valid container ids from processCids If package
14828     * information doesn't match the one on record or package scanning fails,
14829     * the cid is added to list of removeCids. We currently don't delete stale
14830     * containers.
14831     */
14832    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
14833        ArrayList<String> pkgList = new ArrayList<String>();
14834        Set<AsecInstallArgs> keys = processCids.keySet();
14835
14836        for (AsecInstallArgs args : keys) {
14837            String codePath = processCids.get(args);
14838            if (DEBUG_SD_INSTALL)
14839                Log.i(TAG, "Loading container : " + args.cid);
14840            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14841            try {
14842                // Make sure there are no container errors first.
14843                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
14844                    Slog.e(TAG, "Failed to mount cid : " + args.cid
14845                            + " when installing from sdcard");
14846                    continue;
14847                }
14848                // Check code path here.
14849                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
14850                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
14851                            + " does not match one in settings " + codePath);
14852                    continue;
14853                }
14854                // Parse package
14855                int parseFlags = mDefParseFlags;
14856                if (args.isExternalAsec()) {
14857                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
14858                }
14859                if (args.isFwdLocked()) {
14860                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
14861                }
14862
14863                synchronized (mInstallLock) {
14864                    PackageParser.Package pkg = null;
14865                    try {
14866                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
14867                    } catch (PackageManagerException e) {
14868                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
14869                    }
14870                    // Scan the package
14871                    if (pkg != null) {
14872                        /*
14873                         * TODO why is the lock being held? doPostInstall is
14874                         * called in other places without the lock. This needs
14875                         * to be straightened out.
14876                         */
14877                        // writer
14878                        synchronized (mPackages) {
14879                            retCode = PackageManager.INSTALL_SUCCEEDED;
14880                            pkgList.add(pkg.packageName);
14881                            // Post process args
14882                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
14883                                    pkg.applicationInfo.uid);
14884                        }
14885                    } else {
14886                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
14887                    }
14888                }
14889
14890            } finally {
14891                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
14892                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
14893                }
14894            }
14895        }
14896        // writer
14897        synchronized (mPackages) {
14898            // If the platform SDK has changed since the last time we booted,
14899            // we need to re-grant app permission to catch any new ones that
14900            // appear. This is really a hack, and means that apps can in some
14901            // cases get permissions that the user didn't initially explicitly
14902            // allow... it would be nice to have some better way to handle
14903            // this situation.
14904            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
14905            if (regrantPermissions)
14906                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
14907                        + mSdkVersion + "; regranting permissions for external storage");
14908            mSettings.mExternalSdkPlatform = mSdkVersion;
14909
14910            // Make sure group IDs have been assigned, and any permission
14911            // changes in other apps are accounted for
14912            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
14913                    | (regrantPermissions
14914                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
14915                            : 0));
14916
14917            mSettings.updateExternalDatabaseVersion();
14918
14919            // can downgrade to reader
14920            // Persist settings
14921            mSettings.writeLPr();
14922        }
14923        // Send a broadcast to let everyone know we are done processing
14924        if (pkgList.size() > 0) {
14925            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
14926        }
14927    }
14928
14929   /*
14930     * Utility method to unload a list of specified containers
14931     */
14932    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
14933        // Just unmount all valid containers.
14934        for (AsecInstallArgs arg : cidArgs) {
14935            synchronized (mInstallLock) {
14936                arg.doPostDeleteLI(false);
14937           }
14938       }
14939   }
14940
14941    /*
14942     * Unload packages mounted on external media. This involves deleting package
14943     * data from internal structures, sending broadcasts about diabled packages,
14944     * gc'ing to free up references, unmounting all secure containers
14945     * corresponding to packages on external media, and posting a
14946     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
14947     * that we always have to post this message if status has been requested no
14948     * matter what.
14949     */
14950    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
14951            final boolean reportStatus) {
14952        if (DEBUG_SD_INSTALL)
14953            Log.i(TAG, "unloading media packages");
14954        ArrayList<String> pkgList = new ArrayList<String>();
14955        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
14956        final Set<AsecInstallArgs> keys = processCids.keySet();
14957        for (AsecInstallArgs args : keys) {
14958            String pkgName = args.getPackageName();
14959            if (DEBUG_SD_INSTALL)
14960                Log.i(TAG, "Trying to unload pkg : " + pkgName);
14961            // Delete package internally
14962            PackageRemovedInfo outInfo = new PackageRemovedInfo();
14963            synchronized (mInstallLock) {
14964                boolean res = deletePackageLI(pkgName, null, false, null, null,
14965                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
14966                if (res) {
14967                    pkgList.add(pkgName);
14968                } else {
14969                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
14970                    failedList.add(args);
14971                }
14972            }
14973        }
14974
14975        // reader
14976        synchronized (mPackages) {
14977            // We didn't update the settings after removing each package;
14978            // write them now for all packages.
14979            mSettings.writeLPr();
14980        }
14981
14982        // We have to absolutely send UPDATED_MEDIA_STATUS only
14983        // after confirming that all the receivers processed the ordered
14984        // broadcast when packages get disabled, force a gc to clean things up.
14985        // and unload all the containers.
14986        if (pkgList.size() > 0) {
14987            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
14988                    new IIntentReceiver.Stub() {
14989                public void performReceive(Intent intent, int resultCode, String data,
14990                        Bundle extras, boolean ordered, boolean sticky,
14991                        int sendingUser) throws RemoteException {
14992                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
14993                            reportStatus ? 1 : 0, 1, keys);
14994                    mHandler.sendMessage(msg);
14995                }
14996            });
14997        } else {
14998            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
14999                    keys);
15000            mHandler.sendMessage(msg);
15001        }
15002    }
15003
15004    private void loadPrivatePackages(VolumeInfo vol) {
15005        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
15006        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
15007        synchronized (mInstallLock) {
15008        synchronized (mPackages) {
15009            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15010            for (PackageSetting ps : packages) {
15011                final PackageParser.Package pkg;
15012                try {
15013                    pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null);
15014                    loaded.add(pkg.applicationInfo);
15015                } catch (PackageManagerException e) {
15016                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
15017                }
15018            }
15019
15020            // TODO: regrant any permissions that changed based since original install
15021
15022            mSettings.writeLPr();
15023        }
15024        }
15025
15026        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
15027        sendResourcesChangedBroadcast(true, false, loaded, null);
15028    }
15029
15030    private void unloadPrivatePackages(VolumeInfo vol) {
15031        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
15032        synchronized (mInstallLock) {
15033        synchronized (mPackages) {
15034            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15035            for (PackageSetting ps : packages) {
15036                if (ps.pkg == null) continue;
15037
15038                final ApplicationInfo info = ps.pkg.applicationInfo;
15039                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
15040                if (deletePackageLI(ps.name, null, false, null, null,
15041                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
15042                    unloaded.add(info);
15043                } else {
15044                    Slog.w(TAG, "Failed to unload " + ps.codePath);
15045                }
15046            }
15047
15048            mSettings.writeLPr();
15049        }
15050        }
15051
15052        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
15053        sendResourcesChangedBroadcast(false, false, unloaded, null);
15054    }
15055
15056    private void unfreezePackage(String packageName) {
15057        synchronized (mPackages) {
15058            final PackageSetting ps = mSettings.mPackages.get(packageName);
15059            if (ps != null) {
15060                ps.frozen = false;
15061            }
15062        }
15063    }
15064
15065    @Override
15066    public int movePackage(final String packageName, final String volumeUuid) {
15067        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15068
15069        final int moveId = mNextMoveId.getAndIncrement();
15070        try {
15071            movePackageInternal(packageName, volumeUuid, moveId);
15072        } catch (PackageManagerException e) {
15073            Slog.w(TAG, "Failed to move " + packageName, e);
15074            mMoveCallbacks.notifyStatusChanged(moveId,
15075                    PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15076        }
15077        return moveId;
15078    }
15079
15080    private void movePackageInternal(final String packageName, final String volumeUuid,
15081            final int moveId) throws PackageManagerException {
15082        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
15083        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15084        final PackageManager pm = mContext.getPackageManager();
15085
15086        final boolean currentAsec;
15087        final String currentVolumeUuid;
15088        final File codeFile;
15089        final String installerPackageName;
15090        final String packageAbiOverride;
15091        final int appId;
15092        final String seinfo;
15093        final String label;
15094
15095        // reader
15096        synchronized (mPackages) {
15097            final PackageParser.Package pkg = mPackages.get(packageName);
15098            final PackageSetting ps = mSettings.mPackages.get(packageName);
15099            if (pkg == null || ps == null) {
15100                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
15101            }
15102
15103            if (pkg.applicationInfo.isSystemApp()) {
15104                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
15105                        "Cannot move system application");
15106            }
15107
15108            if (Objects.equals(ps.volumeUuid, volumeUuid)) {
15109                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15110                        "Package already moved to " + volumeUuid);
15111            }
15112
15113            final File probe = new File(pkg.codePath);
15114            final File probeOat = new File(probe, "oat");
15115            if (!probe.isDirectory() || !probeOat.isDirectory()) {
15116                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15117                        "Move only supported for modern cluster style installs");
15118            }
15119
15120            if (ps.frozen) {
15121                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
15122                        "Failed to move already frozen package");
15123            }
15124            ps.frozen = true;
15125
15126            currentAsec = pkg.applicationInfo.isForwardLocked()
15127                    || pkg.applicationInfo.isExternalAsec();
15128            currentVolumeUuid = ps.volumeUuid;
15129            codeFile = new File(pkg.codePath);
15130            installerPackageName = ps.installerPackageName;
15131            packageAbiOverride = ps.cpuAbiOverrideString;
15132            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
15133            seinfo = pkg.applicationInfo.seinfo;
15134            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
15135        }
15136
15137        // Now that we're guarded by frozen state, kill app during move
15138        killApplication(packageName, appId, "move pkg");
15139
15140        final Bundle extras = new Bundle();
15141        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
15142        extras.putString(Intent.EXTRA_TITLE, label);
15143        mMoveCallbacks.notifyCreated(moveId, extras);
15144
15145        int installFlags;
15146        final boolean moveCompleteApp;
15147        final File measurePath;
15148
15149        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
15150            installFlags = INSTALL_INTERNAL;
15151            moveCompleteApp = !currentAsec;
15152            measurePath = Environment.getDataAppDirectory(volumeUuid);
15153        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
15154            installFlags = INSTALL_EXTERNAL;
15155            moveCompleteApp = false;
15156            measurePath = storage.getPrimaryPhysicalVolume().getPath();
15157        } else {
15158            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
15159            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
15160                    || !volume.isMountedWritable()) {
15161                unfreezePackage(packageName);
15162                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15163                        "Move location not mounted private volume");
15164            }
15165
15166            Preconditions.checkState(!currentAsec);
15167
15168            installFlags = INSTALL_INTERNAL;
15169            moveCompleteApp = true;
15170            measurePath = Environment.getDataAppDirectory(volumeUuid);
15171        }
15172
15173        final PackageStats stats = new PackageStats(null, -1);
15174        synchronized (mInstaller) {
15175            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
15176                unfreezePackage(packageName);
15177                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15178                        "Failed to measure package size");
15179            }
15180        }
15181
15182        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
15183                + stats.dataSize);
15184
15185        final long startFreeBytes = measurePath.getFreeSpace();
15186        final long sizeBytes;
15187        if (moveCompleteApp) {
15188            sizeBytes = stats.codeSize + stats.dataSize;
15189        } else {
15190            sizeBytes = stats.codeSize;
15191        }
15192
15193        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
15194            unfreezePackage(packageName);
15195            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15196                    "Not enough free space to move");
15197        }
15198
15199        mMoveCallbacks.notifyStatusChanged(moveId, 10);
15200
15201        final CountDownLatch installedLatch = new CountDownLatch(1);
15202        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
15203            @Override
15204            public void onUserActionRequired(Intent intent) throws RemoteException {
15205                throw new IllegalStateException();
15206            }
15207
15208            @Override
15209            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
15210                    Bundle extras) throws RemoteException {
15211                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
15212                        + PackageManager.installStatusToString(returnCode, msg));
15213
15214                installedLatch.countDown();
15215
15216                // Regardless of success or failure of the move operation,
15217                // always unfreeze the package
15218                unfreezePackage(packageName);
15219
15220                final int status = PackageManager.installStatusToPublicStatus(returnCode);
15221                switch (status) {
15222                    case PackageInstaller.STATUS_SUCCESS:
15223                        mMoveCallbacks.notifyStatusChanged(moveId,
15224                                PackageManager.MOVE_SUCCEEDED);
15225                        break;
15226                    case PackageInstaller.STATUS_FAILURE_STORAGE:
15227                        mMoveCallbacks.notifyStatusChanged(moveId,
15228                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
15229                        break;
15230                    default:
15231                        mMoveCallbacks.notifyStatusChanged(moveId,
15232                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15233                        break;
15234                }
15235            }
15236        };
15237
15238        final MoveInfo move;
15239        if (moveCompleteApp) {
15240            // Kick off a thread to report progress estimates
15241            new Thread() {
15242                @Override
15243                public void run() {
15244                    while (true) {
15245                        try {
15246                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
15247                                break;
15248                            }
15249                        } catch (InterruptedException ignored) {
15250                        }
15251
15252                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
15253                        final int progress = 10 + (int) MathUtils.constrain(
15254                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
15255                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
15256                    }
15257                }
15258            }.start();
15259
15260            final String dataAppName = codeFile.getName();
15261            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
15262                    dataAppName, appId, seinfo);
15263        } else {
15264            move = null;
15265        }
15266
15267        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
15268
15269        final Message msg = mHandler.obtainMessage(INIT_COPY);
15270        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
15271        msg.obj = new InstallParams(origin, move, installObserver, installFlags,
15272                installerPackageName, volumeUuid, null, user, packageAbiOverride);
15273        mHandler.sendMessage(msg);
15274    }
15275
15276    @Override
15277    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
15278        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15279
15280        final int realMoveId = mNextMoveId.getAndIncrement();
15281        final Bundle extras = new Bundle();
15282        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
15283        mMoveCallbacks.notifyCreated(realMoveId, extras);
15284
15285        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
15286            @Override
15287            public void onCreated(int moveId, Bundle extras) {
15288                // Ignored
15289            }
15290
15291            @Override
15292            public void onStatusChanged(int moveId, int status, long estMillis) {
15293                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
15294            }
15295        };
15296
15297        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15298        storage.setPrimaryStorageUuid(volumeUuid, callback);
15299        return realMoveId;
15300    }
15301
15302    @Override
15303    public int getMoveStatus(int moveId) {
15304        mContext.enforceCallingOrSelfPermission(
15305                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15306        return mMoveCallbacks.mLastStatus.get(moveId);
15307    }
15308
15309    @Override
15310    public void registerMoveCallback(IPackageMoveObserver callback) {
15311        mContext.enforceCallingOrSelfPermission(
15312                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15313        mMoveCallbacks.register(callback);
15314    }
15315
15316    @Override
15317    public void unregisterMoveCallback(IPackageMoveObserver callback) {
15318        mContext.enforceCallingOrSelfPermission(
15319                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15320        mMoveCallbacks.unregister(callback);
15321    }
15322
15323    @Override
15324    public boolean setInstallLocation(int loc) {
15325        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
15326                null);
15327        if (getInstallLocation() == loc) {
15328            return true;
15329        }
15330        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
15331                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
15332            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
15333                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
15334            return true;
15335        }
15336        return false;
15337   }
15338
15339    @Override
15340    public int getInstallLocation() {
15341        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15342                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
15343                PackageHelper.APP_INSTALL_AUTO);
15344    }
15345
15346    /** Called by UserManagerService */
15347    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
15348        mDirtyUsers.remove(userHandle);
15349        mSettings.removeUserLPw(userHandle);
15350        mPendingBroadcasts.remove(userHandle);
15351        if (mInstaller != null) {
15352            // Technically, we shouldn't be doing this with the package lock
15353            // held.  However, this is very rare, and there is already so much
15354            // other disk I/O going on, that we'll let it slide for now.
15355            final StorageManager storage = StorageManager.from(mContext);
15356            final List<VolumeInfo> vols = storage.getVolumes();
15357            for (VolumeInfo vol : vols) {
15358                if (vol.getType() == VolumeInfo.TYPE_PRIVATE && vol.isMountedWritable()) {
15359                    final String volumeUuid = vol.getFsUuid();
15360                    if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
15361                    mInstaller.removeUserDataDirs(volumeUuid, userHandle);
15362                }
15363            }
15364        }
15365        mUserNeedsBadging.delete(userHandle);
15366        removeUnusedPackagesLILPw(userManager, userHandle);
15367    }
15368
15369    /**
15370     * We're removing userHandle and would like to remove any downloaded packages
15371     * that are no longer in use by any other user.
15372     * @param userHandle the user being removed
15373     */
15374    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
15375        final boolean DEBUG_CLEAN_APKS = false;
15376        int [] users = userManager.getUserIdsLPr();
15377        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
15378        while (psit.hasNext()) {
15379            PackageSetting ps = psit.next();
15380            if (ps.pkg == null) {
15381                continue;
15382            }
15383            final String packageName = ps.pkg.packageName;
15384            // Skip over if system app
15385            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15386                continue;
15387            }
15388            if (DEBUG_CLEAN_APKS) {
15389                Slog.i(TAG, "Checking package " + packageName);
15390            }
15391            boolean keep = false;
15392            for (int i = 0; i < users.length; i++) {
15393                if (users[i] != userHandle && ps.getInstalled(users[i])) {
15394                    keep = true;
15395                    if (DEBUG_CLEAN_APKS) {
15396                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
15397                                + users[i]);
15398                    }
15399                    break;
15400                }
15401            }
15402            if (!keep) {
15403                if (DEBUG_CLEAN_APKS) {
15404                    Slog.i(TAG, "  Removing package " + packageName);
15405                }
15406                mHandler.post(new Runnable() {
15407                    public void run() {
15408                        deletePackageX(packageName, userHandle, 0);
15409                    } //end run
15410                });
15411            }
15412        }
15413    }
15414
15415    /** Called by UserManagerService */
15416    void createNewUserLILPw(int userHandle, File path) {
15417        if (mInstaller != null) {
15418            mInstaller.createUserConfig(userHandle);
15419            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
15420        }
15421    }
15422
15423    void newUserCreatedLILPw(final int userHandle) {
15424        // We cannot grant the default permissions with a lock held as
15425        // we query providers from other components for default handlers
15426        // such as enabled IMEs, etc.
15427        mHandler.post(new Runnable() {
15428            @Override
15429            public void run() {
15430                mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
15431            }
15432        });
15433    }
15434
15435    @Override
15436    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
15437        mContext.enforceCallingOrSelfPermission(
15438                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15439                "Only package verification agents can read the verifier device identity");
15440
15441        synchronized (mPackages) {
15442            return mSettings.getVerifierDeviceIdentityLPw();
15443        }
15444    }
15445
15446    @Override
15447    public void setPermissionEnforced(String permission, boolean enforced) {
15448        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
15449        if (READ_EXTERNAL_STORAGE.equals(permission)) {
15450            synchronized (mPackages) {
15451                if (mSettings.mReadExternalStorageEnforced == null
15452                        || mSettings.mReadExternalStorageEnforced != enforced) {
15453                    mSettings.mReadExternalStorageEnforced = enforced;
15454                    mSettings.writeLPr();
15455                }
15456            }
15457            // kill any non-foreground processes so we restart them and
15458            // grant/revoke the GID.
15459            final IActivityManager am = ActivityManagerNative.getDefault();
15460            if (am != null) {
15461                final long token = Binder.clearCallingIdentity();
15462                try {
15463                    am.killProcessesBelowForeground("setPermissionEnforcement");
15464                } catch (RemoteException e) {
15465                } finally {
15466                    Binder.restoreCallingIdentity(token);
15467                }
15468            }
15469        } else {
15470            throw new IllegalArgumentException("No selective enforcement for " + permission);
15471        }
15472    }
15473
15474    @Override
15475    @Deprecated
15476    public boolean isPermissionEnforced(String permission) {
15477        return true;
15478    }
15479
15480    @Override
15481    public boolean isStorageLow() {
15482        final long token = Binder.clearCallingIdentity();
15483        try {
15484            final DeviceStorageMonitorInternal
15485                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
15486            if (dsm != null) {
15487                return dsm.isMemoryLow();
15488            } else {
15489                return false;
15490            }
15491        } finally {
15492            Binder.restoreCallingIdentity(token);
15493        }
15494    }
15495
15496    @Override
15497    public IPackageInstaller getPackageInstaller() {
15498        return mInstallerService;
15499    }
15500
15501    private boolean userNeedsBadging(int userId) {
15502        int index = mUserNeedsBadging.indexOfKey(userId);
15503        if (index < 0) {
15504            final UserInfo userInfo;
15505            final long token = Binder.clearCallingIdentity();
15506            try {
15507                userInfo = sUserManager.getUserInfo(userId);
15508            } finally {
15509                Binder.restoreCallingIdentity(token);
15510            }
15511            final boolean b;
15512            if (userInfo != null && userInfo.isManagedProfile()) {
15513                b = true;
15514            } else {
15515                b = false;
15516            }
15517            mUserNeedsBadging.put(userId, b);
15518            return b;
15519        }
15520        return mUserNeedsBadging.valueAt(index);
15521    }
15522
15523    @Override
15524    public KeySet getKeySetByAlias(String packageName, String alias) {
15525        if (packageName == null || alias == null) {
15526            return null;
15527        }
15528        synchronized(mPackages) {
15529            final PackageParser.Package pkg = mPackages.get(packageName);
15530            if (pkg == null) {
15531                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15532                throw new IllegalArgumentException("Unknown package: " + packageName);
15533            }
15534            KeySetManagerService ksms = mSettings.mKeySetManagerService;
15535            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
15536        }
15537    }
15538
15539    @Override
15540    public KeySet getSigningKeySet(String packageName) {
15541        if (packageName == null) {
15542            return null;
15543        }
15544        synchronized(mPackages) {
15545            final PackageParser.Package pkg = mPackages.get(packageName);
15546            if (pkg == null) {
15547                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15548                throw new IllegalArgumentException("Unknown package: " + packageName);
15549            }
15550            if (pkg.applicationInfo.uid != Binder.getCallingUid()
15551                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
15552                throw new SecurityException("May not access signing KeySet of other apps.");
15553            }
15554            KeySetManagerService ksms = mSettings.mKeySetManagerService;
15555            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
15556        }
15557    }
15558
15559    @Override
15560    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
15561        if (packageName == null || ks == null) {
15562            return false;
15563        }
15564        synchronized(mPackages) {
15565            final PackageParser.Package pkg = mPackages.get(packageName);
15566            if (pkg == null) {
15567                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15568                throw new IllegalArgumentException("Unknown package: " + packageName);
15569            }
15570            IBinder ksh = ks.getToken();
15571            if (ksh instanceof KeySetHandle) {
15572                KeySetManagerService ksms = mSettings.mKeySetManagerService;
15573                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
15574            }
15575            return false;
15576        }
15577    }
15578
15579    @Override
15580    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
15581        if (packageName == null || ks == null) {
15582            return false;
15583        }
15584        synchronized(mPackages) {
15585            final PackageParser.Package pkg = mPackages.get(packageName);
15586            if (pkg == null) {
15587                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15588                throw new IllegalArgumentException("Unknown package: " + packageName);
15589            }
15590            IBinder ksh = ks.getToken();
15591            if (ksh instanceof KeySetHandle) {
15592                KeySetManagerService ksms = mSettings.mKeySetManagerService;
15593                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
15594            }
15595            return false;
15596        }
15597    }
15598
15599    public void getUsageStatsIfNoPackageUsageInfo() {
15600        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
15601            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
15602            if (usm == null) {
15603                throw new IllegalStateException("UsageStatsManager must be initialized");
15604            }
15605            long now = System.currentTimeMillis();
15606            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
15607            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
15608                String packageName = entry.getKey();
15609                PackageParser.Package pkg = mPackages.get(packageName);
15610                if (pkg == null) {
15611                    continue;
15612                }
15613                UsageStats usage = entry.getValue();
15614                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
15615                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
15616            }
15617        }
15618    }
15619
15620    /**
15621     * Check and throw if the given before/after packages would be considered a
15622     * downgrade.
15623     */
15624    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
15625            throws PackageManagerException {
15626        if (after.versionCode < before.mVersionCode) {
15627            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15628                    "Update version code " + after.versionCode + " is older than current "
15629                    + before.mVersionCode);
15630        } else if (after.versionCode == before.mVersionCode) {
15631            if (after.baseRevisionCode < before.baseRevisionCode) {
15632                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15633                        "Update base revision code " + after.baseRevisionCode
15634                        + " is older than current " + before.baseRevisionCode);
15635            }
15636
15637            if (!ArrayUtils.isEmpty(after.splitNames)) {
15638                for (int i = 0; i < after.splitNames.length; i++) {
15639                    final String splitName = after.splitNames[i];
15640                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
15641                    if (j != -1) {
15642                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
15643                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15644                                    "Update split " + splitName + " revision code "
15645                                    + after.splitRevisionCodes[i] + " is older than current "
15646                                    + before.splitRevisionCodes[j]);
15647                        }
15648                    }
15649                }
15650            }
15651        }
15652    }
15653
15654    private static class MoveCallbacks extends Handler {
15655        private static final int MSG_CREATED = 1;
15656        private static final int MSG_STATUS_CHANGED = 2;
15657
15658        private final RemoteCallbackList<IPackageMoveObserver>
15659                mCallbacks = new RemoteCallbackList<>();
15660
15661        private final SparseIntArray mLastStatus = new SparseIntArray();
15662
15663        public MoveCallbacks(Looper looper) {
15664            super(looper);
15665        }
15666
15667        public void register(IPackageMoveObserver callback) {
15668            mCallbacks.register(callback);
15669        }
15670
15671        public void unregister(IPackageMoveObserver callback) {
15672            mCallbacks.unregister(callback);
15673        }
15674
15675        @Override
15676        public void handleMessage(Message msg) {
15677            final SomeArgs args = (SomeArgs) msg.obj;
15678            final int n = mCallbacks.beginBroadcast();
15679            for (int i = 0; i < n; i++) {
15680                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
15681                try {
15682                    invokeCallback(callback, msg.what, args);
15683                } catch (RemoteException ignored) {
15684                }
15685            }
15686            mCallbacks.finishBroadcast();
15687            args.recycle();
15688        }
15689
15690        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
15691                throws RemoteException {
15692            switch (what) {
15693                case MSG_CREATED: {
15694                    callback.onCreated(args.argi1, (Bundle) args.arg2);
15695                    break;
15696                }
15697                case MSG_STATUS_CHANGED: {
15698                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
15699                    break;
15700                }
15701            }
15702        }
15703
15704        private void notifyCreated(int moveId, Bundle extras) {
15705            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
15706
15707            final SomeArgs args = SomeArgs.obtain();
15708            args.argi1 = moveId;
15709            args.arg2 = extras;
15710            obtainMessage(MSG_CREATED, args).sendToTarget();
15711        }
15712
15713        private void notifyStatusChanged(int moveId, int status) {
15714            notifyStatusChanged(moveId, status, -1);
15715        }
15716
15717        private void notifyStatusChanged(int moveId, int status, long estMillis) {
15718            Slog.v(TAG, "Move " + moveId + " status " + status);
15719
15720            final SomeArgs args = SomeArgs.obtain();
15721            args.argi1 = moveId;
15722            args.argi2 = status;
15723            args.arg3 = estMillis;
15724            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
15725
15726            synchronized (mLastStatus) {
15727                mLastStatus.put(moveId, status);
15728            }
15729        }
15730    }
15731
15732    private final class OnPermissionChangeListeners extends Handler {
15733        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
15734
15735        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
15736                new RemoteCallbackList<>();
15737
15738        public OnPermissionChangeListeners(Looper looper) {
15739            super(looper);
15740        }
15741
15742        @Override
15743        public void handleMessage(Message msg) {
15744            switch (msg.what) {
15745                case MSG_ON_PERMISSIONS_CHANGED: {
15746                    final int uid = msg.arg1;
15747                    handleOnPermissionsChanged(uid);
15748                } break;
15749            }
15750        }
15751
15752        public void addListenerLocked(IOnPermissionsChangeListener listener) {
15753            mPermissionListeners.register(listener);
15754
15755        }
15756
15757        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
15758            mPermissionListeners.unregister(listener);
15759        }
15760
15761        public void onPermissionsChanged(int uid) {
15762            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
15763                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
15764            }
15765        }
15766
15767        private void handleOnPermissionsChanged(int uid) {
15768            final int count = mPermissionListeners.beginBroadcast();
15769            try {
15770                for (int i = 0; i < count; i++) {
15771                    IOnPermissionsChangeListener callback = mPermissionListeners
15772                            .getBroadcastItem(i);
15773                    try {
15774                        callback.onPermissionsChanged(uid);
15775                    } catch (RemoteException e) {
15776                        Log.e(TAG, "Permission listener is dead", e);
15777                    }
15778                }
15779            } finally {
15780                mPermissionListeners.finishBroadcast();
15781            }
15782        }
15783    }
15784
15785    private class PackageManagerInternalImpl extends PackageManagerInternal {
15786        @Override
15787        public void setLocationPackagesProvider(PackagesProvider provider) {
15788            synchronized (mPackages) {
15789                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
15790            }
15791        }
15792
15793        @Override
15794        public void setImePackagesProvider(PackagesProvider provider) {
15795            synchronized (mPackages) {
15796                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
15797            }
15798        }
15799
15800        @Override
15801        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
15802            synchronized (mPackages) {
15803                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
15804            }
15805        }
15806    }
15807
15808    @Override
15809    public void grantDefaultPermissions(final int userId) {
15810        enforceSystemOrPhoneCaller("grantDefaultPermissions");
15811        long token = Binder.clearCallingIdentity();
15812        try {
15813            // We cannot grant the default permissions with a lock held as
15814            // we query providers from other components for default handlers
15815            // such as enabled IMEs, etc.
15816            mHandler.post(new Runnable() {
15817                @Override
15818                public void run() {
15819                    mDefaultPermissionPolicy.grantDefaultPermissions(userId);
15820                }
15821            });
15822        } finally {
15823            Binder.restoreCallingIdentity(token);
15824        }
15825    }
15826
15827    @Override
15828    public void setCarrierAppPackagesProvider(final IPackagesProvider provider) {
15829        enforceSystemOrPhoneCaller("setCarrierAppPackagesProvider");
15830        long token = Binder.clearCallingIdentity();
15831        try {
15832            PackageManagerInternal.PackagesProvider wrapper =
15833                    new PackageManagerInternal.PackagesProvider() {
15834                @Override
15835                public String[] getPackages(int userId) {
15836                    try {
15837                        return provider.getPackages(userId);
15838                    } catch (RemoteException e) {
15839                        return null;
15840                    }
15841                }
15842            };
15843            synchronized (mPackages) {
15844                mDefaultPermissionPolicy.setCarrierAppPackagesProviderLPw(wrapper);
15845            }
15846        } finally {
15847            Binder.restoreCallingIdentity(token);
15848        }
15849    }
15850
15851    private static void enforceSystemOrPhoneCaller(String tag) {
15852        int callingUid = Binder.getCallingUid();
15853        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
15854            throw new SecurityException(
15855                    "Cannot call " + tag + " from UID " + callingUid);
15856        }
15857    }
15858}
15859