PackageManagerService.java revision 1d69d48596dae3c3e365182aa13acbd56b106b2e
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.InstrumentationInfo;
104import android.content.pm.IntentFilterVerificationInfo;
105import android.content.pm.KeySet;
106import android.content.pm.ManifestDigest;
107import android.content.pm.PackageCleanItem;
108import android.content.pm.PackageInfo;
109import android.content.pm.PackageInfoLite;
110import android.content.pm.PackageInstaller;
111import android.content.pm.PackageManager;
112import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
113import android.content.pm.PackageManagerInternal;
114import android.content.pm.PackageParser;
115import android.content.pm.PackageParser.ActivityIntentInfo;
116import android.content.pm.PackageParser.PackageLite;
117import android.content.pm.PackageParser.PackageParserException;
118import android.content.pm.PackageStats;
119import android.content.pm.PackageUserState;
120import android.content.pm.ParceledListSlice;
121import android.content.pm.PermissionGroupInfo;
122import android.content.pm.PermissionInfo;
123import android.content.pm.ProviderInfo;
124import android.content.pm.ResolveInfo;
125import android.content.pm.ServiceInfo;
126import android.content.pm.Signature;
127import android.content.pm.UserInfo;
128import android.content.pm.VerificationParams;
129import android.content.pm.VerifierDeviceIdentity;
130import android.content.pm.VerifierInfo;
131import android.content.res.Resources;
132import android.hardware.display.DisplayManager;
133import android.net.Uri;
134import android.os.Binder;
135import android.os.Build;
136import android.os.Bundle;
137import android.os.Debug;
138import android.os.Environment;
139import android.os.Environment.UserEnvironment;
140import android.os.FileUtils;
141import android.os.Handler;
142import android.os.IBinder;
143import android.os.Looper;
144import android.os.Message;
145import android.os.Parcel;
146import android.os.ParcelFileDescriptor;
147import android.os.Process;
148import android.os.RemoteCallbackList;
149import android.os.RemoteException;
150import android.os.SELinux;
151import android.os.ServiceManager;
152import android.os.SystemClock;
153import android.os.SystemProperties;
154import android.os.UserHandle;
155import android.os.UserManager;
156import android.os.storage.IMountService;
157import android.os.storage.StorageEventListener;
158import android.os.storage.StorageManager;
159import android.os.storage.VolumeInfo;
160import android.os.storage.VolumeRecord;
161import android.security.KeyStore;
162import android.security.SystemKeyStore;
163import android.system.ErrnoException;
164import android.system.Os;
165import android.system.StructStat;
166import android.text.TextUtils;
167import android.text.format.DateUtils;
168import android.util.ArrayMap;
169import android.util.ArraySet;
170import android.util.AtomicFile;
171import android.util.DisplayMetrics;
172import android.util.EventLog;
173import android.util.ExceptionUtils;
174import android.util.Log;
175import android.util.LogPrinter;
176import android.util.MathUtils;
177import android.util.PrintStreamPrinter;
178import android.util.Slog;
179import android.util.SparseArray;
180import android.util.SparseBooleanArray;
181import android.util.SparseIntArray;
182import android.util.Xml;
183import android.view.Display;
184
185import dalvik.system.DexFile;
186import dalvik.system.VMRuntime;
187
188import libcore.io.IoUtils;
189import libcore.util.EmptyArray;
190
191import com.android.internal.R;
192import com.android.internal.app.IMediaContainerService;
193import com.android.internal.app.ResolverActivity;
194import com.android.internal.content.NativeLibraryHelper;
195import com.android.internal.content.PackageHelper;
196import com.android.internal.os.IParcelFileDescriptorFactory;
197import com.android.internal.os.SomeArgs;
198import com.android.internal.util.ArrayUtils;
199import com.android.internal.util.FastPrintWriter;
200import com.android.internal.util.FastXmlSerializer;
201import com.android.internal.util.IndentingPrintWriter;
202import com.android.internal.util.Preconditions;
203import com.android.server.EventLogTags;
204import com.android.server.FgThread;
205import com.android.server.IntentResolver;
206import com.android.server.LocalServices;
207import com.android.server.ServiceThread;
208import com.android.server.SystemConfig;
209import com.android.server.Watchdog;
210import com.android.server.pm.Settings.DatabaseVersion;
211import com.android.server.pm.PermissionsState.PermissionState;
212import com.android.server.storage.DeviceStorageMonitorInternal;
213
214import org.xmlpull.v1.XmlPullParser;
215import org.xmlpull.v1.XmlPullParserException;
216import org.xmlpull.v1.XmlSerializer;
217
218import java.io.BufferedInputStream;
219import java.io.BufferedOutputStream;
220import java.io.BufferedReader;
221import java.io.ByteArrayInputStream;
222import java.io.ByteArrayOutputStream;
223import java.io.File;
224import java.io.FileDescriptor;
225import java.io.FileNotFoundException;
226import java.io.FileOutputStream;
227import java.io.FileReader;
228import java.io.FilenameFilter;
229import java.io.IOException;
230import java.io.InputStream;
231import java.io.PrintWriter;
232import java.nio.charset.StandardCharsets;
233import java.security.NoSuchAlgorithmException;
234import java.security.PublicKey;
235import java.security.cert.CertificateEncodingException;
236import java.security.cert.CertificateException;
237import java.text.SimpleDateFormat;
238import java.util.ArrayList;
239import java.util.Arrays;
240import java.util.Collection;
241import java.util.Collections;
242import java.util.Comparator;
243import java.util.Date;
244import java.util.Iterator;
245import java.util.List;
246import java.util.Map;
247import java.util.Objects;
248import java.util.Set;
249import java.util.concurrent.CountDownLatch;
250import java.util.concurrent.TimeUnit;
251import java.util.concurrent.atomic.AtomicBoolean;
252import java.util.concurrent.atomic.AtomicInteger;
253import java.util.concurrent.atomic.AtomicLong;
254
255/**
256 * Keep track of all those .apks everywhere.
257 *
258 * This is very central to the platform's security; please run the unit
259 * tests whenever making modifications here:
260 *
261runtest -c android.content.pm.PackageManagerTests frameworks-core
262 *
263 * {@hide}
264 */
265public class PackageManagerService extends IPackageManager.Stub {
266    static final String TAG = "PackageManager";
267    static final boolean DEBUG_SETTINGS = false;
268    static final boolean DEBUG_PREFERRED = false;
269    static final boolean DEBUG_UPGRADE = false;
270    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
271    private static final boolean DEBUG_BACKUP = true;
272    private static final boolean DEBUG_INSTALL = false;
273    private static final boolean DEBUG_REMOVE = false;
274    private static final boolean DEBUG_BROADCASTS = false;
275    private static final boolean DEBUG_SHOW_INFO = false;
276    private static final boolean DEBUG_PACKAGE_INFO = false;
277    private static final boolean DEBUG_INTENT_MATCHING = false;
278    private static final boolean DEBUG_PACKAGE_SCANNING = false;
279    private static final boolean DEBUG_VERIFY = false;
280    private static final boolean DEBUG_DEXOPT = false;
281    private static final boolean DEBUG_ABI_SELECTION = false;
282
283    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = Build.IS_DEBUGGABLE;
284
285    private static final int RADIO_UID = Process.PHONE_UID;
286    private static final int LOG_UID = Process.LOG_UID;
287    private static final int NFC_UID = Process.NFC_UID;
288    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
289    private static final int SHELL_UID = Process.SHELL_UID;
290
291    // Cap the size of permission trees that 3rd party apps can define
292    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
293
294    // Suffix used during package installation when copying/moving
295    // package apks to install directory.
296    private static final String INSTALL_PACKAGE_SUFFIX = "-";
297
298    static final int SCAN_NO_DEX = 1<<1;
299    static final int SCAN_FORCE_DEX = 1<<2;
300    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
301    static final int SCAN_NEW_INSTALL = 1<<4;
302    static final int SCAN_NO_PATHS = 1<<5;
303    static final int SCAN_UPDATE_TIME = 1<<6;
304    static final int SCAN_DEFER_DEX = 1<<7;
305    static final int SCAN_BOOTING = 1<<8;
306    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
307    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
308    static final int SCAN_REQUIRE_KNOWN = 1<<12;
309    static final int SCAN_MOVE = 1<<13;
310
311    static final int REMOVE_CHATTY = 1<<16;
312
313    private static final int[] EMPTY_INT_ARRAY = new int[0];
314
315    /**
316     * Timeout (in milliseconds) after which the watchdog should declare that
317     * our handler thread is wedged.  The usual default for such things is one
318     * minute but we sometimes do very lengthy I/O operations on this thread,
319     * such as installing multi-gigabyte applications, so ours needs to be longer.
320     */
321    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
322
323    /**
324     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
325     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
326     * settings entry if available, otherwise we use the hardcoded default.  If it's been
327     * more than this long since the last fstrim, we force one during the boot sequence.
328     *
329     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
330     * one gets run at the next available charging+idle time.  This final mandatory
331     * no-fstrim check kicks in only of the other scheduling criteria is never met.
332     */
333    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
334
335    /**
336     * Whether verification is enabled by default.
337     */
338    private static final boolean DEFAULT_VERIFY_ENABLE = true;
339
340    /**
341     * The default maximum time to wait for the verification agent to return in
342     * milliseconds.
343     */
344    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
345
346    /**
347     * The default response for package verification timeout.
348     *
349     * This can be either PackageManager.VERIFICATION_ALLOW or
350     * PackageManager.VERIFICATION_REJECT.
351     */
352    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
353
354    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
355
356    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
357            DEFAULT_CONTAINER_PACKAGE,
358            "com.android.defcontainer.DefaultContainerService");
359
360    private static final String KILL_APP_REASON_GIDS_CHANGED =
361            "permission grant or revoke changed gids";
362
363    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
364            "permissions revoked";
365
366    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
367
368    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
369
370    /** Permission grant: not grant the permission. */
371    private static final int GRANT_DENIED = 1;
372
373    /** Permission grant: grant the permission as an install permission. */
374    private static final int GRANT_INSTALL = 2;
375
376    /** Permission grant: grant the permission as an install permission for a legacy app. */
377    private static final int GRANT_INSTALL_LEGACY = 3;
378
379    /** Permission grant: grant the permission as a runtime one. */
380    private static final int GRANT_RUNTIME = 4;
381
382    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
383    private static final int GRANT_UPGRADE = 5;
384
385    final ServiceThread mHandlerThread;
386
387    final PackageHandler mHandler;
388
389    /**
390     * Messages for {@link #mHandler} that need to wait for system ready before
391     * being dispatched.
392     */
393    private ArrayList<Message> mPostSystemReadyMessages;
394
395    final int mSdkVersion = Build.VERSION.SDK_INT;
396
397    final Context mContext;
398    final boolean mFactoryTest;
399    final boolean mOnlyCore;
400    final boolean mLazyDexOpt;
401    final long mDexOptLRUThresholdInMills;
402    final DisplayMetrics mMetrics;
403    final int mDefParseFlags;
404    final String[] mSeparateProcesses;
405    final boolean mIsUpgrade;
406
407    // This is where all application persistent data goes.
408    final File mAppDataDir;
409
410    // This is where all application persistent data goes for secondary users.
411    final File mUserAppDataDir;
412
413    /** The location for ASEC container files on internal storage. */
414    final String mAsecInternalPath;
415
416    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
417    // LOCK HELD.  Can be called with mInstallLock held.
418    final Installer mInstaller;
419
420    /** Directory where installed third-party apps stored */
421    final File mAppInstallDir;
422
423    /**
424     * Directory to which applications installed internally have their
425     * 32 bit native libraries copied.
426     */
427    private File mAppLib32InstallDir;
428
429    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
430    // apps.
431    final File mDrmAppPrivateInstallDir;
432
433    // ----------------------------------------------------------------
434
435    // Lock for state used when installing and doing other long running
436    // operations.  Methods that must be called with this lock held have
437    // the suffix "LI".
438    final Object mInstallLock = new Object();
439
440    // ----------------------------------------------------------------
441
442    // Keys are String (package name), values are Package.  This also serves
443    // as the lock for the global state.  Methods that must be called with
444    // this lock held have the prefix "LP".
445    final ArrayMap<String, PackageParser.Package> mPackages =
446            new ArrayMap<String, PackageParser.Package>();
447
448    // Tracks available target package names -> overlay package paths.
449    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
450        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
451
452    final Settings mSettings;
453    boolean mRestoredSettings;
454
455    // System configuration read by SystemConfig.
456    final int[] mGlobalGids;
457    final SparseArray<ArraySet<String>> mSystemPermissions;
458    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
459
460    // If mac_permissions.xml was found for seinfo labeling.
461    boolean mFoundPolicyFile;
462
463    // If a recursive restorecon of /data/data/<pkg> is needed.
464    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
465
466    public static final class SharedLibraryEntry {
467        public final String path;
468        public final String apk;
469
470        SharedLibraryEntry(String _path, String _apk) {
471            path = _path;
472            apk = _apk;
473        }
474    }
475
476    // Currently known shared libraries.
477    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
478            new ArrayMap<String, SharedLibraryEntry>();
479
480    // All available activities, for your resolving pleasure.
481    final ActivityIntentResolver mActivities =
482            new ActivityIntentResolver();
483
484    // All available receivers, for your resolving pleasure.
485    final ActivityIntentResolver mReceivers =
486            new ActivityIntentResolver();
487
488    // All available services, for your resolving pleasure.
489    final ServiceIntentResolver mServices = new ServiceIntentResolver();
490
491    // All available providers, for your resolving pleasure.
492    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
493
494    // Mapping from provider base names (first directory in content URI codePath)
495    // to the provider information.
496    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
497            new ArrayMap<String, PackageParser.Provider>();
498
499    // Mapping from instrumentation class names to info about them.
500    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
501            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
502
503    // Mapping from permission names to info about them.
504    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
505            new ArrayMap<String, PackageParser.PermissionGroup>();
506
507    // Packages whose data we have transfered into another package, thus
508    // should no longer exist.
509    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
510
511    // Broadcast actions that are only available to the system.
512    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
513
514    /** List of packages waiting for verification. */
515    final SparseArray<PackageVerificationState> mPendingVerification
516            = new SparseArray<PackageVerificationState>();
517
518    /** Set of packages associated with each app op permission. */
519    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
520
521    final PackageInstallerService mInstallerService;
522
523    private final PackageDexOptimizer mPackageDexOptimizer;
524
525    private AtomicInteger mNextMoveId = new AtomicInteger();
526    private final MoveCallbacks mMoveCallbacks;
527
528    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
529
530    // Cache of users who need badging.
531    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
532
533    /** Token for keys in mPendingVerification. */
534    private int mPendingVerificationToken = 0;
535
536    volatile boolean mSystemReady;
537    volatile boolean mSafeMode;
538    volatile boolean mHasSystemUidErrors;
539
540    ApplicationInfo mAndroidApplication;
541    final ActivityInfo mResolveActivity = new ActivityInfo();
542    final ResolveInfo mResolveInfo = new ResolveInfo();
543    ComponentName mResolveComponentName;
544    PackageParser.Package mPlatformPackage;
545    ComponentName mCustomResolverComponentName;
546
547    boolean mResolverReplaced = false;
548
549    private final ComponentName mIntentFilterVerifierComponent;
550    private int mIntentFilterVerificationToken = 0;
551
552    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
553            = new SparseArray<IntentFilterVerificationState>();
554
555    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
556            new DefaultPermissionGrantPolicy(this);
557
558    private static class IFVerificationParams {
559        PackageParser.Package pkg;
560        boolean replacing;
561        int userId;
562        int verifierUid;
563
564        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
565                int _userId, int _verifierUid) {
566            pkg = _pkg;
567            replacing = _replacing;
568            userId = _userId;
569            replacing = _replacing;
570            verifierUid = _verifierUid;
571        }
572    }
573
574    private interface IntentFilterVerifier<T extends IntentFilter> {
575        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
576                                               T filter, String packageName);
577        void startVerifications(int userId);
578        void receiveVerificationResponse(int verificationId);
579    }
580
581    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
582        private Context mContext;
583        private ComponentName mIntentFilterVerifierComponent;
584        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
585
586        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
587            mContext = context;
588            mIntentFilterVerifierComponent = verifierComponent;
589        }
590
591        private String getDefaultScheme() {
592            return IntentFilter.SCHEME_HTTPS;
593        }
594
595        @Override
596        public void startVerifications(int userId) {
597            // Launch verifications requests
598            int count = mCurrentIntentFilterVerifications.size();
599            for (int n=0; n<count; n++) {
600                int verificationId = mCurrentIntentFilterVerifications.get(n);
601                final IntentFilterVerificationState ivs =
602                        mIntentFilterVerificationStates.get(verificationId);
603
604                String packageName = ivs.getPackageName();
605
606                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
607                final int filterCount = filters.size();
608                ArraySet<String> domainsSet = new ArraySet<>();
609                for (int m=0; m<filterCount; m++) {
610                    PackageParser.ActivityIntentInfo filter = filters.get(m);
611                    domainsSet.addAll(filter.getHostsList());
612                }
613                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
614                synchronized (mPackages) {
615                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
616                            packageName, domainsList) != null) {
617                        scheduleWriteSettingsLocked();
618                    }
619                }
620                sendVerificationRequest(userId, verificationId, ivs);
621            }
622            mCurrentIntentFilterVerifications.clear();
623        }
624
625        private void sendVerificationRequest(int userId, int verificationId,
626                IntentFilterVerificationState ivs) {
627
628            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
629            verificationIntent.putExtra(
630                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
631                    verificationId);
632            verificationIntent.putExtra(
633                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
634                    getDefaultScheme());
635            verificationIntent.putExtra(
636                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
637                    ivs.getHostsString());
638            verificationIntent.putExtra(
639                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
640                    ivs.getPackageName());
641            verificationIntent.setComponent(mIntentFilterVerifierComponent);
642            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
643
644            UserHandle user = new UserHandle(userId);
645            mContext.sendBroadcastAsUser(verificationIntent, user);
646            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
647                    "Sending IntentFilter verification broadcast");
648        }
649
650        public void receiveVerificationResponse(int verificationId) {
651            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
652
653            final boolean verified = ivs.isVerified();
654
655            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
656            final int count = filters.size();
657            if (DEBUG_DOMAIN_VERIFICATION) {
658                Slog.i(TAG, "Received verification response " + verificationId
659                        + " for " + count + " filters, verified=" + verified);
660            }
661            for (int n=0; n<count; n++) {
662                PackageParser.ActivityIntentInfo filter = filters.get(n);
663                filter.setVerified(verified);
664
665                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
666                        + " verified with result:" + verified + " and hosts:"
667                        + ivs.getHostsString());
668            }
669
670            mIntentFilterVerificationStates.remove(verificationId);
671
672            final String packageName = ivs.getPackageName();
673            IntentFilterVerificationInfo ivi = null;
674
675            synchronized (mPackages) {
676                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
677            }
678            if (ivi == null) {
679                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
680                        + verificationId + " packageName:" + packageName);
681                return;
682            }
683            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
684                    "Updating IntentFilterVerificationInfo for verificationId:" + verificationId);
685
686            synchronized (mPackages) {
687                if (verified) {
688                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
689                } else {
690                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
691                }
692                scheduleWriteSettingsLocked();
693
694                final int userId = ivs.getUserId();
695                if (userId != UserHandle.USER_ALL) {
696                    final int userStatus =
697                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
698
699                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
700                    boolean needUpdate = false;
701
702                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
703                    // already been set by the User thru the Disambiguation dialog
704                    switch (userStatus) {
705                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
706                            if (verified) {
707                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
708                            } else {
709                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
710                            }
711                            needUpdate = true;
712                            break;
713
714                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
715                            if (verified) {
716                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
717                                needUpdate = true;
718                            }
719                            break;
720
721                        default:
722                            // Nothing to do
723                    }
724
725                    if (needUpdate) {
726                        mSettings.updateIntentFilterVerificationStatusLPw(
727                                packageName, updatedStatus, userId);
728                        scheduleWritePackageRestrictionsLocked(userId);
729                    }
730                }
731            }
732        }
733
734        @Override
735        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
736                    ActivityIntentInfo filter, String packageName) {
737            if (!hasValidDomains(filter)) {
738                return false;
739            }
740            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
741            if (ivs == null) {
742                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
743                        packageName);
744            }
745            if (DEBUG_DOMAIN_VERIFICATION) {
746                Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter);
747            }
748            ivs.addFilter(filter);
749            return true;
750        }
751
752        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
753                int userId, int verificationId, String packageName) {
754            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
755                    verifierUid, userId, packageName);
756            ivs.setPendingState();
757            synchronized (mPackages) {
758                mIntentFilterVerificationStates.append(verificationId, ivs);
759                mCurrentIntentFilterVerifications.add(verificationId);
760            }
761            return ivs;
762        }
763    }
764
765    private static boolean hasValidDomains(ActivityIntentInfo filter) {
766        boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
767                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS);
768        if (!hasHTTPorHTTPS) {
769            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
770                    "IntentFilter does not contain any HTTP or HTTPS data scheme");
771            return false;
772        }
773        return true;
774    }
775
776    private IntentFilterVerifier mIntentFilterVerifier;
777
778    // Set of pending broadcasts for aggregating enable/disable of components.
779    static class PendingPackageBroadcasts {
780        // for each user id, a map of <package name -> components within that package>
781        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
782
783        public PendingPackageBroadcasts() {
784            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
785        }
786
787        public ArrayList<String> get(int userId, String packageName) {
788            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
789            return packages.get(packageName);
790        }
791
792        public void put(int userId, String packageName, ArrayList<String> components) {
793            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
794            packages.put(packageName, components);
795        }
796
797        public void remove(int userId, String packageName) {
798            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
799            if (packages != null) {
800                packages.remove(packageName);
801            }
802        }
803
804        public void remove(int userId) {
805            mUidMap.remove(userId);
806        }
807
808        public int userIdCount() {
809            return mUidMap.size();
810        }
811
812        public int userIdAt(int n) {
813            return mUidMap.keyAt(n);
814        }
815
816        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
817            return mUidMap.get(userId);
818        }
819
820        public int size() {
821            // total number of pending broadcast entries across all userIds
822            int num = 0;
823            for (int i = 0; i< mUidMap.size(); i++) {
824                num += mUidMap.valueAt(i).size();
825            }
826            return num;
827        }
828
829        public void clear() {
830            mUidMap.clear();
831        }
832
833        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
834            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
835            if (map == null) {
836                map = new ArrayMap<String, ArrayList<String>>();
837                mUidMap.put(userId, map);
838            }
839            return map;
840        }
841    }
842    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
843
844    // Service Connection to remote media container service to copy
845    // package uri's from external media onto secure containers
846    // or internal storage.
847    private IMediaContainerService mContainerService = null;
848
849    static final int SEND_PENDING_BROADCAST = 1;
850    static final int MCS_BOUND = 3;
851    static final int END_COPY = 4;
852    static final int INIT_COPY = 5;
853    static final int MCS_UNBIND = 6;
854    static final int START_CLEANING_PACKAGE = 7;
855    static final int FIND_INSTALL_LOC = 8;
856    static final int POST_INSTALL = 9;
857    static final int MCS_RECONNECT = 10;
858    static final int MCS_GIVE_UP = 11;
859    static final int UPDATED_MEDIA_STATUS = 12;
860    static final int WRITE_SETTINGS = 13;
861    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
862    static final int PACKAGE_VERIFIED = 15;
863    static final int CHECK_PENDING_VERIFICATION = 16;
864    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
865    static final int INTENT_FILTER_VERIFIED = 18;
866
867    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
868
869    // Delay time in millisecs
870    static final int BROADCAST_DELAY = 10 * 1000;
871
872    static UserManagerService sUserManager;
873
874    // Stores a list of users whose package restrictions file needs to be updated
875    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
876
877    final private DefaultContainerConnection mDefContainerConn =
878            new DefaultContainerConnection();
879    class DefaultContainerConnection implements ServiceConnection {
880        public void onServiceConnected(ComponentName name, IBinder service) {
881            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
882            IMediaContainerService imcs =
883                IMediaContainerService.Stub.asInterface(service);
884            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
885        }
886
887        public void onServiceDisconnected(ComponentName name) {
888            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
889        }
890    }
891
892    // Recordkeeping of restore-after-install operations that are currently in flight
893    // between the Package Manager and the Backup Manager
894    class PostInstallData {
895        public InstallArgs args;
896        public PackageInstalledInfo res;
897
898        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
899            args = _a;
900            res = _r;
901        }
902    }
903
904    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
905    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
906
907    // XML tags for backup/restore of various bits of state
908    private static final String TAG_PREFERRED_BACKUP = "pa";
909    private static final String TAG_DEFAULT_APPS = "da";
910    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
911
912    private final String mRequiredVerifierPackage;
913
914    private final PackageUsage mPackageUsage = new PackageUsage();
915
916    private class PackageUsage {
917        private static final int WRITE_INTERVAL
918            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
919
920        private final Object mFileLock = new Object();
921        private final AtomicLong mLastWritten = new AtomicLong(0);
922        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
923
924        private boolean mIsHistoricalPackageUsageAvailable = true;
925
926        boolean isHistoricalPackageUsageAvailable() {
927            return mIsHistoricalPackageUsageAvailable;
928        }
929
930        void write(boolean force) {
931            if (force) {
932                writeInternal();
933                return;
934            }
935            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
936                && !DEBUG_DEXOPT) {
937                return;
938            }
939            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
940                new Thread("PackageUsage_DiskWriter") {
941                    @Override
942                    public void run() {
943                        try {
944                            writeInternal();
945                        } finally {
946                            mBackgroundWriteRunning.set(false);
947                        }
948                    }
949                }.start();
950            }
951        }
952
953        private void writeInternal() {
954            synchronized (mPackages) {
955                synchronized (mFileLock) {
956                    AtomicFile file = getFile();
957                    FileOutputStream f = null;
958                    try {
959                        f = file.startWrite();
960                        BufferedOutputStream out = new BufferedOutputStream(f);
961                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
962                        StringBuilder sb = new StringBuilder();
963                        for (PackageParser.Package pkg : mPackages.values()) {
964                            if (pkg.mLastPackageUsageTimeInMills == 0) {
965                                continue;
966                            }
967                            sb.setLength(0);
968                            sb.append(pkg.packageName);
969                            sb.append(' ');
970                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
971                            sb.append('\n');
972                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
973                        }
974                        out.flush();
975                        file.finishWrite(f);
976                    } catch (IOException e) {
977                        if (f != null) {
978                            file.failWrite(f);
979                        }
980                        Log.e(TAG, "Failed to write package usage times", e);
981                    }
982                }
983            }
984            mLastWritten.set(SystemClock.elapsedRealtime());
985        }
986
987        void readLP() {
988            synchronized (mFileLock) {
989                AtomicFile file = getFile();
990                BufferedInputStream in = null;
991                try {
992                    in = new BufferedInputStream(file.openRead());
993                    StringBuffer sb = new StringBuffer();
994                    while (true) {
995                        String packageName = readToken(in, sb, ' ');
996                        if (packageName == null) {
997                            break;
998                        }
999                        String timeInMillisString = readToken(in, sb, '\n');
1000                        if (timeInMillisString == null) {
1001                            throw new IOException("Failed to find last usage time for package "
1002                                                  + packageName);
1003                        }
1004                        PackageParser.Package pkg = mPackages.get(packageName);
1005                        if (pkg == null) {
1006                            continue;
1007                        }
1008                        long timeInMillis;
1009                        try {
1010                            timeInMillis = Long.parseLong(timeInMillisString.toString());
1011                        } catch (NumberFormatException e) {
1012                            throw new IOException("Failed to parse " + timeInMillisString
1013                                                  + " as a long.", e);
1014                        }
1015                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1016                    }
1017                } catch (FileNotFoundException expected) {
1018                    mIsHistoricalPackageUsageAvailable = false;
1019                } catch (IOException e) {
1020                    Log.w(TAG, "Failed to read package usage times", e);
1021                } finally {
1022                    IoUtils.closeQuietly(in);
1023                }
1024            }
1025            mLastWritten.set(SystemClock.elapsedRealtime());
1026        }
1027
1028        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1029                throws IOException {
1030            sb.setLength(0);
1031            while (true) {
1032                int ch = in.read();
1033                if (ch == -1) {
1034                    if (sb.length() == 0) {
1035                        return null;
1036                    }
1037                    throw new IOException("Unexpected EOF");
1038                }
1039                if (ch == endOfToken) {
1040                    return sb.toString();
1041                }
1042                sb.append((char)ch);
1043            }
1044        }
1045
1046        private AtomicFile getFile() {
1047            File dataDir = Environment.getDataDirectory();
1048            File systemDir = new File(dataDir, "system");
1049            File fname = new File(systemDir, "package-usage.list");
1050            return new AtomicFile(fname);
1051        }
1052    }
1053
1054    class PackageHandler extends Handler {
1055        private boolean mBound = false;
1056        final ArrayList<HandlerParams> mPendingInstalls =
1057            new ArrayList<HandlerParams>();
1058
1059        private boolean connectToService() {
1060            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1061                    " DefaultContainerService");
1062            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1063            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1064            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1065                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
1066                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1067                mBound = true;
1068                return true;
1069            }
1070            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1071            return false;
1072        }
1073
1074        private void disconnectService() {
1075            mContainerService = null;
1076            mBound = false;
1077            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1078            mContext.unbindService(mDefContainerConn);
1079            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1080        }
1081
1082        PackageHandler(Looper looper) {
1083            super(looper);
1084        }
1085
1086        public void handleMessage(Message msg) {
1087            try {
1088                doHandleMessage(msg);
1089            } finally {
1090                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1091            }
1092        }
1093
1094        void doHandleMessage(Message msg) {
1095            switch (msg.what) {
1096                case INIT_COPY: {
1097                    HandlerParams params = (HandlerParams) msg.obj;
1098                    int idx = mPendingInstalls.size();
1099                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1100                    // If a bind was already initiated we dont really
1101                    // need to do anything. The pending install
1102                    // will be processed later on.
1103                    if (!mBound) {
1104                        // If this is the only one pending we might
1105                        // have to bind to the service again.
1106                        if (!connectToService()) {
1107                            Slog.e(TAG, "Failed to bind to media container service");
1108                            params.serviceError();
1109                            return;
1110                        } else {
1111                            // Once we bind to the service, the first
1112                            // pending request will be processed.
1113                            mPendingInstalls.add(idx, params);
1114                        }
1115                    } else {
1116                        mPendingInstalls.add(idx, params);
1117                        // Already bound to the service. Just make
1118                        // sure we trigger off processing the first request.
1119                        if (idx == 0) {
1120                            mHandler.sendEmptyMessage(MCS_BOUND);
1121                        }
1122                    }
1123                    break;
1124                }
1125                case MCS_BOUND: {
1126                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1127                    if (msg.obj != null) {
1128                        mContainerService = (IMediaContainerService) msg.obj;
1129                    }
1130                    if (mContainerService == null) {
1131                        if (!mBound) {
1132                            // Something seriously wrong since we are not bound and we are not
1133                            // waiting for connection. Bail out.
1134                            Slog.e(TAG, "Cannot bind to media container service");
1135                            for (HandlerParams params : mPendingInstalls) {
1136                                // Indicate service bind error
1137                                params.serviceError();
1138                            }
1139                            mPendingInstalls.clear();
1140                        } else {
1141                            Slog.w(TAG, "Waiting to connect to media container service");
1142                        }
1143                    } else if (mPendingInstalls.size() > 0) {
1144                        HandlerParams params = mPendingInstalls.get(0);
1145                        if (params != null) {
1146                            if (params.startCopy()) {
1147                                // We are done...  look for more work or to
1148                                // go idle.
1149                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1150                                        "Checking for more work or unbind...");
1151                                // Delete pending install
1152                                if (mPendingInstalls.size() > 0) {
1153                                    mPendingInstalls.remove(0);
1154                                }
1155                                if (mPendingInstalls.size() == 0) {
1156                                    if (mBound) {
1157                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1158                                                "Posting delayed MCS_UNBIND");
1159                                        removeMessages(MCS_UNBIND);
1160                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1161                                        // Unbind after a little delay, to avoid
1162                                        // continual thrashing.
1163                                        sendMessageDelayed(ubmsg, 10000);
1164                                    }
1165                                } else {
1166                                    // There are more pending requests in queue.
1167                                    // Just post MCS_BOUND message to trigger processing
1168                                    // of next pending install.
1169                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1170                                            "Posting MCS_BOUND for next work");
1171                                    mHandler.sendEmptyMessage(MCS_BOUND);
1172                                }
1173                            }
1174                        }
1175                    } else {
1176                        // Should never happen ideally.
1177                        Slog.w(TAG, "Empty queue");
1178                    }
1179                    break;
1180                }
1181                case MCS_RECONNECT: {
1182                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1183                    if (mPendingInstalls.size() > 0) {
1184                        if (mBound) {
1185                            disconnectService();
1186                        }
1187                        if (!connectToService()) {
1188                            Slog.e(TAG, "Failed to bind to media container service");
1189                            for (HandlerParams params : mPendingInstalls) {
1190                                // Indicate service bind error
1191                                params.serviceError();
1192                            }
1193                            mPendingInstalls.clear();
1194                        }
1195                    }
1196                    break;
1197                }
1198                case MCS_UNBIND: {
1199                    // If there is no actual work left, then time to unbind.
1200                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1201
1202                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1203                        if (mBound) {
1204                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1205
1206                            disconnectService();
1207                        }
1208                    } else if (mPendingInstalls.size() > 0) {
1209                        // There are more pending requests in queue.
1210                        // Just post MCS_BOUND message to trigger processing
1211                        // of next pending install.
1212                        mHandler.sendEmptyMessage(MCS_BOUND);
1213                    }
1214
1215                    break;
1216                }
1217                case MCS_GIVE_UP: {
1218                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1219                    mPendingInstalls.remove(0);
1220                    break;
1221                }
1222                case SEND_PENDING_BROADCAST: {
1223                    String packages[];
1224                    ArrayList<String> components[];
1225                    int size = 0;
1226                    int uids[];
1227                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1228                    synchronized (mPackages) {
1229                        if (mPendingBroadcasts == null) {
1230                            return;
1231                        }
1232                        size = mPendingBroadcasts.size();
1233                        if (size <= 0) {
1234                            // Nothing to be done. Just return
1235                            return;
1236                        }
1237                        packages = new String[size];
1238                        components = new ArrayList[size];
1239                        uids = new int[size];
1240                        int i = 0;  // filling out the above arrays
1241
1242                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1243                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1244                            Iterator<Map.Entry<String, ArrayList<String>>> it
1245                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1246                                            .entrySet().iterator();
1247                            while (it.hasNext() && i < size) {
1248                                Map.Entry<String, ArrayList<String>> ent = it.next();
1249                                packages[i] = ent.getKey();
1250                                components[i] = ent.getValue();
1251                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1252                                uids[i] = (ps != null)
1253                                        ? UserHandle.getUid(packageUserId, ps.appId)
1254                                        : -1;
1255                                i++;
1256                            }
1257                        }
1258                        size = i;
1259                        mPendingBroadcasts.clear();
1260                    }
1261                    // Send broadcasts
1262                    for (int i = 0; i < size; i++) {
1263                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1264                    }
1265                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1266                    break;
1267                }
1268                case START_CLEANING_PACKAGE: {
1269                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1270                    final String packageName = (String)msg.obj;
1271                    final int userId = msg.arg1;
1272                    final boolean andCode = msg.arg2 != 0;
1273                    synchronized (mPackages) {
1274                        if (userId == UserHandle.USER_ALL) {
1275                            int[] users = sUserManager.getUserIds();
1276                            for (int user : users) {
1277                                mSettings.addPackageToCleanLPw(
1278                                        new PackageCleanItem(user, packageName, andCode));
1279                            }
1280                        } else {
1281                            mSettings.addPackageToCleanLPw(
1282                                    new PackageCleanItem(userId, packageName, andCode));
1283                        }
1284                    }
1285                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1286                    startCleaningPackages();
1287                } break;
1288                case POST_INSTALL: {
1289                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1290                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1291                    mRunningInstalls.delete(msg.arg1);
1292                    boolean deleteOld = false;
1293
1294                    if (data != null) {
1295                        InstallArgs args = data.args;
1296                        PackageInstalledInfo res = data.res;
1297
1298                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1299                            res.removedInfo.sendBroadcast(false, true, false);
1300                            Bundle extras = new Bundle(1);
1301                            extras.putInt(Intent.EXTRA_UID, res.uid);
1302
1303                            // Now that we successfully installed the package, grant runtime
1304                            // permissions if requested before broadcasting the install.
1305                            if ((args.installFlags
1306                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) {
1307                                grantRequestedRuntimePermissions(res.pkg,
1308                                        args.user.getIdentifier());
1309                            }
1310
1311                            // Determine the set of users who are adding this
1312                            // package for the first time vs. those who are seeing
1313                            // an update.
1314                            int[] firstUsers;
1315                            int[] updateUsers = new int[0];
1316                            if (res.origUsers == null || res.origUsers.length == 0) {
1317                                firstUsers = res.newUsers;
1318                            } else {
1319                                firstUsers = new int[0];
1320                                for (int i=0; i<res.newUsers.length; i++) {
1321                                    int user = res.newUsers[i];
1322                                    boolean isNew = true;
1323                                    for (int j=0; j<res.origUsers.length; j++) {
1324                                        if (res.origUsers[j] == user) {
1325                                            isNew = false;
1326                                            break;
1327                                        }
1328                                    }
1329                                    if (isNew) {
1330                                        int[] newFirst = new int[firstUsers.length+1];
1331                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1332                                                firstUsers.length);
1333                                        newFirst[firstUsers.length] = user;
1334                                        firstUsers = newFirst;
1335                                    } else {
1336                                        int[] newUpdate = new int[updateUsers.length+1];
1337                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1338                                                updateUsers.length);
1339                                        newUpdate[updateUsers.length] = user;
1340                                        updateUsers = newUpdate;
1341                                    }
1342                                }
1343                            }
1344                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1345                                    res.pkg.applicationInfo.packageName,
1346                                    extras, null, null, firstUsers);
1347                            final boolean update = res.removedInfo.removedPackage != null;
1348                            if (update) {
1349                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1350                            }
1351                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1352                                    res.pkg.applicationInfo.packageName,
1353                                    extras, null, null, updateUsers);
1354                            if (update) {
1355                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1356                                        res.pkg.applicationInfo.packageName,
1357                                        extras, null, null, updateUsers);
1358                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1359                                        null, null,
1360                                        res.pkg.applicationInfo.packageName, null, updateUsers);
1361
1362                                // treat asec-hosted packages like removable media on upgrade
1363                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1364                                    if (DEBUG_INSTALL) {
1365                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1366                                                + " is ASEC-hosted -> AVAILABLE");
1367                                    }
1368                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1369                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1370                                    pkgList.add(res.pkg.applicationInfo.packageName);
1371                                    sendResourcesChangedBroadcast(true, true,
1372                                            pkgList,uidArray, null);
1373                                }
1374                            }
1375                            if (res.removedInfo.args != null) {
1376                                // Remove the replaced package's older resources safely now
1377                                deleteOld = true;
1378                            }
1379
1380                            // Log current value of "unknown sources" setting
1381                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1382                                getUnknownSourcesSettings());
1383                        }
1384                        // Force a gc to clear up things
1385                        Runtime.getRuntime().gc();
1386                        // We delete after a gc for applications  on sdcard.
1387                        if (deleteOld) {
1388                            synchronized (mInstallLock) {
1389                                res.removedInfo.args.doPostDeleteLI(true);
1390                            }
1391                        }
1392                        if (args.observer != null) {
1393                            try {
1394                                Bundle extras = extrasForInstallResult(res);
1395                                args.observer.onPackageInstalled(res.name, res.returnCode,
1396                                        res.returnMsg, extras);
1397                            } catch (RemoteException e) {
1398                                Slog.i(TAG, "Observer no longer exists.");
1399                            }
1400                        }
1401                    } else {
1402                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1403                    }
1404                } break;
1405                case UPDATED_MEDIA_STATUS: {
1406                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1407                    boolean reportStatus = msg.arg1 == 1;
1408                    boolean doGc = msg.arg2 == 1;
1409                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1410                    if (doGc) {
1411                        // Force a gc to clear up stale containers.
1412                        Runtime.getRuntime().gc();
1413                    }
1414                    if (msg.obj != null) {
1415                        @SuppressWarnings("unchecked")
1416                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1417                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1418                        // Unload containers
1419                        unloadAllContainers(args);
1420                    }
1421                    if (reportStatus) {
1422                        try {
1423                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1424                            PackageHelper.getMountService().finishMediaUpdate();
1425                        } catch (RemoteException e) {
1426                            Log.e(TAG, "MountService not running?");
1427                        }
1428                    }
1429                } break;
1430                case WRITE_SETTINGS: {
1431                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1432                    synchronized (mPackages) {
1433                        removeMessages(WRITE_SETTINGS);
1434                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1435                        mSettings.writeLPr();
1436                        mDirtyUsers.clear();
1437                    }
1438                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1439                } break;
1440                case WRITE_PACKAGE_RESTRICTIONS: {
1441                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1442                    synchronized (mPackages) {
1443                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1444                        for (int userId : mDirtyUsers) {
1445                            mSettings.writePackageRestrictionsLPr(userId);
1446                        }
1447                        mDirtyUsers.clear();
1448                    }
1449                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1450                } break;
1451                case CHECK_PENDING_VERIFICATION: {
1452                    final int verificationId = msg.arg1;
1453                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1454
1455                    if ((state != null) && !state.timeoutExtended()) {
1456                        final InstallArgs args = state.getInstallArgs();
1457                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1458
1459                        Slog.i(TAG, "Verification timed out for " + originUri);
1460                        mPendingVerification.remove(verificationId);
1461
1462                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1463
1464                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1465                            Slog.i(TAG, "Continuing with installation of " + originUri);
1466                            state.setVerifierResponse(Binder.getCallingUid(),
1467                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1468                            broadcastPackageVerified(verificationId, originUri,
1469                                    PackageManager.VERIFICATION_ALLOW,
1470                                    state.getInstallArgs().getUser());
1471                            try {
1472                                ret = args.copyApk(mContainerService, true);
1473                            } catch (RemoteException e) {
1474                                Slog.e(TAG, "Could not contact the ContainerService");
1475                            }
1476                        } else {
1477                            broadcastPackageVerified(verificationId, originUri,
1478                                    PackageManager.VERIFICATION_REJECT,
1479                                    state.getInstallArgs().getUser());
1480                        }
1481
1482                        processPendingInstall(args, ret);
1483                        mHandler.sendEmptyMessage(MCS_UNBIND);
1484                    }
1485                    break;
1486                }
1487                case PACKAGE_VERIFIED: {
1488                    final int verificationId = msg.arg1;
1489
1490                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1491                    if (state == null) {
1492                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1493                        break;
1494                    }
1495
1496                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1497
1498                    state.setVerifierResponse(response.callerUid, response.code);
1499
1500                    if (state.isVerificationComplete()) {
1501                        mPendingVerification.remove(verificationId);
1502
1503                        final InstallArgs args = state.getInstallArgs();
1504                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1505
1506                        int ret;
1507                        if (state.isInstallAllowed()) {
1508                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1509                            broadcastPackageVerified(verificationId, originUri,
1510                                    response.code, state.getInstallArgs().getUser());
1511                            try {
1512                                ret = args.copyApk(mContainerService, true);
1513                            } catch (RemoteException e) {
1514                                Slog.e(TAG, "Could not contact the ContainerService");
1515                            }
1516                        } else {
1517                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1518                        }
1519
1520                        processPendingInstall(args, ret);
1521
1522                        mHandler.sendEmptyMessage(MCS_UNBIND);
1523                    }
1524
1525                    break;
1526                }
1527                case START_INTENT_FILTER_VERIFICATIONS: {
1528                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1529                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1530                            params.replacing, params.pkg);
1531                    break;
1532                }
1533                case INTENT_FILTER_VERIFIED: {
1534                    final int verificationId = msg.arg1;
1535
1536                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1537                            verificationId);
1538                    if (state == null) {
1539                        Slog.w(TAG, "Invalid IntentFilter verification token "
1540                                + verificationId + " received");
1541                        break;
1542                    }
1543
1544                    final int userId = state.getUserId();
1545
1546                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1547                            "Processing IntentFilter verification with token:"
1548                            + verificationId + " and userId:" + userId);
1549
1550                    final IntentFilterVerificationResponse response =
1551                            (IntentFilterVerificationResponse) msg.obj;
1552
1553                    state.setVerifierResponse(response.callerUid, response.code);
1554
1555                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1556                            "IntentFilter verification with token:" + verificationId
1557                            + " and userId:" + userId
1558                            + " is settings verifier response with response code:"
1559                            + response.code);
1560
1561                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1562                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1563                                + response.getFailedDomainsString());
1564                    }
1565
1566                    if (state.isVerificationComplete()) {
1567                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1568                    } else {
1569                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1570                                "IntentFilter verification with token:" + verificationId
1571                                + " was not said to be complete");
1572                    }
1573
1574                    break;
1575                }
1576            }
1577        }
1578    }
1579
1580    private StorageEventListener mStorageListener = new StorageEventListener() {
1581        @Override
1582        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1583            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1584                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1585                    // TODO: ensure that private directories exist for all active users
1586                    // TODO: remove user data whose serial number doesn't match
1587                    loadPrivatePackages(vol);
1588                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1589                    unloadPrivatePackages(vol);
1590                }
1591            }
1592
1593            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1594                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1595                    updateExternalMediaStatus(true, false);
1596                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1597                    updateExternalMediaStatus(false, false);
1598                }
1599            }
1600        }
1601
1602        @Override
1603        public void onVolumeForgotten(String fsUuid) {
1604            // TODO: remove all packages hosted on this uuid
1605        }
1606    };
1607
1608    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) {
1609        if (userId >= UserHandle.USER_OWNER) {
1610            grantRequestedRuntimePermissionsForUser(pkg, userId);
1611        } else if (userId == UserHandle.USER_ALL) {
1612            for (int someUserId : UserManagerService.getInstance().getUserIds()) {
1613                grantRequestedRuntimePermissionsForUser(pkg, someUserId);
1614            }
1615        }
1616
1617        // We could have touched GID membership, so flush out packages.list
1618        synchronized (mPackages) {
1619            mSettings.writePackageListLPr();
1620        }
1621    }
1622
1623    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) {
1624        SettingBase sb = (SettingBase) pkg.mExtras;
1625        if (sb == null) {
1626            return;
1627        }
1628
1629        PermissionsState permissionsState = sb.getPermissionsState();
1630
1631        for (String permission : pkg.requestedPermissions) {
1632            BasePermission bp = mSettings.mPermissions.get(permission);
1633            if (bp != null && bp.isRuntime()) {
1634                permissionsState.grantRuntimePermission(bp, userId);
1635            }
1636        }
1637    }
1638
1639    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1640        Bundle extras = null;
1641        switch (res.returnCode) {
1642            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1643                extras = new Bundle();
1644                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1645                        res.origPermission);
1646                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1647                        res.origPackage);
1648                break;
1649            }
1650            case PackageManager.INSTALL_SUCCEEDED: {
1651                extras = new Bundle();
1652                extras.putBoolean(Intent.EXTRA_REPLACING,
1653                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1654                break;
1655            }
1656        }
1657        return extras;
1658    }
1659
1660    void scheduleWriteSettingsLocked() {
1661        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1662            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1663        }
1664    }
1665
1666    void scheduleWritePackageRestrictionsLocked(int userId) {
1667        if (!sUserManager.exists(userId)) return;
1668        mDirtyUsers.add(userId);
1669        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1670            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1671        }
1672    }
1673
1674    public static PackageManagerService main(Context context, Installer installer,
1675            boolean factoryTest, boolean onlyCore) {
1676        PackageManagerService m = new PackageManagerService(context, installer,
1677                factoryTest, onlyCore);
1678        ServiceManager.addService("package", m);
1679        return m;
1680    }
1681
1682    static String[] splitString(String str, char sep) {
1683        int count = 1;
1684        int i = 0;
1685        while ((i=str.indexOf(sep, i)) >= 0) {
1686            count++;
1687            i++;
1688        }
1689
1690        String[] res = new String[count];
1691        i=0;
1692        count = 0;
1693        int lastI=0;
1694        while ((i=str.indexOf(sep, i)) >= 0) {
1695            res[count] = str.substring(lastI, i);
1696            count++;
1697            i++;
1698            lastI = i;
1699        }
1700        res[count] = str.substring(lastI, str.length());
1701        return res;
1702    }
1703
1704    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1705        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1706                Context.DISPLAY_SERVICE);
1707        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1708    }
1709
1710    public PackageManagerService(Context context, Installer installer,
1711            boolean factoryTest, boolean onlyCore) {
1712        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1713                SystemClock.uptimeMillis());
1714
1715        if (mSdkVersion <= 0) {
1716            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1717        }
1718
1719        mContext = context;
1720        mFactoryTest = factoryTest;
1721        mOnlyCore = onlyCore;
1722        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1723        mMetrics = new DisplayMetrics();
1724        mSettings = new Settings(mPackages);
1725        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1726                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1727        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1728                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1729        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1730                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1731        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1732                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1733        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1734                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1735        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1736                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1737
1738        // TODO: add a property to control this?
1739        long dexOptLRUThresholdInMinutes;
1740        if (mLazyDexOpt) {
1741            dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1742        } else {
1743            dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1744        }
1745        mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1746
1747        String separateProcesses = SystemProperties.get("debug.separate_processes");
1748        if (separateProcesses != null && separateProcesses.length() > 0) {
1749            if ("*".equals(separateProcesses)) {
1750                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1751                mSeparateProcesses = null;
1752                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1753            } else {
1754                mDefParseFlags = 0;
1755                mSeparateProcesses = separateProcesses.split(",");
1756                Slog.w(TAG, "Running with debug.separate_processes: "
1757                        + separateProcesses);
1758            }
1759        } else {
1760            mDefParseFlags = 0;
1761            mSeparateProcesses = null;
1762        }
1763
1764        mInstaller = installer;
1765        mPackageDexOptimizer = new PackageDexOptimizer(this);
1766        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1767
1768        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1769                FgThread.get().getLooper());
1770
1771        getDefaultDisplayMetrics(context, mMetrics);
1772
1773        SystemConfig systemConfig = SystemConfig.getInstance();
1774        mGlobalGids = systemConfig.getGlobalGids();
1775        mSystemPermissions = systemConfig.getSystemPermissions();
1776        mAvailableFeatures = systemConfig.getAvailableFeatures();
1777
1778        synchronized (mInstallLock) {
1779        // writer
1780        synchronized (mPackages) {
1781            mHandlerThread = new ServiceThread(TAG,
1782                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1783            mHandlerThread.start();
1784            mHandler = new PackageHandler(mHandlerThread.getLooper());
1785            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1786
1787            File dataDir = Environment.getDataDirectory();
1788            mAppDataDir = new File(dataDir, "data");
1789            mAppInstallDir = new File(dataDir, "app");
1790            mAppLib32InstallDir = new File(dataDir, "app-lib");
1791            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1792            mUserAppDataDir = new File(dataDir, "user");
1793            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1794
1795            sUserManager = new UserManagerService(context, this,
1796                    mInstallLock, mPackages);
1797
1798            // Propagate permission configuration in to package manager.
1799            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1800                    = systemConfig.getPermissions();
1801            for (int i=0; i<permConfig.size(); i++) {
1802                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1803                BasePermission bp = mSettings.mPermissions.get(perm.name);
1804                if (bp == null) {
1805                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1806                    mSettings.mPermissions.put(perm.name, bp);
1807                }
1808                if (perm.gids != null) {
1809                    bp.setGids(perm.gids, perm.perUser);
1810                }
1811            }
1812
1813            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1814            for (int i=0; i<libConfig.size(); i++) {
1815                mSharedLibraries.put(libConfig.keyAt(i),
1816                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1817            }
1818
1819            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1820
1821            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1822                    mSdkVersion, mOnlyCore);
1823
1824            String customResolverActivity = Resources.getSystem().getString(
1825                    R.string.config_customResolverActivity);
1826            if (TextUtils.isEmpty(customResolverActivity)) {
1827                customResolverActivity = null;
1828            } else {
1829                mCustomResolverComponentName = ComponentName.unflattenFromString(
1830                        customResolverActivity);
1831            }
1832
1833            long startTime = SystemClock.uptimeMillis();
1834
1835            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1836                    startTime);
1837
1838            // Set flag to monitor and not change apk file paths when
1839            // scanning install directories.
1840            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
1841
1842            final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1843
1844            /**
1845             * Add everything in the in the boot class path to the
1846             * list of process files because dexopt will have been run
1847             * if necessary during zygote startup.
1848             */
1849            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1850            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1851
1852            if (bootClassPath != null) {
1853                String[] bootClassPathElements = splitString(bootClassPath, ':');
1854                for (String element : bootClassPathElements) {
1855                    alreadyDexOpted.add(element);
1856                }
1857            } else {
1858                Slog.w(TAG, "No BOOTCLASSPATH found!");
1859            }
1860
1861            if (systemServerClassPath != null) {
1862                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1863                for (String element : systemServerClassPathElements) {
1864                    alreadyDexOpted.add(element);
1865                }
1866            } else {
1867                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1868            }
1869
1870            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
1871            final String[] dexCodeInstructionSets =
1872                    getDexCodeInstructionSets(
1873                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
1874
1875            /**
1876             * Ensure all external libraries have had dexopt run on them.
1877             */
1878            if (mSharedLibraries.size() > 0) {
1879                // NOTE: For now, we're compiling these system "shared libraries"
1880                // (and framework jars) into all available architectures. It's possible
1881                // to compile them only when we come across an app that uses them (there's
1882                // already logic for that in scanPackageLI) but that adds some complexity.
1883                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1884                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1885                        final String lib = libEntry.path;
1886                        if (lib == null) {
1887                            continue;
1888                        }
1889
1890                        try {
1891                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
1892                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1893                                alreadyDexOpted.add(lib);
1894                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1895                            }
1896                        } catch (FileNotFoundException e) {
1897                            Slog.w(TAG, "Library not found: " + lib);
1898                        } catch (IOException e) {
1899                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1900                                    + e.getMessage());
1901                        }
1902                    }
1903                }
1904            }
1905
1906            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1907
1908            // Gross hack for now: we know this file doesn't contain any
1909            // code, so don't dexopt it to avoid the resulting log spew.
1910            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1911
1912            // Gross hack for now: we know this file is only part of
1913            // the boot class path for art, so don't dexopt it to
1914            // avoid the resulting log spew.
1915            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1916
1917            /**
1918             * There are a number of commands implemented in Java, which
1919             * we currently need to do the dexopt on so that they can be
1920             * run from a non-root shell.
1921             */
1922            String[] frameworkFiles = frameworkDir.list();
1923            if (frameworkFiles != null) {
1924                // TODO: We could compile these only for the most preferred ABI. We should
1925                // first double check that the dex files for these commands are not referenced
1926                // by other system apps.
1927                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1928                    for (int i=0; i<frameworkFiles.length; i++) {
1929                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1930                        String path = libPath.getPath();
1931                        // Skip the file if we already did it.
1932                        if (alreadyDexOpted.contains(path)) {
1933                            continue;
1934                        }
1935                        // Skip the file if it is not a type we want to dexopt.
1936                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1937                            continue;
1938                        }
1939                        try {
1940                            int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false);
1941                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1942                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1943                            }
1944                        } catch (FileNotFoundException e) {
1945                            Slog.w(TAG, "Jar not found: " + path);
1946                        } catch (IOException e) {
1947                            Slog.w(TAG, "Exception reading jar: " + path, e);
1948                        }
1949                    }
1950                }
1951            }
1952
1953            // Collect vendor overlay packages.
1954            // (Do this before scanning any apps.)
1955            // For security and version matching reason, only consider
1956            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1957            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1958            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1959                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
1960
1961            // Find base frameworks (resource packages without code).
1962            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1963                    | PackageParser.PARSE_IS_SYSTEM_DIR
1964                    | PackageParser.PARSE_IS_PRIVILEGED,
1965                    scanFlags | SCAN_NO_DEX, 0);
1966
1967            // Collected privileged system packages.
1968            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1969            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1970                    | PackageParser.PARSE_IS_SYSTEM_DIR
1971                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
1972
1973            // Collect ordinary system packages.
1974            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
1975            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1976                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1977
1978            // Collect all vendor packages.
1979            File vendorAppDir = new File("/vendor/app");
1980            try {
1981                vendorAppDir = vendorAppDir.getCanonicalFile();
1982            } catch (IOException e) {
1983                // failed to look up canonical path, continue with original one
1984            }
1985            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1986                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1987
1988            // Collect all OEM packages.
1989            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
1990            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
1991                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1992
1993            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1994            mInstaller.moveFiles();
1995
1996            // Prune any system packages that no longer exist.
1997            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
1998            final ArrayMap<String, File> expectingBetter = new ArrayMap<>();
1999            if (!mOnlyCore) {
2000                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2001                while (psit.hasNext()) {
2002                    PackageSetting ps = psit.next();
2003
2004                    /*
2005                     * If this is not a system app, it can't be a
2006                     * disable system app.
2007                     */
2008                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2009                        continue;
2010                    }
2011
2012                    /*
2013                     * If the package is scanned, it's not erased.
2014                     */
2015                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2016                    if (scannedPkg != null) {
2017                        /*
2018                         * If the system app is both scanned and in the
2019                         * disabled packages list, then it must have been
2020                         * added via OTA. Remove it from the currently
2021                         * scanned package so the previously user-installed
2022                         * application can be scanned.
2023                         */
2024                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2025                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2026                                    + ps.name + "; removing system app.  Last known codePath="
2027                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2028                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2029                                    + scannedPkg.mVersionCode);
2030                            removePackageLI(ps, true);
2031                            expectingBetter.put(ps.name, ps.codePath);
2032                        }
2033
2034                        continue;
2035                    }
2036
2037                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2038                        psit.remove();
2039                        logCriticalInfo(Log.WARN, "System package " + ps.name
2040                                + " no longer exists; wiping its data");
2041                        removeDataDirsLI(null, ps.name);
2042                    } else {
2043                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2044                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2045                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2046                        }
2047                    }
2048                }
2049            }
2050
2051            //look for any incomplete package installations
2052            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2053            //clean up list
2054            for(int i = 0; i < deletePkgsList.size(); i++) {
2055                //clean up here
2056                cleanupInstallFailedPackage(deletePkgsList.get(i));
2057            }
2058            //delete tmp files
2059            deleteTempPackageFiles();
2060
2061            // Remove any shared userIDs that have no associated packages
2062            mSettings.pruneSharedUsersLPw();
2063
2064            if (!mOnlyCore) {
2065                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2066                        SystemClock.uptimeMillis());
2067                scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2068
2069                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2070                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2071
2072                /**
2073                 * Remove disable package settings for any updated system
2074                 * apps that were removed via an OTA. If they're not a
2075                 * previously-updated app, remove them completely.
2076                 * Otherwise, just revoke their system-level permissions.
2077                 */
2078                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2079                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2080                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2081
2082                    String msg;
2083                    if (deletedPkg == null) {
2084                        msg = "Updated system package " + deletedAppName
2085                                + " no longer exists; wiping its data";
2086                        removeDataDirsLI(null, deletedAppName);
2087                    } else {
2088                        msg = "Updated system app + " + deletedAppName
2089                                + " no longer present; removing system privileges for "
2090                                + deletedAppName;
2091
2092                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2093
2094                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2095                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2096                    }
2097                    logCriticalInfo(Log.WARN, msg);
2098                }
2099
2100                /**
2101                 * Make sure all system apps that we expected to appear on
2102                 * the userdata partition actually showed up. If they never
2103                 * appeared, crawl back and revive the system version.
2104                 */
2105                for (int i = 0; i < expectingBetter.size(); i++) {
2106                    final String packageName = expectingBetter.keyAt(i);
2107                    if (!mPackages.containsKey(packageName)) {
2108                        final File scanFile = expectingBetter.valueAt(i);
2109
2110                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2111                                + " but never showed up; reverting to system");
2112
2113                        final int reparseFlags;
2114                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2115                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2116                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2117                                    | PackageParser.PARSE_IS_PRIVILEGED;
2118                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2119                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2120                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2121                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2122                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2123                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2124                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2125                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2126                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2127                        } else {
2128                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2129                            continue;
2130                        }
2131
2132                        mSettings.enableSystemPackageLPw(packageName);
2133
2134                        try {
2135                            scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
2136                        } catch (PackageManagerException e) {
2137                            Slog.e(TAG, "Failed to parse original system package: "
2138                                    + e.getMessage());
2139                        }
2140                    }
2141                }
2142            }
2143
2144            // Now that we know all of the shared libraries, update all clients to have
2145            // the correct library paths.
2146            updateAllSharedLibrariesLPw();
2147
2148            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2149                // NOTE: We ignore potential failures here during a system scan (like
2150                // the rest of the commands above) because there's precious little we
2151                // can do about it. A settings error is reported, though.
2152                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2153                        false /* force dexopt */, false /* defer dexopt */);
2154            }
2155
2156            // Now that we know all the packages we are keeping,
2157            // read and update their last usage times.
2158            mPackageUsage.readLP();
2159
2160            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2161                    SystemClock.uptimeMillis());
2162            Slog.i(TAG, "Time to scan packages: "
2163                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2164                    + " seconds");
2165
2166            // If the platform SDK has changed since the last time we booted,
2167            // we need to re-grant app permission to catch any new ones that
2168            // appear.  This is really a hack, and means that apps can in some
2169            // cases get permissions that the user didn't initially explicitly
2170            // allow...  it would be nice to have some better way to handle
2171            // this situation.
2172            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
2173                    != mSdkVersion;
2174            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
2175                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
2176                    + "; regranting permissions for internal storage");
2177            mSettings.mInternalSdkPlatform = mSdkVersion;
2178
2179            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
2180                    | (regrantPermissions
2181                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
2182                            : 0));
2183
2184            // If this is the first boot, and it is a normal boot, then
2185            // we need to initialize the default preferred apps.
2186            if (!mRestoredSettings && !onlyCore) {
2187                mSettings.readDefaultPreferredAppsLPw(this, 0);
2188            }
2189
2190            // If this is first boot after an OTA, and a normal boot, then
2191            // we need to clear code cache directories.
2192            mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint);
2193            if (mIsUpgrade && !onlyCore) {
2194                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2195                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2196                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2197                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2198                }
2199                mSettings.mFingerprint = Build.FINGERPRINT;
2200            }
2201
2202            primeDomainVerificationsLPw();
2203            checkDefaultBrowser();
2204
2205            // All the changes are done during package scanning.
2206            mSettings.updateInternalDatabaseVersion();
2207
2208            // can downgrade to reader
2209            mSettings.writeLPr();
2210
2211            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2212                    SystemClock.uptimeMillis());
2213
2214            mRequiredVerifierPackage = getRequiredVerifierLPr();
2215
2216            mInstallerService = new PackageInstallerService(context, this);
2217
2218            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2219            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2220                    mIntentFilterVerifierComponent);
2221
2222        } // synchronized (mPackages)
2223        } // synchronized (mInstallLock)
2224
2225        // Now after opening every single application zip, make sure they
2226        // are all flushed.  Not really needed, but keeps things nice and
2227        // tidy.
2228        Runtime.getRuntime().gc();
2229
2230        // Expose private service for system components to use.
2231        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2232    }
2233
2234    @Override
2235    public boolean isFirstBoot() {
2236        return !mRestoredSettings;
2237    }
2238
2239    @Override
2240    public boolean isOnlyCoreApps() {
2241        return mOnlyCore;
2242    }
2243
2244    @Override
2245    public boolean isUpgrade() {
2246        return mIsUpgrade;
2247    }
2248
2249    private String getRequiredVerifierLPr() {
2250        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2251        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2252                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
2253
2254        String requiredVerifier = null;
2255
2256        final int N = receivers.size();
2257        for (int i = 0; i < N; i++) {
2258            final ResolveInfo info = receivers.get(i);
2259
2260            if (info.activityInfo == null) {
2261                continue;
2262            }
2263
2264            final String packageName = info.activityInfo.packageName;
2265
2266            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2267                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2268                continue;
2269            }
2270
2271            if (requiredVerifier != null) {
2272                throw new RuntimeException("There can be only one required verifier");
2273            }
2274
2275            requiredVerifier = packageName;
2276        }
2277
2278        return requiredVerifier;
2279    }
2280
2281    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2282        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2283        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2284                PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */);
2285
2286        ComponentName verifierComponentName = null;
2287
2288        int priority = -1000;
2289        final int N = receivers.size();
2290        for (int i = 0; i < N; i++) {
2291            final ResolveInfo info = receivers.get(i);
2292
2293            if (info.activityInfo == null) {
2294                continue;
2295            }
2296
2297            final String packageName = info.activityInfo.packageName;
2298
2299            final PackageSetting ps = mSettings.mPackages.get(packageName);
2300            if (ps == null) {
2301                continue;
2302            }
2303
2304            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2305                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2306                continue;
2307            }
2308
2309            // Select the IntentFilterVerifier with the highest priority
2310            if (priority < info.priority) {
2311                priority = info.priority;
2312                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2313                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2314                        + verifierComponentName + " with priority: " + info.priority);
2315            }
2316        }
2317
2318        return verifierComponentName;
2319    }
2320
2321    private void primeDomainVerificationsLPw() {
2322        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Start priming domain verifications");
2323        boolean updated = false;
2324        ArraySet<String> allHostsSet = new ArraySet<>();
2325        for (PackageParser.Package pkg : mPackages.values()) {
2326            final String packageName = pkg.packageName;
2327            if (!hasDomainURLs(pkg)) {
2328                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "No priming domain verifications for " +
2329                            "package with no domain URLs: " + packageName);
2330                continue;
2331            }
2332            if (!pkg.isSystemApp()) {
2333                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2334                        "No priming domain verifications for a non system package : " +
2335                                packageName);
2336                continue;
2337            }
2338            for (PackageParser.Activity a : pkg.activities) {
2339                for (ActivityIntentInfo filter : a.intents) {
2340                    if (hasValidDomains(filter)) {
2341                        allHostsSet.addAll(filter.getHostsList());
2342                    }
2343                }
2344            }
2345            if (allHostsSet.size() == 0) {
2346                allHostsSet.add("*");
2347            }
2348            ArrayList<String> allHostsList = new ArrayList<>(allHostsSet);
2349            IntentFilterVerificationInfo ivi =
2350                    mSettings.createIntentFilterVerificationIfNeededLPw(packageName, allHostsList);
2351            if (ivi != null) {
2352                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2353                        "Priming domain verifications for package: " + packageName +
2354                        " with hosts:" + ivi.getDomainsString());
2355                ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
2356                updated = true;
2357            }
2358            else {
2359                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2360                        "No priming domain verifications for package: " + packageName);
2361            }
2362            allHostsSet.clear();
2363        }
2364        if (updated) {
2365            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2366                    "Will need to write primed domain verifications");
2367        }
2368        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "End priming domain verifications");
2369    }
2370
2371    private void checkDefaultBrowser() {
2372        final int myUserId = UserHandle.myUserId();
2373        final String packageName = getDefaultBrowserPackageName(myUserId);
2374        PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2375        if (info == null) {
2376            Slog.w(TAG, "Default browser no longer installed: " + packageName);
2377            setDefaultBrowserPackageName(null, myUserId);
2378        }
2379    }
2380
2381    @Override
2382    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2383            throws RemoteException {
2384        try {
2385            return super.onTransact(code, data, reply, flags);
2386        } catch (RuntimeException e) {
2387            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2388                Slog.wtf(TAG, "Package Manager Crash", e);
2389            }
2390            throw e;
2391        }
2392    }
2393
2394    void cleanupInstallFailedPackage(PackageSetting ps) {
2395        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2396
2397        removeDataDirsLI(ps.volumeUuid, ps.name);
2398        if (ps.codePath != null) {
2399            if (ps.codePath.isDirectory()) {
2400                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2401            } else {
2402                ps.codePath.delete();
2403            }
2404        }
2405        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2406            if (ps.resourcePath.isDirectory()) {
2407                FileUtils.deleteContents(ps.resourcePath);
2408            }
2409            ps.resourcePath.delete();
2410        }
2411        mSettings.removePackageLPw(ps.name);
2412    }
2413
2414    static int[] appendInts(int[] cur, int[] add) {
2415        if (add == null) return cur;
2416        if (cur == null) return add;
2417        final int N = add.length;
2418        for (int i=0; i<N; i++) {
2419            cur = appendInt(cur, add[i]);
2420        }
2421        return cur;
2422    }
2423
2424    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2425        if (!sUserManager.exists(userId)) return null;
2426        final PackageSetting ps = (PackageSetting) p.mExtras;
2427        if (ps == null) {
2428            return null;
2429        }
2430
2431        final PermissionsState permissionsState = ps.getPermissionsState();
2432
2433        final int[] gids = permissionsState.computeGids(userId);
2434        final Set<String> permissions = permissionsState.getPermissions(userId);
2435        final PackageUserState state = ps.readUserState(userId);
2436
2437        return PackageParser.generatePackageInfo(p, gids, flags,
2438                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2439    }
2440
2441    @Override
2442    public boolean isPackageFrozen(String packageName) {
2443        synchronized (mPackages) {
2444            final PackageSetting ps = mSettings.mPackages.get(packageName);
2445            if (ps != null) {
2446                return ps.frozen;
2447            }
2448        }
2449        Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen");
2450        return true;
2451    }
2452
2453    @Override
2454    public boolean isPackageAvailable(String packageName, int userId) {
2455        if (!sUserManager.exists(userId)) return false;
2456        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2457        synchronized (mPackages) {
2458            PackageParser.Package p = mPackages.get(packageName);
2459            if (p != null) {
2460                final PackageSetting ps = (PackageSetting) p.mExtras;
2461                if (ps != null) {
2462                    final PackageUserState state = ps.readUserState(userId);
2463                    if (state != null) {
2464                        return PackageParser.isAvailable(state);
2465                    }
2466                }
2467            }
2468        }
2469        return false;
2470    }
2471
2472    @Override
2473    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2474        if (!sUserManager.exists(userId)) return null;
2475        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2476        // reader
2477        synchronized (mPackages) {
2478            PackageParser.Package p = mPackages.get(packageName);
2479            if (DEBUG_PACKAGE_INFO)
2480                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2481            if (p != null) {
2482                return generatePackageInfo(p, flags, userId);
2483            }
2484            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2485                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2486            }
2487        }
2488        return null;
2489    }
2490
2491    @Override
2492    public String[] currentToCanonicalPackageNames(String[] names) {
2493        String[] out = new String[names.length];
2494        // reader
2495        synchronized (mPackages) {
2496            for (int i=names.length-1; i>=0; i--) {
2497                PackageSetting ps = mSettings.mPackages.get(names[i]);
2498                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2499            }
2500        }
2501        return out;
2502    }
2503
2504    @Override
2505    public String[] canonicalToCurrentPackageNames(String[] names) {
2506        String[] out = new String[names.length];
2507        // reader
2508        synchronized (mPackages) {
2509            for (int i=names.length-1; i>=0; i--) {
2510                String cur = mSettings.mRenamedPackages.get(names[i]);
2511                out[i] = cur != null ? cur : names[i];
2512            }
2513        }
2514        return out;
2515    }
2516
2517    @Override
2518    public int getPackageUid(String packageName, int userId) {
2519        if (!sUserManager.exists(userId)) return -1;
2520        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2521
2522        // reader
2523        synchronized (mPackages) {
2524            PackageParser.Package p = mPackages.get(packageName);
2525            if(p != null) {
2526                return UserHandle.getUid(userId, p.applicationInfo.uid);
2527            }
2528            PackageSetting ps = mSettings.mPackages.get(packageName);
2529            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2530                return -1;
2531            }
2532            p = ps.pkg;
2533            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2534        }
2535    }
2536
2537    @Override
2538    public int[] getPackageGids(String packageName, int userId) throws RemoteException {
2539        if (!sUserManager.exists(userId)) {
2540            return null;
2541        }
2542
2543        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2544                "getPackageGids");
2545
2546        // reader
2547        synchronized (mPackages) {
2548            PackageParser.Package p = mPackages.get(packageName);
2549            if (DEBUG_PACKAGE_INFO) {
2550                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2551            }
2552            if (p != null) {
2553                PackageSetting ps = (PackageSetting) p.mExtras;
2554                return ps.getPermissionsState().computeGids(userId);
2555            }
2556        }
2557
2558        return null;
2559    }
2560
2561    static PermissionInfo generatePermissionInfo(
2562            BasePermission bp, int flags) {
2563        if (bp.perm != null) {
2564            return PackageParser.generatePermissionInfo(bp.perm, flags);
2565        }
2566        PermissionInfo pi = new PermissionInfo();
2567        pi.name = bp.name;
2568        pi.packageName = bp.sourcePackage;
2569        pi.nonLocalizedLabel = bp.name;
2570        pi.protectionLevel = bp.protectionLevel;
2571        return pi;
2572    }
2573
2574    @Override
2575    public PermissionInfo getPermissionInfo(String name, int flags) {
2576        // reader
2577        synchronized (mPackages) {
2578            final BasePermission p = mSettings.mPermissions.get(name);
2579            if (p != null) {
2580                return generatePermissionInfo(p, flags);
2581            }
2582            return null;
2583        }
2584    }
2585
2586    @Override
2587    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2588        // reader
2589        synchronized (mPackages) {
2590            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2591            for (BasePermission p : mSettings.mPermissions.values()) {
2592                if (group == null) {
2593                    if (p.perm == null || p.perm.info.group == null) {
2594                        out.add(generatePermissionInfo(p, flags));
2595                    }
2596                } else {
2597                    if (p.perm != null && group.equals(p.perm.info.group)) {
2598                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2599                    }
2600                }
2601            }
2602
2603            if (out.size() > 0) {
2604                return out;
2605            }
2606            return mPermissionGroups.containsKey(group) ? out : null;
2607        }
2608    }
2609
2610    @Override
2611    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2612        // reader
2613        synchronized (mPackages) {
2614            return PackageParser.generatePermissionGroupInfo(
2615                    mPermissionGroups.get(name), flags);
2616        }
2617    }
2618
2619    @Override
2620    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2621        // reader
2622        synchronized (mPackages) {
2623            final int N = mPermissionGroups.size();
2624            ArrayList<PermissionGroupInfo> out
2625                    = new ArrayList<PermissionGroupInfo>(N);
2626            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2627                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2628            }
2629            return out;
2630        }
2631    }
2632
2633    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2634            int userId) {
2635        if (!sUserManager.exists(userId)) return null;
2636        PackageSetting ps = mSettings.mPackages.get(packageName);
2637        if (ps != null) {
2638            if (ps.pkg == null) {
2639                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2640                        flags, userId);
2641                if (pInfo != null) {
2642                    return pInfo.applicationInfo;
2643                }
2644                return null;
2645            }
2646            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2647                    ps.readUserState(userId), userId);
2648        }
2649        return null;
2650    }
2651
2652    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2653            int userId) {
2654        if (!sUserManager.exists(userId)) return null;
2655        PackageSetting ps = mSettings.mPackages.get(packageName);
2656        if (ps != null) {
2657            PackageParser.Package pkg = ps.pkg;
2658            if (pkg == null) {
2659                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2660                    return null;
2661                }
2662                // Only data remains, so we aren't worried about code paths
2663                pkg = new PackageParser.Package(packageName);
2664                pkg.applicationInfo.packageName = packageName;
2665                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2666                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2667                pkg.applicationInfo.dataDir = PackageManager.getDataDirForUser(ps.volumeUuid,
2668                        packageName, userId).getAbsolutePath();
2669                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2670                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2671            }
2672            return generatePackageInfo(pkg, flags, userId);
2673        }
2674        return null;
2675    }
2676
2677    @Override
2678    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2679        if (!sUserManager.exists(userId)) return null;
2680        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2681        // writer
2682        synchronized (mPackages) {
2683            PackageParser.Package p = mPackages.get(packageName);
2684            if (DEBUG_PACKAGE_INFO) Log.v(
2685                    TAG, "getApplicationInfo " + packageName
2686                    + ": " + p);
2687            if (p != null) {
2688                PackageSetting ps = mSettings.mPackages.get(packageName);
2689                if (ps == null) return null;
2690                // Note: isEnabledLP() does not apply here - always return info
2691                return PackageParser.generateApplicationInfo(
2692                        p, flags, ps.readUserState(userId), userId);
2693            }
2694            if ("android".equals(packageName)||"system".equals(packageName)) {
2695                return mAndroidApplication;
2696            }
2697            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2698                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2699            }
2700        }
2701        return null;
2702    }
2703
2704    @Override
2705    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
2706            final IPackageDataObserver observer) {
2707        mContext.enforceCallingOrSelfPermission(
2708                android.Manifest.permission.CLEAR_APP_CACHE, null);
2709        // Queue up an async operation since clearing cache may take a little while.
2710        mHandler.post(new Runnable() {
2711            public void run() {
2712                mHandler.removeCallbacks(this);
2713                int retCode = -1;
2714                synchronized (mInstallLock) {
2715                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2716                    if (retCode < 0) {
2717                        Slog.w(TAG, "Couldn't clear application caches");
2718                    }
2719                }
2720                if (observer != null) {
2721                    try {
2722                        observer.onRemoveCompleted(null, (retCode >= 0));
2723                    } catch (RemoteException e) {
2724                        Slog.w(TAG, "RemoveException when invoking call back");
2725                    }
2726                }
2727            }
2728        });
2729    }
2730
2731    @Override
2732    public void freeStorage(final String volumeUuid, final long freeStorageSize,
2733            final IntentSender pi) {
2734        mContext.enforceCallingOrSelfPermission(
2735                android.Manifest.permission.CLEAR_APP_CACHE, null);
2736        // Queue up an async operation since clearing cache may take a little while.
2737        mHandler.post(new Runnable() {
2738            public void run() {
2739                mHandler.removeCallbacks(this);
2740                int retCode = -1;
2741                synchronized (mInstallLock) {
2742                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2743                    if (retCode < 0) {
2744                        Slog.w(TAG, "Couldn't clear application caches");
2745                    }
2746                }
2747                if(pi != null) {
2748                    try {
2749                        // Callback via pending intent
2750                        int code = (retCode >= 0) ? 1 : 0;
2751                        pi.sendIntent(null, code, null,
2752                                null, null);
2753                    } catch (SendIntentException e1) {
2754                        Slog.i(TAG, "Failed to send pending intent");
2755                    }
2756                }
2757            }
2758        });
2759    }
2760
2761    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
2762        synchronized (mInstallLock) {
2763            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
2764                throw new IOException("Failed to free enough space");
2765            }
2766        }
2767    }
2768
2769    @Override
2770    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2771        if (!sUserManager.exists(userId)) return null;
2772        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2773        synchronized (mPackages) {
2774            PackageParser.Activity a = mActivities.mActivities.get(component);
2775
2776            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2777            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2778                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2779                if (ps == null) return null;
2780                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2781                        userId);
2782            }
2783            if (mResolveComponentName.equals(component)) {
2784                return PackageParser.generateActivityInfo(mResolveActivity, flags,
2785                        new PackageUserState(), userId);
2786            }
2787        }
2788        return null;
2789    }
2790
2791    @Override
2792    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2793            String resolvedType) {
2794        synchronized (mPackages) {
2795            PackageParser.Activity a = mActivities.mActivities.get(component);
2796            if (a == null) {
2797                return false;
2798            }
2799            for (int i=0; i<a.intents.size(); i++) {
2800                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2801                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2802                    return true;
2803                }
2804            }
2805            return false;
2806        }
2807    }
2808
2809    @Override
2810    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2811        if (!sUserManager.exists(userId)) return null;
2812        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
2813        synchronized (mPackages) {
2814            PackageParser.Activity a = mReceivers.mActivities.get(component);
2815            if (DEBUG_PACKAGE_INFO) Log.v(
2816                TAG, "getReceiverInfo " + component + ": " + a);
2817            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2818                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2819                if (ps == null) return null;
2820                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2821                        userId);
2822            }
2823        }
2824        return null;
2825    }
2826
2827    @Override
2828    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2829        if (!sUserManager.exists(userId)) return null;
2830        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
2831        synchronized (mPackages) {
2832            PackageParser.Service s = mServices.mServices.get(component);
2833            if (DEBUG_PACKAGE_INFO) Log.v(
2834                TAG, "getServiceInfo " + component + ": " + s);
2835            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2836                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2837                if (ps == null) return null;
2838                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2839                        userId);
2840            }
2841        }
2842        return null;
2843    }
2844
2845    @Override
2846    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2847        if (!sUserManager.exists(userId)) return null;
2848        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
2849        synchronized (mPackages) {
2850            PackageParser.Provider p = mProviders.mProviders.get(component);
2851            if (DEBUG_PACKAGE_INFO) Log.v(
2852                TAG, "getProviderInfo " + component + ": " + p);
2853            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2854                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2855                if (ps == null) return null;
2856                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2857                        userId);
2858            }
2859        }
2860        return null;
2861    }
2862
2863    @Override
2864    public String[] getSystemSharedLibraryNames() {
2865        Set<String> libSet;
2866        synchronized (mPackages) {
2867            libSet = mSharedLibraries.keySet();
2868            int size = libSet.size();
2869            if (size > 0) {
2870                String[] libs = new String[size];
2871                libSet.toArray(libs);
2872                return libs;
2873            }
2874        }
2875        return null;
2876    }
2877
2878    /**
2879     * @hide
2880     */
2881    PackageParser.Package findSharedNonSystemLibrary(String libName) {
2882        synchronized (mPackages) {
2883            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
2884            if (lib != null && lib.apk != null) {
2885                return mPackages.get(lib.apk);
2886            }
2887        }
2888        return null;
2889    }
2890
2891    @Override
2892    public FeatureInfo[] getSystemAvailableFeatures() {
2893        Collection<FeatureInfo> featSet;
2894        synchronized (mPackages) {
2895            featSet = mAvailableFeatures.values();
2896            int size = featSet.size();
2897            if (size > 0) {
2898                FeatureInfo[] features = new FeatureInfo[size+1];
2899                featSet.toArray(features);
2900                FeatureInfo fi = new FeatureInfo();
2901                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2902                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2903                features[size] = fi;
2904                return features;
2905            }
2906        }
2907        return null;
2908    }
2909
2910    @Override
2911    public boolean hasSystemFeature(String name) {
2912        synchronized (mPackages) {
2913            return mAvailableFeatures.containsKey(name);
2914        }
2915    }
2916
2917    private void checkValidCaller(int uid, int userId) {
2918        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2919            return;
2920
2921        throw new SecurityException("Caller uid=" + uid
2922                + " is not privileged to communicate with user=" + userId);
2923    }
2924
2925    @Override
2926    public int checkPermission(String permName, String pkgName, int userId) {
2927        if (!sUserManager.exists(userId)) {
2928            return PackageManager.PERMISSION_DENIED;
2929        }
2930
2931        synchronized (mPackages) {
2932            final PackageParser.Package p = mPackages.get(pkgName);
2933            if (p != null && p.mExtras != null) {
2934                final PackageSetting ps = (PackageSetting) p.mExtras;
2935                if (ps.getPermissionsState().hasPermission(permName, userId)) {
2936                    return PackageManager.PERMISSION_GRANTED;
2937                }
2938            }
2939        }
2940
2941        return PackageManager.PERMISSION_DENIED;
2942    }
2943
2944    @Override
2945    public int checkUidPermission(String permName, int uid) {
2946        final int userId = UserHandle.getUserId(uid);
2947
2948        if (!sUserManager.exists(userId)) {
2949            return PackageManager.PERMISSION_DENIED;
2950        }
2951
2952        synchronized (mPackages) {
2953            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2954            if (obj != null) {
2955                final SettingBase ps = (SettingBase) obj;
2956                if (ps.getPermissionsState().hasPermission(permName, userId)) {
2957                    return PackageManager.PERMISSION_GRANTED;
2958                }
2959            } else {
2960                ArraySet<String> perms = mSystemPermissions.get(uid);
2961                if (perms != null && perms.contains(permName)) {
2962                    return PackageManager.PERMISSION_GRANTED;
2963                }
2964            }
2965        }
2966
2967        return PackageManager.PERMISSION_DENIED;
2968    }
2969
2970    /**
2971     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2972     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2973     * @param checkShell TODO(yamasani):
2974     * @param message the message to log on security exception
2975     */
2976    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
2977            boolean checkShell, String message) {
2978        if (userId < 0) {
2979            throw new IllegalArgumentException("Invalid userId " + userId);
2980        }
2981        if (checkShell) {
2982            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
2983        }
2984        if (userId == UserHandle.getUserId(callingUid)) return;
2985        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2986            if (requireFullPermission) {
2987                mContext.enforceCallingOrSelfPermission(
2988                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2989            } else {
2990                try {
2991                    mContext.enforceCallingOrSelfPermission(
2992                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2993                } catch (SecurityException se) {
2994                    mContext.enforceCallingOrSelfPermission(
2995                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2996                }
2997            }
2998        }
2999    }
3000
3001    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3002        if (callingUid == Process.SHELL_UID) {
3003            if (userHandle >= 0
3004                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3005                throw new SecurityException("Shell does not have permission to access user "
3006                        + userHandle);
3007            } else if (userHandle < 0) {
3008                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3009                        + Debug.getCallers(3));
3010            }
3011        }
3012    }
3013
3014    private BasePermission findPermissionTreeLP(String permName) {
3015        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3016            if (permName.startsWith(bp.name) &&
3017                    permName.length() > bp.name.length() &&
3018                    permName.charAt(bp.name.length()) == '.') {
3019                return bp;
3020            }
3021        }
3022        return null;
3023    }
3024
3025    private BasePermission checkPermissionTreeLP(String permName) {
3026        if (permName != null) {
3027            BasePermission bp = findPermissionTreeLP(permName);
3028            if (bp != null) {
3029                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3030                    return bp;
3031                }
3032                throw new SecurityException("Calling uid "
3033                        + Binder.getCallingUid()
3034                        + " is not allowed to add to permission tree "
3035                        + bp.name + " owned by uid " + bp.uid);
3036            }
3037        }
3038        throw new SecurityException("No permission tree found for " + permName);
3039    }
3040
3041    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3042        if (s1 == null) {
3043            return s2 == null;
3044        }
3045        if (s2 == null) {
3046            return false;
3047        }
3048        if (s1.getClass() != s2.getClass()) {
3049            return false;
3050        }
3051        return s1.equals(s2);
3052    }
3053
3054    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3055        if (pi1.icon != pi2.icon) return false;
3056        if (pi1.logo != pi2.logo) return false;
3057        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3058        if (!compareStrings(pi1.name, pi2.name)) return false;
3059        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3060        // We'll take care of setting this one.
3061        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3062        // These are not currently stored in settings.
3063        //if (!compareStrings(pi1.group, pi2.group)) return false;
3064        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3065        //if (pi1.labelRes != pi2.labelRes) return false;
3066        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3067        return true;
3068    }
3069
3070    int permissionInfoFootprint(PermissionInfo info) {
3071        int size = info.name.length();
3072        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3073        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3074        return size;
3075    }
3076
3077    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3078        int size = 0;
3079        for (BasePermission perm : mSettings.mPermissions.values()) {
3080            if (perm.uid == tree.uid) {
3081                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3082            }
3083        }
3084        return size;
3085    }
3086
3087    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3088        // We calculate the max size of permissions defined by this uid and throw
3089        // if that plus the size of 'info' would exceed our stated maximum.
3090        if (tree.uid != Process.SYSTEM_UID) {
3091            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3092            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3093                throw new SecurityException("Permission tree size cap exceeded");
3094            }
3095        }
3096    }
3097
3098    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3099        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3100            throw new SecurityException("Label must be specified in permission");
3101        }
3102        BasePermission tree = checkPermissionTreeLP(info.name);
3103        BasePermission bp = mSettings.mPermissions.get(info.name);
3104        boolean added = bp == null;
3105        boolean changed = true;
3106        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3107        if (added) {
3108            enforcePermissionCapLocked(info, tree);
3109            bp = new BasePermission(info.name, tree.sourcePackage,
3110                    BasePermission.TYPE_DYNAMIC);
3111        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3112            throw new SecurityException(
3113                    "Not allowed to modify non-dynamic permission "
3114                    + info.name);
3115        } else {
3116            if (bp.protectionLevel == fixedLevel
3117                    && bp.perm.owner.equals(tree.perm.owner)
3118                    && bp.uid == tree.uid
3119                    && comparePermissionInfos(bp.perm.info, info)) {
3120                changed = false;
3121            }
3122        }
3123        bp.protectionLevel = fixedLevel;
3124        info = new PermissionInfo(info);
3125        info.protectionLevel = fixedLevel;
3126        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3127        bp.perm.info.packageName = tree.perm.info.packageName;
3128        bp.uid = tree.uid;
3129        if (added) {
3130            mSettings.mPermissions.put(info.name, bp);
3131        }
3132        if (changed) {
3133            if (!async) {
3134                mSettings.writeLPr();
3135            } else {
3136                scheduleWriteSettingsLocked();
3137            }
3138        }
3139        return added;
3140    }
3141
3142    @Override
3143    public boolean addPermission(PermissionInfo info) {
3144        synchronized (mPackages) {
3145            return addPermissionLocked(info, false);
3146        }
3147    }
3148
3149    @Override
3150    public boolean addPermissionAsync(PermissionInfo info) {
3151        synchronized (mPackages) {
3152            return addPermissionLocked(info, true);
3153        }
3154    }
3155
3156    @Override
3157    public void removePermission(String name) {
3158        synchronized (mPackages) {
3159            checkPermissionTreeLP(name);
3160            BasePermission bp = mSettings.mPermissions.get(name);
3161            if (bp != null) {
3162                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3163                    throw new SecurityException(
3164                            "Not allowed to modify non-dynamic permission "
3165                            + name);
3166                }
3167                mSettings.mPermissions.remove(name);
3168                mSettings.writeLPr();
3169            }
3170        }
3171    }
3172
3173    private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg,
3174            BasePermission bp) {
3175        int index = pkg.requestedPermissions.indexOf(bp.name);
3176        if (index == -1) {
3177            throw new SecurityException("Package " + pkg.packageName
3178                    + " has not requested permission " + bp.name);
3179        }
3180        if (!bp.isRuntime()) {
3181            throw new SecurityException("Permission " + bp.name
3182                    + " is not a changeable permission type");
3183        }
3184    }
3185
3186    @Override
3187    public void grantRuntimePermission(String packageName, String name, final int userId) {
3188        if (!sUserManager.exists(userId)) {
3189            Log.e(TAG, "No such user:" + userId);
3190            return;
3191        }
3192
3193        mContext.enforceCallingOrSelfPermission(
3194                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3195                "grantRuntimePermission");
3196
3197        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3198                "grantRuntimePermission");
3199
3200        final SettingBase sb;
3201
3202        synchronized (mPackages) {
3203            final PackageParser.Package pkg = mPackages.get(packageName);
3204            if (pkg == null) {
3205                throw new IllegalArgumentException("Unknown package: " + packageName);
3206            }
3207
3208            final BasePermission bp = mSettings.mPermissions.get(name);
3209            if (bp == null) {
3210                throw new IllegalArgumentException("Unknown permission: " + name);
3211            }
3212
3213            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3214
3215            sb = (SettingBase) pkg.mExtras;
3216            if (sb == null) {
3217                throw new IllegalArgumentException("Unknown package: " + packageName);
3218            }
3219
3220            final PermissionsState permissionsState = sb.getPermissionsState();
3221
3222            final int flags = permissionsState.getPermissionFlags(name, userId);
3223            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3224                throw new SecurityException("Cannot grant system fixed permission: "
3225                        + name + " for package: " + packageName);
3226            }
3227
3228            final int result = permissionsState.grantRuntimePermission(bp, userId);
3229            switch (result) {
3230                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3231                    return;
3232                }
3233
3234                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3235                    mHandler.post(new Runnable() {
3236                        @Override
3237                        public void run() {
3238                            killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED);
3239                        }
3240                    });
3241                } break;
3242            }
3243
3244            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3245
3246            // Not critical if that is lost - app has to request again.
3247            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3248        }
3249    }
3250
3251    @Override
3252    public void revokeRuntimePermission(String packageName, String name, int userId) {
3253        if (!sUserManager.exists(userId)) {
3254            Log.e(TAG, "No such user:" + userId);
3255            return;
3256        }
3257
3258        mContext.enforceCallingOrSelfPermission(
3259                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3260                "revokeRuntimePermission");
3261
3262        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3263                "revokeRuntimePermission");
3264
3265        final SettingBase sb;
3266
3267        synchronized (mPackages) {
3268            final PackageParser.Package pkg = mPackages.get(packageName);
3269            if (pkg == null) {
3270                throw new IllegalArgumentException("Unknown package: " + packageName);
3271            }
3272
3273            final BasePermission bp = mSettings.mPermissions.get(name);
3274            if (bp == null) {
3275                throw new IllegalArgumentException("Unknown permission: " + name);
3276            }
3277
3278            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3279
3280            sb = (SettingBase) pkg.mExtras;
3281            if (sb == null) {
3282                throw new IllegalArgumentException("Unknown package: " + packageName);
3283            }
3284
3285            final PermissionsState permissionsState = sb.getPermissionsState();
3286
3287            final int flags = permissionsState.getPermissionFlags(name, userId);
3288            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3289                throw new SecurityException("Cannot revoke system fixed permission: "
3290                        + name + " for package: " + packageName);
3291            }
3292
3293            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3294                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3295                return;
3296            }
3297
3298            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3299
3300            // Critical, after this call app should never have the permission.
3301            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3302        }
3303
3304        killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3305    }
3306
3307    @Override
3308    public int getPermissionFlags(String name, String packageName, int userId) {
3309        if (!sUserManager.exists(userId)) {
3310            return 0;
3311        }
3312
3313        mContext.enforceCallingOrSelfPermission(
3314                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3315                "getPermissionFlags");
3316
3317        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3318                "getPermissionFlags");
3319
3320        synchronized (mPackages) {
3321            final PackageParser.Package pkg = mPackages.get(packageName);
3322            if (pkg == null) {
3323                throw new IllegalArgumentException("Unknown package: " + packageName);
3324            }
3325
3326            final BasePermission bp = mSettings.mPermissions.get(name);
3327            if (bp == null) {
3328                throw new IllegalArgumentException("Unknown permission: " + name);
3329            }
3330
3331            SettingBase sb = (SettingBase) pkg.mExtras;
3332            if (sb == null) {
3333                throw new IllegalArgumentException("Unknown package: " + packageName);
3334            }
3335
3336            PermissionsState permissionsState = sb.getPermissionsState();
3337            return permissionsState.getPermissionFlags(name, userId);
3338        }
3339    }
3340
3341    @Override
3342    public void updatePermissionFlags(String name, String packageName, int flagMask,
3343            int flagValues, int userId) {
3344        if (!sUserManager.exists(userId)) {
3345            return;
3346        }
3347
3348        mContext.enforceCallingOrSelfPermission(
3349                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3350                "updatePermissionFlags");
3351
3352        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3353                "updatePermissionFlags");
3354
3355        // Only the system can change system fixed flags.
3356        if (getCallingUid() != Process.SYSTEM_UID) {
3357            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3358            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3359        }
3360
3361        synchronized (mPackages) {
3362            final PackageParser.Package pkg = mPackages.get(packageName);
3363            if (pkg == null) {
3364                throw new IllegalArgumentException("Unknown package: " + packageName);
3365            }
3366
3367            final BasePermission bp = mSettings.mPermissions.get(name);
3368            if (bp == null) {
3369                throw new IllegalArgumentException("Unknown permission: " + name);
3370            }
3371
3372            SettingBase sb = (SettingBase) pkg.mExtras;
3373            if (sb == null) {
3374                throw new IllegalArgumentException("Unknown package: " + packageName);
3375            }
3376
3377            PermissionsState permissionsState = sb.getPermissionsState();
3378
3379            // Only the package manager can change flags for system component permissions.
3380            final int flags = permissionsState.getPermissionFlags(bp.name, userId);
3381            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3382                return;
3383            }
3384
3385            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3386
3387            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3388                // Install and runtime permissions are stored in different places,
3389                // so figure out what permission changed and persist the change.
3390                if (permissionsState.getInstallPermissionState(name) != null) {
3391                    scheduleWriteSettingsLocked();
3392                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3393                        || hadState) {
3394                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3395                }
3396            }
3397        }
3398    }
3399
3400    /**
3401     * Update the permission flags for all packages and runtime permissions of a user in order
3402     * to allow device or profile owner to remove POLICY_FIXED.
3403     */
3404    @Override
3405    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3406        if (!sUserManager.exists(userId)) {
3407            return;
3408        }
3409
3410        mContext.enforceCallingOrSelfPermission(
3411                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3412                "updatePermissionFlagsForAllApps");
3413
3414        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3415                "updatePermissionFlagsForAllApps");
3416
3417        // Only the system can change system fixed flags.
3418        if (getCallingUid() != Process.SYSTEM_UID) {
3419            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3420            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3421        }
3422
3423        synchronized (mPackages) {
3424            boolean changed = false;
3425            final int packageCount = mPackages.size();
3426            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
3427                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
3428                SettingBase sb = (SettingBase) pkg.mExtras;
3429                if (sb == null) {
3430                    continue;
3431                }
3432                PermissionsState permissionsState = sb.getPermissionsState();
3433                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
3434                        userId, flagMask, flagValues);
3435            }
3436            if (changed) {
3437                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3438            }
3439        }
3440    }
3441
3442    @Override
3443    public boolean shouldShowRequestPermissionRationale(String permissionName,
3444            String packageName, int userId) {
3445        if (UserHandle.getCallingUserId() != userId) {
3446            mContext.enforceCallingPermission(
3447                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3448                    "canShowRequestPermissionRationale for user " + userId);
3449        }
3450
3451        final int uid = getPackageUid(packageName, userId);
3452        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
3453            return false;
3454        }
3455
3456        if (checkPermission(permissionName, packageName, userId)
3457                == PackageManager.PERMISSION_GRANTED) {
3458            return false;
3459        }
3460
3461        final int flags;
3462
3463        final long identity = Binder.clearCallingIdentity();
3464        try {
3465            flags = getPermissionFlags(permissionName,
3466                    packageName, userId);
3467        } finally {
3468            Binder.restoreCallingIdentity(identity);
3469        }
3470
3471        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
3472                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
3473                | PackageManager.FLAG_PERMISSION_USER_FIXED;
3474
3475        if ((flags & fixedFlags) != 0) {
3476            return false;
3477        }
3478
3479        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
3480    }
3481
3482    void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) {
3483        BasePermission bp = mSettings.mPermissions.get(permission);
3484        if (bp == null) {
3485            throw new SecurityException("Missing " + permission + " permission");
3486        }
3487
3488        SettingBase sb = (SettingBase) pkg.mExtras;
3489        PermissionsState permissionsState = sb.getPermissionsState();
3490
3491        if (permissionsState.grantInstallPermission(bp) !=
3492                PermissionsState.PERMISSION_OPERATION_FAILURE) {
3493            scheduleWriteSettingsLocked();
3494        }
3495    }
3496
3497    @Override
3498    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3499        mContext.enforceCallingOrSelfPermission(
3500                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
3501                "addOnPermissionsChangeListener");
3502
3503        synchronized (mPackages) {
3504            mOnPermissionChangeListeners.addListenerLocked(listener);
3505        }
3506    }
3507
3508    @Override
3509    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3510        synchronized (mPackages) {
3511            mOnPermissionChangeListeners.removeListenerLocked(listener);
3512        }
3513    }
3514
3515    @Override
3516    public boolean isProtectedBroadcast(String actionName) {
3517        synchronized (mPackages) {
3518            return mProtectedBroadcasts.contains(actionName);
3519        }
3520    }
3521
3522    @Override
3523    public int checkSignatures(String pkg1, String pkg2) {
3524        synchronized (mPackages) {
3525            final PackageParser.Package p1 = mPackages.get(pkg1);
3526            final PackageParser.Package p2 = mPackages.get(pkg2);
3527            if (p1 == null || p1.mExtras == null
3528                    || p2 == null || p2.mExtras == null) {
3529                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3530            }
3531            return compareSignatures(p1.mSignatures, p2.mSignatures);
3532        }
3533    }
3534
3535    @Override
3536    public int checkUidSignatures(int uid1, int uid2) {
3537        // Map to base uids.
3538        uid1 = UserHandle.getAppId(uid1);
3539        uid2 = UserHandle.getAppId(uid2);
3540        // reader
3541        synchronized (mPackages) {
3542            Signature[] s1;
3543            Signature[] s2;
3544            Object obj = mSettings.getUserIdLPr(uid1);
3545            if (obj != null) {
3546                if (obj instanceof SharedUserSetting) {
3547                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3548                } else if (obj instanceof PackageSetting) {
3549                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3550                } else {
3551                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3552                }
3553            } else {
3554                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3555            }
3556            obj = mSettings.getUserIdLPr(uid2);
3557            if (obj != null) {
3558                if (obj instanceof SharedUserSetting) {
3559                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3560                } else if (obj instanceof PackageSetting) {
3561                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3562                } else {
3563                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3564                }
3565            } else {
3566                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3567            }
3568            return compareSignatures(s1, s2);
3569        }
3570    }
3571
3572    private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) {
3573        final long identity = Binder.clearCallingIdentity();
3574        try {
3575            if (sb instanceof SharedUserSetting) {
3576                SharedUserSetting sus = (SharedUserSetting) sb;
3577                final int packageCount = sus.packages.size();
3578                for (int i = 0; i < packageCount; i++) {
3579                    PackageSetting susPs = sus.packages.valueAt(i);
3580                    if (userId == UserHandle.USER_ALL) {
3581                        killApplication(susPs.pkg.packageName, susPs.appId, reason);
3582                    } else {
3583                        final int uid = UserHandle.getUid(userId, susPs.appId);
3584                        killUid(uid, reason);
3585                    }
3586                }
3587            } else if (sb instanceof PackageSetting) {
3588                PackageSetting ps = (PackageSetting) sb;
3589                if (userId == UserHandle.USER_ALL) {
3590                    killApplication(ps.pkg.packageName, ps.appId, reason);
3591                } else {
3592                    final int uid = UserHandle.getUid(userId, ps.appId);
3593                    killUid(uid, reason);
3594                }
3595            }
3596        } finally {
3597            Binder.restoreCallingIdentity(identity);
3598        }
3599    }
3600
3601    private static void killUid(int uid, String reason) {
3602        IActivityManager am = ActivityManagerNative.getDefault();
3603        if (am != null) {
3604            try {
3605                am.killUid(uid, reason);
3606            } catch (RemoteException e) {
3607                /* ignore - same process */
3608            }
3609        }
3610    }
3611
3612    /**
3613     * Compares two sets of signatures. Returns:
3614     * <br />
3615     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3616     * <br />
3617     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3618     * <br />
3619     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3620     * <br />
3621     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3622     * <br />
3623     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3624     */
3625    static int compareSignatures(Signature[] s1, Signature[] s2) {
3626        if (s1 == null) {
3627            return s2 == null
3628                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3629                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3630        }
3631
3632        if (s2 == null) {
3633            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3634        }
3635
3636        if (s1.length != s2.length) {
3637            return PackageManager.SIGNATURE_NO_MATCH;
3638        }
3639
3640        // Since both signature sets are of size 1, we can compare without HashSets.
3641        if (s1.length == 1) {
3642            return s1[0].equals(s2[0]) ?
3643                    PackageManager.SIGNATURE_MATCH :
3644                    PackageManager.SIGNATURE_NO_MATCH;
3645        }
3646
3647        ArraySet<Signature> set1 = new ArraySet<Signature>();
3648        for (Signature sig : s1) {
3649            set1.add(sig);
3650        }
3651        ArraySet<Signature> set2 = new ArraySet<Signature>();
3652        for (Signature sig : s2) {
3653            set2.add(sig);
3654        }
3655        // Make sure s2 contains all signatures in s1.
3656        if (set1.equals(set2)) {
3657            return PackageManager.SIGNATURE_MATCH;
3658        }
3659        return PackageManager.SIGNATURE_NO_MATCH;
3660    }
3661
3662    /**
3663     * If the database version for this type of package (internal storage or
3664     * external storage) is less than the version where package signatures
3665     * were updated, return true.
3666     */
3667    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3668        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
3669                DatabaseVersion.SIGNATURE_END_ENTITY))
3670                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
3671                        DatabaseVersion.SIGNATURE_END_ENTITY));
3672    }
3673
3674    /**
3675     * Used for backward compatibility to make sure any packages with
3676     * certificate chains get upgraded to the new style. {@code existingSigs}
3677     * will be in the old format (since they were stored on disk from before the
3678     * system upgrade) and {@code scannedSigs} will be in the newer format.
3679     */
3680    private int compareSignaturesCompat(PackageSignatures existingSigs,
3681            PackageParser.Package scannedPkg) {
3682        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
3683            return PackageManager.SIGNATURE_NO_MATCH;
3684        }
3685
3686        ArraySet<Signature> existingSet = new ArraySet<Signature>();
3687        for (Signature sig : existingSigs.mSignatures) {
3688            existingSet.add(sig);
3689        }
3690        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
3691        for (Signature sig : scannedPkg.mSignatures) {
3692            try {
3693                Signature[] chainSignatures = sig.getChainSignatures();
3694                for (Signature chainSig : chainSignatures) {
3695                    scannedCompatSet.add(chainSig);
3696                }
3697            } catch (CertificateEncodingException e) {
3698                scannedCompatSet.add(sig);
3699            }
3700        }
3701        /*
3702         * Make sure the expanded scanned set contains all signatures in the
3703         * existing one.
3704         */
3705        if (scannedCompatSet.equals(existingSet)) {
3706            // Migrate the old signatures to the new scheme.
3707            existingSigs.assignSignatures(scannedPkg.mSignatures);
3708            // The new KeySets will be re-added later in the scanning process.
3709            synchronized (mPackages) {
3710                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
3711            }
3712            return PackageManager.SIGNATURE_MATCH;
3713        }
3714        return PackageManager.SIGNATURE_NO_MATCH;
3715    }
3716
3717    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3718        if (isExternal(scannedPkg)) {
3719            return mSettings.isExternalDatabaseVersionOlderThan(
3720                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3721        } else {
3722            return mSettings.isInternalDatabaseVersionOlderThan(
3723                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3724        }
3725    }
3726
3727    private int compareSignaturesRecover(PackageSignatures existingSigs,
3728            PackageParser.Package scannedPkg) {
3729        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
3730            return PackageManager.SIGNATURE_NO_MATCH;
3731        }
3732
3733        String msg = null;
3734        try {
3735            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
3736                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
3737                        + scannedPkg.packageName);
3738                return PackageManager.SIGNATURE_MATCH;
3739            }
3740        } catch (CertificateException e) {
3741            msg = e.getMessage();
3742        }
3743
3744        logCriticalInfo(Log.INFO,
3745                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
3746        return PackageManager.SIGNATURE_NO_MATCH;
3747    }
3748
3749    @Override
3750    public String[] getPackagesForUid(int uid) {
3751        uid = UserHandle.getAppId(uid);
3752        // reader
3753        synchronized (mPackages) {
3754            Object obj = mSettings.getUserIdLPr(uid);
3755            if (obj instanceof SharedUserSetting) {
3756                final SharedUserSetting sus = (SharedUserSetting) obj;
3757                final int N = sus.packages.size();
3758                final String[] res = new String[N];
3759                final Iterator<PackageSetting> it = sus.packages.iterator();
3760                int i = 0;
3761                while (it.hasNext()) {
3762                    res[i++] = it.next().name;
3763                }
3764                return res;
3765            } else if (obj instanceof PackageSetting) {
3766                final PackageSetting ps = (PackageSetting) obj;
3767                return new String[] { ps.name };
3768            }
3769        }
3770        return null;
3771    }
3772
3773    @Override
3774    public String getNameForUid(int uid) {
3775        // reader
3776        synchronized (mPackages) {
3777            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3778            if (obj instanceof SharedUserSetting) {
3779                final SharedUserSetting sus = (SharedUserSetting) obj;
3780                return sus.name + ":" + sus.userId;
3781            } else if (obj instanceof PackageSetting) {
3782                final PackageSetting ps = (PackageSetting) obj;
3783                return ps.name;
3784            }
3785        }
3786        return null;
3787    }
3788
3789    @Override
3790    public int getUidForSharedUser(String sharedUserName) {
3791        if(sharedUserName == null) {
3792            return -1;
3793        }
3794        // reader
3795        synchronized (mPackages) {
3796            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
3797            if (suid == null) {
3798                return -1;
3799            }
3800            return suid.userId;
3801        }
3802    }
3803
3804    @Override
3805    public int getFlagsForUid(int uid) {
3806        synchronized (mPackages) {
3807            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3808            if (obj instanceof SharedUserSetting) {
3809                final SharedUserSetting sus = (SharedUserSetting) obj;
3810                return sus.pkgFlags;
3811            } else if (obj instanceof PackageSetting) {
3812                final PackageSetting ps = (PackageSetting) obj;
3813                return ps.pkgFlags;
3814            }
3815        }
3816        return 0;
3817    }
3818
3819    @Override
3820    public int getPrivateFlagsForUid(int uid) {
3821        synchronized (mPackages) {
3822            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3823            if (obj instanceof SharedUserSetting) {
3824                final SharedUserSetting sus = (SharedUserSetting) obj;
3825                return sus.pkgPrivateFlags;
3826            } else if (obj instanceof PackageSetting) {
3827                final PackageSetting ps = (PackageSetting) obj;
3828                return ps.pkgPrivateFlags;
3829            }
3830        }
3831        return 0;
3832    }
3833
3834    @Override
3835    public boolean isUidPrivileged(int uid) {
3836        uid = UserHandle.getAppId(uid);
3837        // reader
3838        synchronized (mPackages) {
3839            Object obj = mSettings.getUserIdLPr(uid);
3840            if (obj instanceof SharedUserSetting) {
3841                final SharedUserSetting sus = (SharedUserSetting) obj;
3842                final Iterator<PackageSetting> it = sus.packages.iterator();
3843                while (it.hasNext()) {
3844                    if (it.next().isPrivileged()) {
3845                        return true;
3846                    }
3847                }
3848            } else if (obj instanceof PackageSetting) {
3849                final PackageSetting ps = (PackageSetting) obj;
3850                return ps.isPrivileged();
3851            }
3852        }
3853        return false;
3854    }
3855
3856    @Override
3857    public String[] getAppOpPermissionPackages(String permissionName) {
3858        synchronized (mPackages) {
3859            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
3860            if (pkgs == null) {
3861                return null;
3862            }
3863            return pkgs.toArray(new String[pkgs.size()]);
3864        }
3865    }
3866
3867    @Override
3868    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
3869            int flags, int userId) {
3870        if (!sUserManager.exists(userId)) return null;
3871        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
3872        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3873        return chooseBestActivity(intent, resolvedType, flags, query, userId);
3874    }
3875
3876    @Override
3877    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
3878            IntentFilter filter, int match, ComponentName activity) {
3879        final int userId = UserHandle.getCallingUserId();
3880        if (DEBUG_PREFERRED) {
3881            Log.v(TAG, "setLastChosenActivity intent=" + intent
3882                + " resolvedType=" + resolvedType
3883                + " flags=" + flags
3884                + " filter=" + filter
3885                + " match=" + match
3886                + " activity=" + activity);
3887            filter.dump(new PrintStreamPrinter(System.out), "    ");
3888        }
3889        intent.setComponent(null);
3890        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3891        // Find any earlier preferred or last chosen entries and nuke them
3892        findPreferredActivity(intent, resolvedType,
3893                flags, query, 0, false, true, false, userId);
3894        // Add the new activity as the last chosen for this filter
3895        addPreferredActivityInternal(filter, match, null, activity, false, userId,
3896                "Setting last chosen");
3897    }
3898
3899    @Override
3900    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
3901        final int userId = UserHandle.getCallingUserId();
3902        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
3903        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3904        return findPreferredActivity(intent, resolvedType, flags, query, 0,
3905                false, false, false, userId);
3906    }
3907
3908    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
3909            int flags, List<ResolveInfo> query, int userId) {
3910        if (query != null) {
3911            final int N = query.size();
3912            if (N == 1) {
3913                return query.get(0);
3914            } else if (N > 1) {
3915                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
3916                // If there is more than one activity with the same priority,
3917                // then let the user decide between them.
3918                ResolveInfo r0 = query.get(0);
3919                ResolveInfo r1 = query.get(1);
3920                if (DEBUG_INTENT_MATCHING || debug) {
3921                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
3922                            + r1.activityInfo.name + "=" + r1.priority);
3923                }
3924                // If the first activity has a higher priority, or a different
3925                // default, then it is always desireable to pick it.
3926                if (r0.priority != r1.priority
3927                        || r0.preferredOrder != r1.preferredOrder
3928                        || r0.isDefault != r1.isDefault) {
3929                    return query.get(0);
3930                }
3931                // If we have saved a preference for a preferred activity for
3932                // this Intent, use that.
3933                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
3934                        flags, query, r0.priority, true, false, debug, userId);
3935                if (ri != null) {
3936                    return ri;
3937                }
3938                if (userId != 0) {
3939                    ri = new ResolveInfo(mResolveInfo);
3940                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
3941                    ri.activityInfo.applicationInfo = new ApplicationInfo(
3942                            ri.activityInfo.applicationInfo);
3943                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
3944                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
3945                    return ri;
3946                }
3947                return mResolveInfo;
3948            }
3949        }
3950        return null;
3951    }
3952
3953    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
3954            int flags, List<ResolveInfo> query, boolean debug, int userId) {
3955        final int N = query.size();
3956        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
3957                .get(userId);
3958        // Get the list of persistent preferred activities that handle the intent
3959        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
3960        List<PersistentPreferredActivity> pprefs = ppir != null
3961                ? ppir.queryIntent(intent, resolvedType,
3962                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3963                : null;
3964        if (pprefs != null && pprefs.size() > 0) {
3965            final int M = pprefs.size();
3966            for (int i=0; i<M; i++) {
3967                final PersistentPreferredActivity ppa = pprefs.get(i);
3968                if (DEBUG_PREFERRED || debug) {
3969                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
3970                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
3971                            + "\n  component=" + ppa.mComponent);
3972                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3973                }
3974                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
3975                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3976                if (DEBUG_PREFERRED || debug) {
3977                    Slog.v(TAG, "Found persistent preferred activity:");
3978                    if (ai != null) {
3979                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3980                    } else {
3981                        Slog.v(TAG, "  null");
3982                    }
3983                }
3984                if (ai == null) {
3985                    // This previously registered persistent preferred activity
3986                    // component is no longer known. Ignore it and do NOT remove it.
3987                    continue;
3988                }
3989                for (int j=0; j<N; j++) {
3990                    final ResolveInfo ri = query.get(j);
3991                    if (!ri.activityInfo.applicationInfo.packageName
3992                            .equals(ai.applicationInfo.packageName)) {
3993                        continue;
3994                    }
3995                    if (!ri.activityInfo.name.equals(ai.name)) {
3996                        continue;
3997                    }
3998                    //  Found a persistent preference that can handle the intent.
3999                    if (DEBUG_PREFERRED || debug) {
4000                        Slog.v(TAG, "Returning persistent preferred activity: " +
4001                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4002                    }
4003                    return ri;
4004                }
4005            }
4006        }
4007        return null;
4008    }
4009
4010    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4011            List<ResolveInfo> query, int priority, boolean always,
4012            boolean removeMatches, boolean debug, int userId) {
4013        if (!sUserManager.exists(userId)) return null;
4014        // writer
4015        synchronized (mPackages) {
4016            if (intent.getSelector() != null) {
4017                intent = intent.getSelector();
4018            }
4019            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4020
4021            // Try to find a matching persistent preferred activity.
4022            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4023                    debug, userId);
4024
4025            // If a persistent preferred activity matched, use it.
4026            if (pri != null) {
4027                return pri;
4028            }
4029
4030            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4031            // Get the list of preferred activities that handle the intent
4032            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4033            List<PreferredActivity> prefs = pir != null
4034                    ? pir.queryIntent(intent, resolvedType,
4035                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4036                    : null;
4037            if (prefs != null && prefs.size() > 0) {
4038                boolean changed = false;
4039                try {
4040                    // First figure out how good the original match set is.
4041                    // We will only allow preferred activities that came
4042                    // from the same match quality.
4043                    int match = 0;
4044
4045                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4046
4047                    final int N = query.size();
4048                    for (int j=0; j<N; j++) {
4049                        final ResolveInfo ri = query.get(j);
4050                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4051                                + ": 0x" + Integer.toHexString(match));
4052                        if (ri.match > match) {
4053                            match = ri.match;
4054                        }
4055                    }
4056
4057                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4058                            + Integer.toHexString(match));
4059
4060                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4061                    final int M = prefs.size();
4062                    for (int i=0; i<M; i++) {
4063                        final PreferredActivity pa = prefs.get(i);
4064                        if (DEBUG_PREFERRED || debug) {
4065                            Slog.v(TAG, "Checking PreferredActivity ds="
4066                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4067                                    + "\n  component=" + pa.mPref.mComponent);
4068                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4069                        }
4070                        if (pa.mPref.mMatch != match) {
4071                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4072                                    + Integer.toHexString(pa.mPref.mMatch));
4073                            continue;
4074                        }
4075                        // If it's not an "always" type preferred activity and that's what we're
4076                        // looking for, skip it.
4077                        if (always && !pa.mPref.mAlways) {
4078                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4079                            continue;
4080                        }
4081                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4082                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4083                        if (DEBUG_PREFERRED || debug) {
4084                            Slog.v(TAG, "Found preferred activity:");
4085                            if (ai != null) {
4086                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4087                            } else {
4088                                Slog.v(TAG, "  null");
4089                            }
4090                        }
4091                        if (ai == null) {
4092                            // This previously registered preferred activity
4093                            // component is no longer known.  Most likely an update
4094                            // to the app was installed and in the new version this
4095                            // component no longer exists.  Clean it up by removing
4096                            // it from the preferred activities list, and skip it.
4097                            Slog.w(TAG, "Removing dangling preferred activity: "
4098                                    + pa.mPref.mComponent);
4099                            pir.removeFilter(pa);
4100                            changed = true;
4101                            continue;
4102                        }
4103                        for (int j=0; j<N; j++) {
4104                            final ResolveInfo ri = query.get(j);
4105                            if (!ri.activityInfo.applicationInfo.packageName
4106                                    .equals(ai.applicationInfo.packageName)) {
4107                                continue;
4108                            }
4109                            if (!ri.activityInfo.name.equals(ai.name)) {
4110                                continue;
4111                            }
4112
4113                            if (removeMatches) {
4114                                pir.removeFilter(pa);
4115                                changed = true;
4116                                if (DEBUG_PREFERRED) {
4117                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4118                                }
4119                                break;
4120                            }
4121
4122                            // Okay we found a previously set preferred or last chosen app.
4123                            // If the result set is different from when this
4124                            // was created, we need to clear it and re-ask the
4125                            // user their preference, if we're looking for an "always" type entry.
4126                            if (always && !pa.mPref.sameSet(query)) {
4127                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4128                                        + intent + " type " + resolvedType);
4129                                if (DEBUG_PREFERRED) {
4130                                    Slog.v(TAG, "Removing preferred activity since set changed "
4131                                            + pa.mPref.mComponent);
4132                                }
4133                                pir.removeFilter(pa);
4134                                // Re-add the filter as a "last chosen" entry (!always)
4135                                PreferredActivity lastChosen = new PreferredActivity(
4136                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4137                                pir.addFilter(lastChosen);
4138                                changed = true;
4139                                return null;
4140                            }
4141
4142                            // Yay! Either the set matched or we're looking for the last chosen
4143                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4144                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4145                            return ri;
4146                        }
4147                    }
4148                } finally {
4149                    if (changed) {
4150                        if (DEBUG_PREFERRED) {
4151                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4152                        }
4153                        scheduleWritePackageRestrictionsLocked(userId);
4154                    }
4155                }
4156            }
4157        }
4158        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4159        return null;
4160    }
4161
4162    /*
4163     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4164     */
4165    @Override
4166    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4167            int targetUserId) {
4168        mContext.enforceCallingOrSelfPermission(
4169                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4170        List<CrossProfileIntentFilter> matches =
4171                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4172        if (matches != null) {
4173            int size = matches.size();
4174            for (int i = 0; i < size; i++) {
4175                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4176            }
4177        }
4178        if (hasWebURI(intent)) {
4179            // cross-profile app linking works only towards the parent.
4180            final UserInfo parent = getProfileParent(sourceUserId);
4181            synchronized(mPackages) {
4182                return getCrossProfileDomainPreferredLpr(intent, resolvedType, 0, sourceUserId,
4183                        parent.id) != null;
4184            }
4185        }
4186        return false;
4187    }
4188
4189    private UserInfo getProfileParent(int userId) {
4190        final long identity = Binder.clearCallingIdentity();
4191        try {
4192            return sUserManager.getProfileParent(userId);
4193        } finally {
4194            Binder.restoreCallingIdentity(identity);
4195        }
4196    }
4197
4198    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4199            String resolvedType, int userId) {
4200        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4201        if (resolver != null) {
4202            return resolver.queryIntent(intent, resolvedType, false, userId);
4203        }
4204        return null;
4205    }
4206
4207    @Override
4208    public List<ResolveInfo> queryIntentActivities(Intent intent,
4209            String resolvedType, int flags, int userId) {
4210        if (!sUserManager.exists(userId)) return Collections.emptyList();
4211        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4212        ComponentName comp = intent.getComponent();
4213        if (comp == null) {
4214            if (intent.getSelector() != null) {
4215                intent = intent.getSelector();
4216                comp = intent.getComponent();
4217            }
4218        }
4219
4220        if (comp != null) {
4221            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4222            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4223            if (ai != null) {
4224                final ResolveInfo ri = new ResolveInfo();
4225                ri.activityInfo = ai;
4226                list.add(ri);
4227            }
4228            return list;
4229        }
4230
4231        // reader
4232        synchronized (mPackages) {
4233            final String pkgName = intent.getPackage();
4234            if (pkgName == null) {
4235                List<CrossProfileIntentFilter> matchingFilters =
4236                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4237                // Check for results that need to skip the current profile.
4238                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4239                        resolvedType, flags, userId);
4240                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4241                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4242                    result.add(xpResolveInfo);
4243                    return filterIfNotPrimaryUser(result, userId);
4244                }
4245
4246                // Check for results in the current profile.
4247                List<ResolveInfo> result = mActivities.queryIntent(
4248                        intent, resolvedType, flags, userId);
4249
4250                // Check for cross profile results.
4251                xpResolveInfo = queryCrossProfileIntents(
4252                        matchingFilters, intent, resolvedType, flags, userId);
4253                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4254                    result.add(xpResolveInfo);
4255                    Collections.sort(result, mResolvePrioritySorter);
4256                }
4257                result = filterIfNotPrimaryUser(result, userId);
4258                if (hasWebURI(intent)) {
4259                    CrossProfileDomainInfo xpDomainInfo = null;
4260                    final UserInfo parent = getProfileParent(userId);
4261                    if (parent != null) {
4262                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4263                                flags, userId, parent.id);
4264                    }
4265                    if (xpDomainInfo != null) {
4266                        if (xpResolveInfo != null) {
4267                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4268                            // in the result.
4269                            result.remove(xpResolveInfo);
4270                        }
4271                        if (result.size() == 0) {
4272                            result.add(xpDomainInfo.resolveInfo);
4273                            return result;
4274                        }
4275                    } else if (result.size() <= 1) {
4276                        return result;
4277                    }
4278                    result = filterCandidatesWithDomainPreferredActivitiesLPr(flags, result,
4279                            xpDomainInfo);
4280                    Collections.sort(result, mResolvePrioritySorter);
4281                }
4282                return result;
4283            }
4284            final PackageParser.Package pkg = mPackages.get(pkgName);
4285            if (pkg != null) {
4286                return filterIfNotPrimaryUser(
4287                        mActivities.queryIntentForPackage(
4288                                intent, resolvedType, flags, pkg.activities, userId),
4289                        userId);
4290            }
4291            return new ArrayList<ResolveInfo>();
4292        }
4293    }
4294
4295    private static class CrossProfileDomainInfo {
4296        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4297        ResolveInfo resolveInfo;
4298        /* Best domain verification status of the activities found in the other profile */
4299        int bestDomainVerificationStatus;
4300    }
4301
4302    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4303            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4304        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_APP_LINKING,
4305                sourceUserId)) {
4306            return null;
4307        }
4308        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4309                resolvedType, flags, parentUserId);
4310
4311        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4312            return null;
4313        }
4314        CrossProfileDomainInfo result = null;
4315        int size = resultTargetUser.size();
4316        for (int i = 0; i < size; i++) {
4317            ResolveInfo riTargetUser = resultTargetUser.get(i);
4318            // Intent filter verification is only for filters that specify a host. So don't return
4319            // those that handle all web uris.
4320            if (riTargetUser.handleAllWebDataURI) {
4321                continue;
4322            }
4323            String packageName = riTargetUser.activityInfo.packageName;
4324            PackageSetting ps = mSettings.mPackages.get(packageName);
4325            if (ps == null) {
4326                continue;
4327            }
4328            int status = getDomainVerificationStatusLPr(ps, parentUserId);
4329            if (result == null) {
4330                result = new CrossProfileDomainInfo();
4331                result.resolveInfo =
4332                        createForwardingResolveInfo(null, sourceUserId, parentUserId);
4333                result.bestDomainVerificationStatus = status;
4334            } else {
4335                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
4336                        result.bestDomainVerificationStatus);
4337            }
4338        }
4339        return result;
4340    }
4341
4342    /**
4343     * Verification statuses are ordered from the worse to the best, except for
4344     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
4345     */
4346    private int bestDomainVerificationStatus(int status1, int status2) {
4347        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4348            return status2;
4349        }
4350        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4351            return status1;
4352        }
4353        return (int) MathUtils.max(status1, status2);
4354    }
4355
4356    private boolean isUserEnabled(int userId) {
4357        long callingId = Binder.clearCallingIdentity();
4358        try {
4359            UserInfo userInfo = sUserManager.getUserInfo(userId);
4360            return userInfo != null && userInfo.isEnabled();
4361        } finally {
4362            Binder.restoreCallingIdentity(callingId);
4363        }
4364    }
4365
4366    /**
4367     * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
4368     *
4369     * @return filtered list
4370     */
4371    private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
4372        if (userId == UserHandle.USER_OWNER) {
4373            return resolveInfos;
4374        }
4375        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4376            ResolveInfo info = resolveInfos.get(i);
4377            if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
4378                resolveInfos.remove(i);
4379            }
4380        }
4381        return resolveInfos;
4382    }
4383
4384    private static boolean hasWebURI(Intent intent) {
4385        if (intent.getData() == null) {
4386            return false;
4387        }
4388        final String scheme = intent.getScheme();
4389        if (TextUtils.isEmpty(scheme)) {
4390            return false;
4391        }
4392        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4393    }
4394
4395    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(
4396            int flags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo) {
4397        if (DEBUG_PREFERRED) {
4398            Slog.v("TAG", "Filtering results with prefered activities. Candidates count: " +
4399                    candidates.size());
4400        }
4401
4402        final int userId = UserHandle.getCallingUserId();
4403        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4404        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
4405        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4406        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4407        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4408
4409        synchronized (mPackages) {
4410            final int count = candidates.size();
4411            // First, try to use the domain prefered App. Partition the candidates into four lists:
4412            // one for the final results, one for the "do not use ever", one for "undefined status"
4413            // and finally one for "Browser App type".
4414            for (int n=0; n<count; n++) {
4415                ResolveInfo info = candidates.get(n);
4416                String packageName = info.activityInfo.packageName;
4417                PackageSetting ps = mSettings.mPackages.get(packageName);
4418                if (ps != null) {
4419                    // Add to the special match all list (Browser use case)
4420                    if (info.handleAllWebDataURI) {
4421                        matchAllList.add(info);
4422                        continue;
4423                    }
4424                    // Try to get the status from User settings first
4425                    int status = getDomainVerificationStatusLPr(ps, userId);
4426                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4427                        alwaysList.add(info);
4428                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4429                        neverList.add(info);
4430                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
4431                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
4432                        undefinedList.add(info);
4433                    }
4434                }
4435            }
4436            // First try to add the "always" resolution for the current user if there is any
4437            if (alwaysList.size() > 0) {
4438                result.addAll(alwaysList);
4439            // if there is an "always" for the parent user, add it.
4440            } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus
4441                    == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4442                result.add(xpDomainInfo.resolveInfo);
4443            } else {
4444                // Add all undefined Apps as we want them to appear in the Disambiguation dialog.
4445                result.addAll(undefinedList);
4446                if (xpDomainInfo != null && (
4447                        xpDomainInfo.bestDomainVerificationStatus
4448                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
4449                        || xpDomainInfo.bestDomainVerificationStatus
4450                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) {
4451                    result.add(xpDomainInfo.resolveInfo);
4452                }
4453                // Also add Browsers (all of them or only the default one)
4454                if ((flags & MATCH_ALL) != 0) {
4455                    result.addAll(matchAllList);
4456                } else {
4457                    // Try to add the Default Browser if we can
4458                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(
4459                            UserHandle.myUserId());
4460                    if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
4461                        boolean defaultBrowserFound = false;
4462                        final int browserCount = matchAllList.size();
4463                        for (int n=0; n<browserCount; n++) {
4464                            ResolveInfo browser = matchAllList.get(n);
4465                            if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) {
4466                                result.add(browser);
4467                                defaultBrowserFound = true;
4468                                break;
4469                            }
4470                        }
4471                        if (!defaultBrowserFound) {
4472                            result.addAll(matchAllList);
4473                        }
4474                    } else {
4475                        result.addAll(matchAllList);
4476                    }
4477                }
4478
4479                // If there is nothing selected, add all candidates and remove the ones that the User
4480                // has explicitely put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
4481                if (result.size() == 0) {
4482                    result.addAll(candidates);
4483                    result.removeAll(neverList);
4484                }
4485            }
4486        }
4487        if (DEBUG_PREFERRED) {
4488            Slog.v("TAG", "Filtered results with prefered activities. New candidates count: " +
4489                    result.size());
4490        }
4491        return result;
4492    }
4493
4494    private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4495        int status = ps.getDomainVerificationStatusForUser(userId);
4496        // if none available, get the master status
4497        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4498            if (ps.getIntentFilterVerificationInfo() != null) {
4499                status = ps.getIntentFilterVerificationInfo().getStatus();
4500            }
4501        }
4502        return status;
4503    }
4504
4505    private ResolveInfo querySkipCurrentProfileIntents(
4506            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4507            int flags, int sourceUserId) {
4508        if (matchingFilters != null) {
4509            int size = matchingFilters.size();
4510            for (int i = 0; i < size; i ++) {
4511                CrossProfileIntentFilter filter = matchingFilters.get(i);
4512                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4513                    // Checking if there are activities in the target user that can handle the
4514                    // intent.
4515                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4516                            flags, sourceUserId);
4517                    if (resolveInfo != null) {
4518                        return resolveInfo;
4519                    }
4520                }
4521            }
4522        }
4523        return null;
4524    }
4525
4526    // Return matching ResolveInfo if any for skip current profile intent filters.
4527    private ResolveInfo queryCrossProfileIntents(
4528            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4529            int flags, int sourceUserId) {
4530        if (matchingFilters != null) {
4531            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4532            // match the same intent. For performance reasons, it is better not to
4533            // run queryIntent twice for the same userId
4534            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4535            int size = matchingFilters.size();
4536            for (int i = 0; i < size; i++) {
4537                CrossProfileIntentFilter filter = matchingFilters.get(i);
4538                int targetUserId = filter.getTargetUserId();
4539                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4540                        && !alreadyTriedUserIds.get(targetUserId)) {
4541                    // Checking if there are activities in the target user that can handle the
4542                    // intent.
4543                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4544                            flags, sourceUserId);
4545                    if (resolveInfo != null) return resolveInfo;
4546                    alreadyTriedUserIds.put(targetUserId, true);
4547                }
4548            }
4549        }
4550        return null;
4551    }
4552
4553    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
4554            String resolvedType, int flags, int sourceUserId) {
4555        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4556                resolvedType, flags, filter.getTargetUserId());
4557        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
4558            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
4559        }
4560        return null;
4561    }
4562
4563    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
4564            int sourceUserId, int targetUserId) {
4565        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4566        String className;
4567        if (targetUserId == UserHandle.USER_OWNER) {
4568            className = FORWARD_INTENT_TO_USER_OWNER;
4569        } else {
4570            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4571        }
4572        ComponentName forwardingActivityComponentName = new ComponentName(
4573                mAndroidApplication.packageName, className);
4574        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
4575                sourceUserId);
4576        if (targetUserId == UserHandle.USER_OWNER) {
4577            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
4578            forwardingResolveInfo.noResourceId = true;
4579        }
4580        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
4581        forwardingResolveInfo.priority = 0;
4582        forwardingResolveInfo.preferredOrder = 0;
4583        forwardingResolveInfo.match = 0;
4584        forwardingResolveInfo.isDefault = true;
4585        forwardingResolveInfo.filter = filter;
4586        forwardingResolveInfo.targetUserId = targetUserId;
4587        return forwardingResolveInfo;
4588    }
4589
4590    @Override
4591    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
4592            Intent[] specifics, String[] specificTypes, Intent intent,
4593            String resolvedType, int flags, int userId) {
4594        if (!sUserManager.exists(userId)) return Collections.emptyList();
4595        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
4596                false, "query intent activity options");
4597        final String resultsAction = intent.getAction();
4598
4599        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
4600                | PackageManager.GET_RESOLVED_FILTER, userId);
4601
4602        if (DEBUG_INTENT_MATCHING) {
4603            Log.v(TAG, "Query " + intent + ": " + results);
4604        }
4605
4606        int specificsPos = 0;
4607        int N;
4608
4609        // todo: note that the algorithm used here is O(N^2).  This
4610        // isn't a problem in our current environment, but if we start running
4611        // into situations where we have more than 5 or 10 matches then this
4612        // should probably be changed to something smarter...
4613
4614        // First we go through and resolve each of the specific items
4615        // that were supplied, taking care of removing any corresponding
4616        // duplicate items in the generic resolve list.
4617        if (specifics != null) {
4618            for (int i=0; i<specifics.length; i++) {
4619                final Intent sintent = specifics[i];
4620                if (sintent == null) {
4621                    continue;
4622                }
4623
4624                if (DEBUG_INTENT_MATCHING) {
4625                    Log.v(TAG, "Specific #" + i + ": " + sintent);
4626                }
4627
4628                String action = sintent.getAction();
4629                if (resultsAction != null && resultsAction.equals(action)) {
4630                    // If this action was explicitly requested, then don't
4631                    // remove things that have it.
4632                    action = null;
4633                }
4634
4635                ResolveInfo ri = null;
4636                ActivityInfo ai = null;
4637
4638                ComponentName comp = sintent.getComponent();
4639                if (comp == null) {
4640                    ri = resolveIntent(
4641                        sintent,
4642                        specificTypes != null ? specificTypes[i] : null,
4643                            flags, userId);
4644                    if (ri == null) {
4645                        continue;
4646                    }
4647                    if (ri == mResolveInfo) {
4648                        // ACK!  Must do something better with this.
4649                    }
4650                    ai = ri.activityInfo;
4651                    comp = new ComponentName(ai.applicationInfo.packageName,
4652                            ai.name);
4653                } else {
4654                    ai = getActivityInfo(comp, flags, userId);
4655                    if (ai == null) {
4656                        continue;
4657                    }
4658                }
4659
4660                // Look for any generic query activities that are duplicates
4661                // of this specific one, and remove them from the results.
4662                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
4663                N = results.size();
4664                int j;
4665                for (j=specificsPos; j<N; j++) {
4666                    ResolveInfo sri = results.get(j);
4667                    if ((sri.activityInfo.name.equals(comp.getClassName())
4668                            && sri.activityInfo.applicationInfo.packageName.equals(
4669                                    comp.getPackageName()))
4670                        || (action != null && sri.filter.matchAction(action))) {
4671                        results.remove(j);
4672                        if (DEBUG_INTENT_MATCHING) Log.v(
4673                            TAG, "Removing duplicate item from " + j
4674                            + " due to specific " + specificsPos);
4675                        if (ri == null) {
4676                            ri = sri;
4677                        }
4678                        j--;
4679                        N--;
4680                    }
4681                }
4682
4683                // Add this specific item to its proper place.
4684                if (ri == null) {
4685                    ri = new ResolveInfo();
4686                    ri.activityInfo = ai;
4687                }
4688                results.add(specificsPos, ri);
4689                ri.specificIndex = i;
4690                specificsPos++;
4691            }
4692        }
4693
4694        // Now we go through the remaining generic results and remove any
4695        // duplicate actions that are found here.
4696        N = results.size();
4697        for (int i=specificsPos; i<N-1; i++) {
4698            final ResolveInfo rii = results.get(i);
4699            if (rii.filter == null) {
4700                continue;
4701            }
4702
4703            // Iterate over all of the actions of this result's intent
4704            // filter...  typically this should be just one.
4705            final Iterator<String> it = rii.filter.actionsIterator();
4706            if (it == null) {
4707                continue;
4708            }
4709            while (it.hasNext()) {
4710                final String action = it.next();
4711                if (resultsAction != null && resultsAction.equals(action)) {
4712                    // If this action was explicitly requested, then don't
4713                    // remove things that have it.
4714                    continue;
4715                }
4716                for (int j=i+1; j<N; j++) {
4717                    final ResolveInfo rij = results.get(j);
4718                    if (rij.filter != null && rij.filter.hasAction(action)) {
4719                        results.remove(j);
4720                        if (DEBUG_INTENT_MATCHING) Log.v(
4721                            TAG, "Removing duplicate item from " + j
4722                            + " due to action " + action + " at " + i);
4723                        j--;
4724                        N--;
4725                    }
4726                }
4727            }
4728
4729            // If the caller didn't request filter information, drop it now
4730            // so we don't have to marshall/unmarshall it.
4731            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4732                rii.filter = null;
4733            }
4734        }
4735
4736        // Filter out the caller activity if so requested.
4737        if (caller != null) {
4738            N = results.size();
4739            for (int i=0; i<N; i++) {
4740                ActivityInfo ainfo = results.get(i).activityInfo;
4741                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
4742                        && caller.getClassName().equals(ainfo.name)) {
4743                    results.remove(i);
4744                    break;
4745                }
4746            }
4747        }
4748
4749        // If the caller didn't request filter information,
4750        // drop them now so we don't have to
4751        // marshall/unmarshall it.
4752        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4753            N = results.size();
4754            for (int i=0; i<N; i++) {
4755                results.get(i).filter = null;
4756            }
4757        }
4758
4759        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
4760        return results;
4761    }
4762
4763    @Override
4764    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
4765            int userId) {
4766        if (!sUserManager.exists(userId)) return Collections.emptyList();
4767        ComponentName comp = intent.getComponent();
4768        if (comp == null) {
4769            if (intent.getSelector() != null) {
4770                intent = intent.getSelector();
4771                comp = intent.getComponent();
4772            }
4773        }
4774        if (comp != null) {
4775            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4776            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
4777            if (ai != null) {
4778                ResolveInfo ri = new ResolveInfo();
4779                ri.activityInfo = ai;
4780                list.add(ri);
4781            }
4782            return list;
4783        }
4784
4785        // reader
4786        synchronized (mPackages) {
4787            String pkgName = intent.getPackage();
4788            if (pkgName == null) {
4789                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
4790            }
4791            final PackageParser.Package pkg = mPackages.get(pkgName);
4792            if (pkg != null) {
4793                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
4794                        userId);
4795            }
4796            return null;
4797        }
4798    }
4799
4800    @Override
4801    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
4802        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
4803        if (!sUserManager.exists(userId)) return null;
4804        if (query != null) {
4805            if (query.size() >= 1) {
4806                // If there is more than one service with the same priority,
4807                // just arbitrarily pick the first one.
4808                return query.get(0);
4809            }
4810        }
4811        return null;
4812    }
4813
4814    @Override
4815    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
4816            int userId) {
4817        if (!sUserManager.exists(userId)) return Collections.emptyList();
4818        ComponentName comp = intent.getComponent();
4819        if (comp == null) {
4820            if (intent.getSelector() != null) {
4821                intent = intent.getSelector();
4822                comp = intent.getComponent();
4823            }
4824        }
4825        if (comp != null) {
4826            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4827            final ServiceInfo si = getServiceInfo(comp, flags, userId);
4828            if (si != null) {
4829                final ResolveInfo ri = new ResolveInfo();
4830                ri.serviceInfo = si;
4831                list.add(ri);
4832            }
4833            return list;
4834        }
4835
4836        // reader
4837        synchronized (mPackages) {
4838            String pkgName = intent.getPackage();
4839            if (pkgName == null) {
4840                return mServices.queryIntent(intent, resolvedType, flags, userId);
4841            }
4842            final PackageParser.Package pkg = mPackages.get(pkgName);
4843            if (pkg != null) {
4844                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
4845                        userId);
4846            }
4847            return null;
4848        }
4849    }
4850
4851    @Override
4852    public List<ResolveInfo> queryIntentContentProviders(
4853            Intent intent, String resolvedType, int flags, int userId) {
4854        if (!sUserManager.exists(userId)) return Collections.emptyList();
4855        ComponentName comp = intent.getComponent();
4856        if (comp == null) {
4857            if (intent.getSelector() != null) {
4858                intent = intent.getSelector();
4859                comp = intent.getComponent();
4860            }
4861        }
4862        if (comp != null) {
4863            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4864            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
4865            if (pi != null) {
4866                final ResolveInfo ri = new ResolveInfo();
4867                ri.providerInfo = pi;
4868                list.add(ri);
4869            }
4870            return list;
4871        }
4872
4873        // reader
4874        synchronized (mPackages) {
4875            String pkgName = intent.getPackage();
4876            if (pkgName == null) {
4877                return mProviders.queryIntent(intent, resolvedType, flags, userId);
4878            }
4879            final PackageParser.Package pkg = mPackages.get(pkgName);
4880            if (pkg != null) {
4881                return mProviders.queryIntentForPackage(
4882                        intent, resolvedType, flags, pkg.providers, userId);
4883            }
4884            return null;
4885        }
4886    }
4887
4888    @Override
4889    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
4890        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4891
4892        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
4893
4894        // writer
4895        synchronized (mPackages) {
4896            ArrayList<PackageInfo> list;
4897            if (listUninstalled) {
4898                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
4899                for (PackageSetting ps : mSettings.mPackages.values()) {
4900                    PackageInfo pi;
4901                    if (ps.pkg != null) {
4902                        pi = generatePackageInfo(ps.pkg, flags, userId);
4903                    } else {
4904                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
4905                    }
4906                    if (pi != null) {
4907                        list.add(pi);
4908                    }
4909                }
4910            } else {
4911                list = new ArrayList<PackageInfo>(mPackages.size());
4912                for (PackageParser.Package p : mPackages.values()) {
4913                    PackageInfo pi = generatePackageInfo(p, flags, userId);
4914                    if (pi != null) {
4915                        list.add(pi);
4916                    }
4917                }
4918            }
4919
4920            return new ParceledListSlice<PackageInfo>(list);
4921        }
4922    }
4923
4924    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
4925            String[] permissions, boolean[] tmp, int flags, int userId) {
4926        int numMatch = 0;
4927        final PermissionsState permissionsState = ps.getPermissionsState();
4928        for (int i=0; i<permissions.length; i++) {
4929            final String permission = permissions[i];
4930            if (permissionsState.hasPermission(permission, userId)) {
4931                tmp[i] = true;
4932                numMatch++;
4933            } else {
4934                tmp[i] = false;
4935            }
4936        }
4937        if (numMatch == 0) {
4938            return;
4939        }
4940        PackageInfo pi;
4941        if (ps.pkg != null) {
4942            pi = generatePackageInfo(ps.pkg, flags, userId);
4943        } else {
4944            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
4945        }
4946        // The above might return null in cases of uninstalled apps or install-state
4947        // skew across users/profiles.
4948        if (pi != null) {
4949            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
4950                if (numMatch == permissions.length) {
4951                    pi.requestedPermissions = permissions;
4952                } else {
4953                    pi.requestedPermissions = new String[numMatch];
4954                    numMatch = 0;
4955                    for (int i=0; i<permissions.length; i++) {
4956                        if (tmp[i]) {
4957                            pi.requestedPermissions[numMatch] = permissions[i];
4958                            numMatch++;
4959                        }
4960                    }
4961                }
4962            }
4963            list.add(pi);
4964        }
4965    }
4966
4967    @Override
4968    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
4969            String[] permissions, int flags, int userId) {
4970        if (!sUserManager.exists(userId)) return null;
4971        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4972
4973        // writer
4974        synchronized (mPackages) {
4975            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
4976            boolean[] tmpBools = new boolean[permissions.length];
4977            if (listUninstalled) {
4978                for (PackageSetting ps : mSettings.mPackages.values()) {
4979                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
4980                }
4981            } else {
4982                for (PackageParser.Package pkg : mPackages.values()) {
4983                    PackageSetting ps = (PackageSetting)pkg.mExtras;
4984                    if (ps != null) {
4985                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
4986                                userId);
4987                    }
4988                }
4989            }
4990
4991            return new ParceledListSlice<PackageInfo>(list);
4992        }
4993    }
4994
4995    @Override
4996    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
4997        if (!sUserManager.exists(userId)) return null;
4998        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4999
5000        // writer
5001        synchronized (mPackages) {
5002            ArrayList<ApplicationInfo> list;
5003            if (listUninstalled) {
5004                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5005                for (PackageSetting ps : mSettings.mPackages.values()) {
5006                    ApplicationInfo ai;
5007                    if (ps.pkg != null) {
5008                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5009                                ps.readUserState(userId), userId);
5010                    } else {
5011                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5012                    }
5013                    if (ai != null) {
5014                        list.add(ai);
5015                    }
5016                }
5017            } else {
5018                list = new ArrayList<ApplicationInfo>(mPackages.size());
5019                for (PackageParser.Package p : mPackages.values()) {
5020                    if (p.mExtras != null) {
5021                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5022                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5023                        if (ai != null) {
5024                            list.add(ai);
5025                        }
5026                    }
5027                }
5028            }
5029
5030            return new ParceledListSlice<ApplicationInfo>(list);
5031        }
5032    }
5033
5034    public List<ApplicationInfo> getPersistentApplications(int flags) {
5035        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5036
5037        // reader
5038        synchronized (mPackages) {
5039            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5040            final int userId = UserHandle.getCallingUserId();
5041            while (i.hasNext()) {
5042                final PackageParser.Package p = i.next();
5043                if (p.applicationInfo != null
5044                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5045                        && (!mSafeMode || isSystemApp(p))) {
5046                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5047                    if (ps != null) {
5048                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5049                                ps.readUserState(userId), userId);
5050                        if (ai != null) {
5051                            finalList.add(ai);
5052                        }
5053                    }
5054                }
5055            }
5056        }
5057
5058        return finalList;
5059    }
5060
5061    @Override
5062    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5063        if (!sUserManager.exists(userId)) return null;
5064        // reader
5065        synchronized (mPackages) {
5066            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5067            PackageSetting ps = provider != null
5068                    ? mSettings.mPackages.get(provider.owner.packageName)
5069                    : null;
5070            return ps != null
5071                    && mSettings.isEnabledLPr(provider.info, flags, userId)
5072                    && (!mSafeMode || (provider.info.applicationInfo.flags
5073                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5074                    ? PackageParser.generateProviderInfo(provider, flags,
5075                            ps.readUserState(userId), userId)
5076                    : null;
5077        }
5078    }
5079
5080    /**
5081     * @deprecated
5082     */
5083    @Deprecated
5084    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5085        // reader
5086        synchronized (mPackages) {
5087            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5088                    .entrySet().iterator();
5089            final int userId = UserHandle.getCallingUserId();
5090            while (i.hasNext()) {
5091                Map.Entry<String, PackageParser.Provider> entry = i.next();
5092                PackageParser.Provider p = entry.getValue();
5093                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5094
5095                if (ps != null && p.syncable
5096                        && (!mSafeMode || (p.info.applicationInfo.flags
5097                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5098                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5099                            ps.readUserState(userId), userId);
5100                    if (info != null) {
5101                        outNames.add(entry.getKey());
5102                        outInfo.add(info);
5103                    }
5104                }
5105            }
5106        }
5107    }
5108
5109    @Override
5110    public List<ProviderInfo> queryContentProviders(String processName,
5111            int uid, int flags) {
5112        ArrayList<ProviderInfo> finalList = null;
5113        // reader
5114        synchronized (mPackages) {
5115            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5116            final int userId = processName != null ?
5117                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
5118            while (i.hasNext()) {
5119                final PackageParser.Provider p = i.next();
5120                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5121                if (ps != null && p.info.authority != null
5122                        && (processName == null
5123                                || (p.info.processName.equals(processName)
5124                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5125                        && mSettings.isEnabledLPr(p.info, flags, userId)
5126                        && (!mSafeMode
5127                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5128                    if (finalList == null) {
5129                        finalList = new ArrayList<ProviderInfo>(3);
5130                    }
5131                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5132                            ps.readUserState(userId), userId);
5133                    if (info != null) {
5134                        finalList.add(info);
5135                    }
5136                }
5137            }
5138        }
5139
5140        if (finalList != null) {
5141            Collections.sort(finalList, mProviderInitOrderSorter);
5142        }
5143
5144        return finalList;
5145    }
5146
5147    @Override
5148    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
5149            int flags) {
5150        // reader
5151        synchronized (mPackages) {
5152            final PackageParser.Instrumentation i = mInstrumentation.get(name);
5153            return PackageParser.generateInstrumentationInfo(i, flags);
5154        }
5155    }
5156
5157    @Override
5158    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
5159            int flags) {
5160        ArrayList<InstrumentationInfo> finalList =
5161            new ArrayList<InstrumentationInfo>();
5162
5163        // reader
5164        synchronized (mPackages) {
5165            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
5166            while (i.hasNext()) {
5167                final PackageParser.Instrumentation p = i.next();
5168                if (targetPackage == null
5169                        || targetPackage.equals(p.info.targetPackage)) {
5170                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
5171                            flags);
5172                    if (ii != null) {
5173                        finalList.add(ii);
5174                    }
5175                }
5176            }
5177        }
5178
5179        return finalList;
5180    }
5181
5182    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
5183        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
5184        if (overlays == null) {
5185            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
5186            return;
5187        }
5188        for (PackageParser.Package opkg : overlays.values()) {
5189            // Not much to do if idmap fails: we already logged the error
5190            // and we certainly don't want to abort installation of pkg simply
5191            // because an overlay didn't fit properly. For these reasons,
5192            // ignore the return value of createIdmapForPackagePairLI.
5193            createIdmapForPackagePairLI(pkg, opkg);
5194        }
5195    }
5196
5197    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
5198            PackageParser.Package opkg) {
5199        if (!opkg.mTrustedOverlay) {
5200            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
5201                    opkg.baseCodePath + ": overlay not trusted");
5202            return false;
5203        }
5204        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
5205        if (overlaySet == null) {
5206            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
5207                    opkg.baseCodePath + " but target package has no known overlays");
5208            return false;
5209        }
5210        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
5211        // TODO: generate idmap for split APKs
5212        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
5213            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
5214                    + opkg.baseCodePath);
5215            return false;
5216        }
5217        PackageParser.Package[] overlayArray =
5218            overlaySet.values().toArray(new PackageParser.Package[0]);
5219        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
5220            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
5221                return p1.mOverlayPriority - p2.mOverlayPriority;
5222            }
5223        };
5224        Arrays.sort(overlayArray, cmp);
5225
5226        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5227        int i = 0;
5228        for (PackageParser.Package p : overlayArray) {
5229            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5230        }
5231        return true;
5232    }
5233
5234    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5235        final File[] files = dir.listFiles();
5236        if (ArrayUtils.isEmpty(files)) {
5237            Log.d(TAG, "No files in app dir " + dir);
5238            return;
5239        }
5240
5241        if (DEBUG_PACKAGE_SCANNING) {
5242            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
5243                    + " flags=0x" + Integer.toHexString(parseFlags));
5244        }
5245
5246        for (File file : files) {
5247            final boolean isPackage = (isApkFile(file) || file.isDirectory())
5248                    && !PackageInstallerService.isStageName(file.getName());
5249            if (!isPackage) {
5250                // Ignore entries which are not packages
5251                continue;
5252            }
5253            try {
5254                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
5255                        scanFlags, currentTime, null);
5256            } catch (PackageManagerException e) {
5257                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
5258
5259                // Delete invalid userdata apps
5260                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
5261                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
5262                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
5263                    if (file.isDirectory()) {
5264                        mInstaller.rmPackageDir(file.getAbsolutePath());
5265                    } else {
5266                        file.delete();
5267                    }
5268                }
5269            }
5270        }
5271    }
5272
5273    private static File getSettingsProblemFile() {
5274        File dataDir = Environment.getDataDirectory();
5275        File systemDir = new File(dataDir, "system");
5276        File fname = new File(systemDir, "uiderrors.txt");
5277        return fname;
5278    }
5279
5280    static void reportSettingsProblem(int priority, String msg) {
5281        logCriticalInfo(priority, msg);
5282    }
5283
5284    static void logCriticalInfo(int priority, String msg) {
5285        Slog.println(priority, TAG, msg);
5286        EventLogTags.writePmCriticalInfo(msg);
5287        try {
5288            File fname = getSettingsProblemFile();
5289            FileOutputStream out = new FileOutputStream(fname, true);
5290            PrintWriter pw = new FastPrintWriter(out);
5291            SimpleDateFormat formatter = new SimpleDateFormat();
5292            String dateString = formatter.format(new Date(System.currentTimeMillis()));
5293            pw.println(dateString + ": " + msg);
5294            pw.close();
5295            FileUtils.setPermissions(
5296                    fname.toString(),
5297                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5298                    -1, -1);
5299        } catch (java.io.IOException e) {
5300        }
5301    }
5302
5303    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5304            PackageParser.Package pkg, File srcFile, int parseFlags)
5305            throws PackageManagerException {
5306        if (ps != null
5307                && ps.codePath.equals(srcFile)
5308                && ps.timeStamp == srcFile.lastModified()
5309                && !isCompatSignatureUpdateNeeded(pkg)
5310                && !isRecoverSignatureUpdateNeeded(pkg)) {
5311            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5312            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5313            ArraySet<PublicKey> signingKs;
5314            synchronized (mPackages) {
5315                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
5316            }
5317            if (ps.signatures.mSignatures != null
5318                    && ps.signatures.mSignatures.length != 0
5319                    && signingKs != null) {
5320                // Optimization: reuse the existing cached certificates
5321                // if the package appears to be unchanged.
5322                pkg.mSignatures = ps.signatures.mSignatures;
5323                pkg.mSigningKeys = signingKs;
5324                return;
5325            }
5326
5327            Slog.w(TAG, "PackageSetting for " + ps.name
5328                    + " is missing signatures.  Collecting certs again to recover them.");
5329        } else {
5330            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
5331        }
5332
5333        try {
5334            pp.collectCertificates(pkg, parseFlags);
5335            pp.collectManifestDigest(pkg);
5336        } catch (PackageParserException e) {
5337            throw PackageManagerException.from(e);
5338        }
5339    }
5340
5341    /*
5342     *  Scan a package and return the newly parsed package.
5343     *  Returns null in case of errors and the error code is stored in mLastScanError
5344     */
5345    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
5346            long currentTime, UserHandle user) throws PackageManagerException {
5347        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
5348        parseFlags |= mDefParseFlags;
5349        PackageParser pp = new PackageParser();
5350        pp.setSeparateProcesses(mSeparateProcesses);
5351        pp.setOnlyCoreApps(mOnlyCore);
5352        pp.setDisplayMetrics(mMetrics);
5353
5354        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
5355            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
5356        }
5357
5358        final PackageParser.Package pkg;
5359        try {
5360            pkg = pp.parsePackage(scanFile, parseFlags);
5361        } catch (PackageParserException e) {
5362            throw PackageManagerException.from(e);
5363        }
5364
5365        PackageSetting ps = null;
5366        PackageSetting updatedPkg;
5367        // reader
5368        synchronized (mPackages) {
5369            // Look to see if we already know about this package.
5370            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
5371            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
5372                // This package has been renamed to its original name.  Let's
5373                // use that.
5374                ps = mSettings.peekPackageLPr(oldName);
5375            }
5376            // If there was no original package, see one for the real package name.
5377            if (ps == null) {
5378                ps = mSettings.peekPackageLPr(pkg.packageName);
5379            }
5380            // Check to see if this package could be hiding/updating a system
5381            // package.  Must look for it either under the original or real
5382            // package name depending on our state.
5383            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
5384            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
5385        }
5386        boolean updatedPkgBetter = false;
5387        // First check if this is a system package that may involve an update
5388        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5389            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
5390            // it needs to drop FLAG_PRIVILEGED.
5391            if (locationIsPrivileged(scanFile)) {
5392                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5393            } else {
5394                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5395            }
5396
5397            if (ps != null && !ps.codePath.equals(scanFile)) {
5398                // The path has changed from what was last scanned...  check the
5399                // version of the new path against what we have stored to determine
5400                // what to do.
5401                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
5402                if (pkg.mVersionCode <= ps.versionCode) {
5403                    // The system package has been updated and the code path does not match
5404                    // Ignore entry. Skip it.
5405                    Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5406                            + " ignored: updated version " + ps.versionCode
5407                            + " better than this " + pkg.mVersionCode);
5408                    if (!updatedPkg.codePath.equals(scanFile)) {
5409                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5410                                + ps.name + " changing from " + updatedPkg.codePathString
5411                                + " to " + scanFile);
5412                        updatedPkg.codePath = scanFile;
5413                        updatedPkg.codePathString = scanFile.toString();
5414                        updatedPkg.resourcePath = scanFile;
5415                        updatedPkg.resourcePathString = scanFile.toString();
5416                    }
5417                    updatedPkg.pkg = pkg;
5418                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null);
5419                } else {
5420                    // The current app on the system partition is better than
5421                    // what we have updated to on the data partition; switch
5422                    // back to the system partition version.
5423                    // At this point, its safely assumed that package installation for
5424                    // apps in system partition will go through. If not there won't be a working
5425                    // version of the app
5426                    // writer
5427                    synchronized (mPackages) {
5428                        // Just remove the loaded entries from package lists.
5429                        mPackages.remove(ps.name);
5430                    }
5431
5432                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5433                            + " reverting from " + ps.codePathString
5434                            + ": new version " + pkg.mVersionCode
5435                            + " better than installed " + ps.versionCode);
5436
5437                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5438                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5439                    synchronized (mInstallLock) {
5440                        args.cleanUpResourcesLI();
5441                    }
5442                    synchronized (mPackages) {
5443                        mSettings.enableSystemPackageLPw(ps.name);
5444                    }
5445                    updatedPkgBetter = true;
5446                }
5447            }
5448        }
5449
5450        if (updatedPkg != null) {
5451            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5452            // initially
5453            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5454
5455            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5456            // flag set initially
5457            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5458                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5459            }
5460        }
5461
5462        // Verify certificates against what was last scanned
5463        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5464
5465        /*
5466         * A new system app appeared, but we already had a non-system one of the
5467         * same name installed earlier.
5468         */
5469        boolean shouldHideSystemApp = false;
5470        if (updatedPkg == null && ps != null
5471                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5472            /*
5473             * Check to make sure the signatures match first. If they don't,
5474             * wipe the installed application and its data.
5475             */
5476            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5477                    != PackageManager.SIGNATURE_MATCH) {
5478                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5479                        + " signatures don't match existing userdata copy; removing");
5480                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5481                ps = null;
5482            } else {
5483                /*
5484                 * If the newly-added system app is an older version than the
5485                 * already installed version, hide it. It will be scanned later
5486                 * and re-added like an update.
5487                 */
5488                if (pkg.mVersionCode <= ps.versionCode) {
5489                    shouldHideSystemApp = true;
5490                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5491                            + " but new version " + pkg.mVersionCode + " better than installed "
5492                            + ps.versionCode + "; hiding system");
5493                } else {
5494                    /*
5495                     * The newly found system app is a newer version that the
5496                     * one previously installed. Simply remove the
5497                     * already-installed application and replace it with our own
5498                     * while keeping the application data.
5499                     */
5500                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5501                            + " reverting from " + ps.codePathString + ": new version "
5502                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5503                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5504                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5505                    synchronized (mInstallLock) {
5506                        args.cleanUpResourcesLI();
5507                    }
5508                }
5509            }
5510        }
5511
5512        // The apk is forward locked (not public) if its code and resources
5513        // are kept in different files. (except for app in either system or
5514        // vendor path).
5515        // TODO grab this value from PackageSettings
5516        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5517            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5518                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5519            }
5520        }
5521
5522        // TODO: extend to support forward-locked splits
5523        String resourcePath = null;
5524        String baseResourcePath = null;
5525        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5526            if (ps != null && ps.resourcePathString != null) {
5527                resourcePath = ps.resourcePathString;
5528                baseResourcePath = ps.resourcePathString;
5529            } else {
5530                // Should not happen at all. Just log an error.
5531                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5532            }
5533        } else {
5534            resourcePath = pkg.codePath;
5535            baseResourcePath = pkg.baseCodePath;
5536        }
5537
5538        // Set application objects path explicitly.
5539        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
5540        pkg.applicationInfo.setCodePath(pkg.codePath);
5541        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5542        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5543        pkg.applicationInfo.setResourcePath(resourcePath);
5544        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5545        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5546
5547        // Note that we invoke the following method only if we are about to unpack an application
5548        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5549                | SCAN_UPDATE_SIGNATURE, currentTime, user);
5550
5551        /*
5552         * If the system app should be overridden by a previously installed
5553         * data, hide the system app now and let the /data/app scan pick it up
5554         * again.
5555         */
5556        if (shouldHideSystemApp) {
5557            synchronized (mPackages) {
5558                /*
5559                 * We have to grant systems permissions before we hide, because
5560                 * grantPermissions will assume the package update is trying to
5561                 * expand its permissions.
5562                 */
5563                grantPermissionsLPw(pkg, true, pkg.packageName);
5564                mSettings.disableSystemPackageLPw(pkg.packageName);
5565            }
5566        }
5567
5568        return scannedPkg;
5569    }
5570
5571    private static String fixProcessName(String defProcessName,
5572            String processName, int uid) {
5573        if (processName == null) {
5574            return defProcessName;
5575        }
5576        return processName;
5577    }
5578
5579    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
5580            throws PackageManagerException {
5581        if (pkgSetting.signatures.mSignatures != null) {
5582            // Already existing package. Make sure signatures match
5583            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
5584                    == PackageManager.SIGNATURE_MATCH;
5585            if (!match) {
5586                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
5587                        == PackageManager.SIGNATURE_MATCH;
5588            }
5589            if (!match) {
5590                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
5591                        == PackageManager.SIGNATURE_MATCH;
5592            }
5593            if (!match) {
5594                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5595                        + pkg.packageName + " signatures do not match the "
5596                        + "previously installed version; ignoring!");
5597            }
5598        }
5599
5600        // Check for shared user signatures
5601        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
5602            // Already existing package. Make sure signatures match
5603            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5604                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
5605            if (!match) {
5606                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
5607                        == PackageManager.SIGNATURE_MATCH;
5608            }
5609            if (!match) {
5610                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
5611                        == PackageManager.SIGNATURE_MATCH;
5612            }
5613            if (!match) {
5614                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
5615                        "Package " + pkg.packageName
5616                        + " has no signatures that match those in shared user "
5617                        + pkgSetting.sharedUser.name + "; ignoring!");
5618            }
5619        }
5620    }
5621
5622    /**
5623     * Enforces that only the system UID or root's UID can call a method exposed
5624     * via Binder.
5625     *
5626     * @param message used as message if SecurityException is thrown
5627     * @throws SecurityException if the caller is not system or root
5628     */
5629    private static final void enforceSystemOrRoot(String message) {
5630        final int uid = Binder.getCallingUid();
5631        if (uid != Process.SYSTEM_UID && uid != 0) {
5632            throw new SecurityException(message);
5633        }
5634    }
5635
5636    @Override
5637    public void performBootDexOpt() {
5638        enforceSystemOrRoot("Only the system can request dexopt be performed");
5639
5640        // Before everything else, see whether we need to fstrim.
5641        try {
5642            IMountService ms = PackageHelper.getMountService();
5643            if (ms != null) {
5644                final boolean isUpgrade = isUpgrade();
5645                boolean doTrim = isUpgrade;
5646                if (doTrim) {
5647                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
5648                } else {
5649                    final long interval = android.provider.Settings.Global.getLong(
5650                            mContext.getContentResolver(),
5651                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
5652                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
5653                    if (interval > 0) {
5654                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
5655                        if (timeSinceLast > interval) {
5656                            doTrim = true;
5657                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
5658                                    + "; running immediately");
5659                        }
5660                    }
5661                }
5662                if (doTrim) {
5663                    if (!isFirstBoot()) {
5664                        try {
5665                            ActivityManagerNative.getDefault().showBootMessage(
5666                                    mContext.getResources().getString(
5667                                            R.string.android_upgrading_fstrim), true);
5668                        } catch (RemoteException e) {
5669                        }
5670                    }
5671                    ms.runMaintenance();
5672                }
5673            } else {
5674                Slog.e(TAG, "Mount service unavailable!");
5675            }
5676        } catch (RemoteException e) {
5677            // Can't happen; MountService is local
5678        }
5679
5680        final ArraySet<PackageParser.Package> pkgs;
5681        synchronized (mPackages) {
5682            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
5683        }
5684
5685        if (pkgs != null) {
5686            // Sort apps by importance for dexopt ordering. Important apps are given more priority
5687            // in case the device runs out of space.
5688            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
5689            // Give priority to core apps.
5690            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5691                PackageParser.Package pkg = it.next();
5692                if (pkg.coreApp) {
5693                    if (DEBUG_DEXOPT) {
5694                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
5695                    }
5696                    sortedPkgs.add(pkg);
5697                    it.remove();
5698                }
5699            }
5700            // Give priority to system apps that listen for pre boot complete.
5701            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
5702            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
5703            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5704                PackageParser.Package pkg = it.next();
5705                if (pkgNames.contains(pkg.packageName)) {
5706                    if (DEBUG_DEXOPT) {
5707                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
5708                    }
5709                    sortedPkgs.add(pkg);
5710                    it.remove();
5711                }
5712            }
5713            // Give priority to system apps.
5714            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5715                PackageParser.Package pkg = it.next();
5716                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
5717                    if (DEBUG_DEXOPT) {
5718                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
5719                    }
5720                    sortedPkgs.add(pkg);
5721                    it.remove();
5722                }
5723            }
5724            // Give priority to updated system apps.
5725            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5726                PackageParser.Package pkg = it.next();
5727                if (pkg.isUpdatedSystemApp()) {
5728                    if (DEBUG_DEXOPT) {
5729                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
5730                    }
5731                    sortedPkgs.add(pkg);
5732                    it.remove();
5733                }
5734            }
5735            // Give priority to apps that listen for boot complete.
5736            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
5737            pkgNames = getPackageNamesForIntent(intent);
5738            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5739                PackageParser.Package pkg = it.next();
5740                if (pkgNames.contains(pkg.packageName)) {
5741                    if (DEBUG_DEXOPT) {
5742                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
5743                    }
5744                    sortedPkgs.add(pkg);
5745                    it.remove();
5746                }
5747            }
5748            // Filter out packages that aren't recently used.
5749            filterRecentlyUsedApps(pkgs);
5750            // Add all remaining apps.
5751            for (PackageParser.Package pkg : pkgs) {
5752                if (DEBUG_DEXOPT) {
5753                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
5754                }
5755                sortedPkgs.add(pkg);
5756            }
5757
5758            // If we want to be lazy, filter everything that wasn't recently used.
5759            if (mLazyDexOpt) {
5760                filterRecentlyUsedApps(sortedPkgs);
5761            }
5762
5763            int i = 0;
5764            int total = sortedPkgs.size();
5765            File dataDir = Environment.getDataDirectory();
5766            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
5767            if (lowThreshold == 0) {
5768                throw new IllegalStateException("Invalid low memory threshold");
5769            }
5770            for (PackageParser.Package pkg : sortedPkgs) {
5771                long usableSpace = dataDir.getUsableSpace();
5772                if (usableSpace < lowThreshold) {
5773                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
5774                    break;
5775                }
5776                performBootDexOpt(pkg, ++i, total);
5777            }
5778        }
5779    }
5780
5781    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
5782        // Filter out packages that aren't recently used.
5783        //
5784        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
5785        // should do a full dexopt.
5786        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
5787            int total = pkgs.size();
5788            int skipped = 0;
5789            long now = System.currentTimeMillis();
5790            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
5791                PackageParser.Package pkg = i.next();
5792                long then = pkg.mLastPackageUsageTimeInMills;
5793                if (then + mDexOptLRUThresholdInMills < now) {
5794                    if (DEBUG_DEXOPT) {
5795                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
5796                              ((then == 0) ? "never" : new Date(then)));
5797                    }
5798                    i.remove();
5799                    skipped++;
5800                }
5801            }
5802            if (DEBUG_DEXOPT) {
5803                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
5804            }
5805        }
5806    }
5807
5808    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
5809        List<ResolveInfo> ris = null;
5810        try {
5811            ris = AppGlobals.getPackageManager().queryIntentReceivers(
5812                    intent, null, 0, UserHandle.USER_OWNER);
5813        } catch (RemoteException e) {
5814        }
5815        ArraySet<String> pkgNames = new ArraySet<String>();
5816        if (ris != null) {
5817            for (ResolveInfo ri : ris) {
5818                pkgNames.add(ri.activityInfo.packageName);
5819            }
5820        }
5821        return pkgNames;
5822    }
5823
5824    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
5825        if (DEBUG_DEXOPT) {
5826            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
5827        }
5828        if (!isFirstBoot()) {
5829            try {
5830                ActivityManagerNative.getDefault().showBootMessage(
5831                        mContext.getResources().getString(R.string.android_upgrading_apk,
5832                                curr, total), true);
5833            } catch (RemoteException e) {
5834            }
5835        }
5836        PackageParser.Package p = pkg;
5837        synchronized (mInstallLock) {
5838            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
5839                    false /* force dex */, false /* defer */, true /* include dependencies */);
5840        }
5841    }
5842
5843    @Override
5844    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
5845        return performDexOpt(packageName, instructionSet, false);
5846    }
5847
5848    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
5849        boolean dexopt = mLazyDexOpt || backgroundDexopt;
5850        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
5851        if (!dexopt && !updateUsage) {
5852            // We aren't going to dexopt or update usage, so bail early.
5853            return false;
5854        }
5855        PackageParser.Package p;
5856        final String targetInstructionSet;
5857        synchronized (mPackages) {
5858            p = mPackages.get(packageName);
5859            if (p == null) {
5860                return false;
5861            }
5862            if (updateUsage) {
5863                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
5864            }
5865            mPackageUsage.write(false);
5866            if (!dexopt) {
5867                // We aren't going to dexopt, so bail early.
5868                return false;
5869            }
5870
5871            targetInstructionSet = instructionSet != null ? instructionSet :
5872                    getPrimaryInstructionSet(p.applicationInfo);
5873            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
5874                return false;
5875            }
5876        }
5877
5878        synchronized (mInstallLock) {
5879            final String[] instructionSets = new String[] { targetInstructionSet };
5880            int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
5881                    false /* forceDex */, false /* defer */, true /* inclDependencies */);
5882            return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
5883        }
5884    }
5885
5886    public ArraySet<String> getPackagesThatNeedDexOpt() {
5887        ArraySet<String> pkgs = null;
5888        synchronized (mPackages) {
5889            for (PackageParser.Package p : mPackages.values()) {
5890                if (DEBUG_DEXOPT) {
5891                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
5892                }
5893                if (!p.mDexOptPerformed.isEmpty()) {
5894                    continue;
5895                }
5896                if (pkgs == null) {
5897                    pkgs = new ArraySet<String>();
5898                }
5899                pkgs.add(p.packageName);
5900            }
5901        }
5902        return pkgs;
5903    }
5904
5905    public void shutdown() {
5906        mPackageUsage.write(true);
5907    }
5908
5909    @Override
5910    public void forceDexOpt(String packageName) {
5911        enforceSystemOrRoot("forceDexOpt");
5912
5913        PackageParser.Package pkg;
5914        synchronized (mPackages) {
5915            pkg = mPackages.get(packageName);
5916            if (pkg == null) {
5917                throw new IllegalArgumentException("Missing package: " + packageName);
5918            }
5919        }
5920
5921        synchronized (mInstallLock) {
5922            final String[] instructionSets = new String[] {
5923                    getPrimaryInstructionSet(pkg.applicationInfo) };
5924            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
5925                    true /*forceDex*/, false /* defer */, true /* inclDependencies */);
5926            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
5927                throw new IllegalStateException("Failed to dexopt: " + res);
5928            }
5929        }
5930    }
5931
5932    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
5933        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
5934            Slog.w(TAG, "Unable to update from " + oldPkg.name
5935                    + " to " + newPkg.packageName
5936                    + ": old package not in system partition");
5937            return false;
5938        } else if (mPackages.get(oldPkg.name) != null) {
5939            Slog.w(TAG, "Unable to update from " + oldPkg.name
5940                    + " to " + newPkg.packageName
5941                    + ": old package still exists");
5942            return false;
5943        }
5944        return true;
5945    }
5946
5947    private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
5948        int[] users = sUserManager.getUserIds();
5949        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
5950        if (res < 0) {
5951            return res;
5952        }
5953        for (int user : users) {
5954            if (user != 0) {
5955                res = mInstaller.createUserData(volumeUuid, packageName,
5956                        UserHandle.getUid(user, uid), user, seinfo);
5957                if (res < 0) {
5958                    return res;
5959                }
5960            }
5961        }
5962        return res;
5963    }
5964
5965    private int removeDataDirsLI(String volumeUuid, String packageName) {
5966        int[] users = sUserManager.getUserIds();
5967        int res = 0;
5968        for (int user : users) {
5969            int resInner = mInstaller.remove(volumeUuid, packageName, user);
5970            if (resInner < 0) {
5971                res = resInner;
5972            }
5973        }
5974
5975        return res;
5976    }
5977
5978    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
5979        int[] users = sUserManager.getUserIds();
5980        int res = 0;
5981        for (int user : users) {
5982            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
5983            if (resInner < 0) {
5984                res = resInner;
5985            }
5986        }
5987        return res;
5988    }
5989
5990    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
5991            PackageParser.Package changingLib) {
5992        if (file.path != null) {
5993            usesLibraryFiles.add(file.path);
5994            return;
5995        }
5996        PackageParser.Package p = mPackages.get(file.apk);
5997        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
5998            // If we are doing this while in the middle of updating a library apk,
5999            // then we need to make sure to use that new apk for determining the
6000            // dependencies here.  (We haven't yet finished committing the new apk
6001            // to the package manager state.)
6002            if (p == null || p.packageName.equals(changingLib.packageName)) {
6003                p = changingLib;
6004            }
6005        }
6006        if (p != null) {
6007            usesLibraryFiles.addAll(p.getAllCodePaths());
6008        }
6009    }
6010
6011    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6012            PackageParser.Package changingLib) throws PackageManagerException {
6013        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6014            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6015            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6016            for (int i=0; i<N; i++) {
6017                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6018                if (file == null) {
6019                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6020                            "Package " + pkg.packageName + " requires unavailable shared library "
6021                            + pkg.usesLibraries.get(i) + "; failing!");
6022                }
6023                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6024            }
6025            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6026            for (int i=0; i<N; i++) {
6027                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6028                if (file == null) {
6029                    Slog.w(TAG, "Package " + pkg.packageName
6030                            + " desires unavailable shared library "
6031                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6032                } else {
6033                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6034                }
6035            }
6036            N = usesLibraryFiles.size();
6037            if (N > 0) {
6038                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6039            } else {
6040                pkg.usesLibraryFiles = null;
6041            }
6042        }
6043    }
6044
6045    private static boolean hasString(List<String> list, List<String> which) {
6046        if (list == null) {
6047            return false;
6048        }
6049        for (int i=list.size()-1; i>=0; i--) {
6050            for (int j=which.size()-1; j>=0; j--) {
6051                if (which.get(j).equals(list.get(i))) {
6052                    return true;
6053                }
6054            }
6055        }
6056        return false;
6057    }
6058
6059    private void updateAllSharedLibrariesLPw() {
6060        for (PackageParser.Package pkg : mPackages.values()) {
6061            try {
6062                updateSharedLibrariesLPw(pkg, null);
6063            } catch (PackageManagerException e) {
6064                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6065            }
6066        }
6067    }
6068
6069    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6070            PackageParser.Package changingPkg) {
6071        ArrayList<PackageParser.Package> res = null;
6072        for (PackageParser.Package pkg : mPackages.values()) {
6073            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6074                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6075                if (res == null) {
6076                    res = new ArrayList<PackageParser.Package>();
6077                }
6078                res.add(pkg);
6079                try {
6080                    updateSharedLibrariesLPw(pkg, changingPkg);
6081                } catch (PackageManagerException e) {
6082                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6083                }
6084            }
6085        }
6086        return res;
6087    }
6088
6089    /**
6090     * Derive the value of the {@code cpuAbiOverride} based on the provided
6091     * value and an optional stored value from the package settings.
6092     */
6093    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6094        String cpuAbiOverride = null;
6095
6096        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6097            cpuAbiOverride = null;
6098        } else if (abiOverride != null) {
6099            cpuAbiOverride = abiOverride;
6100        } else if (settings != null) {
6101            cpuAbiOverride = settings.cpuAbiOverrideString;
6102        }
6103
6104        return cpuAbiOverride;
6105    }
6106
6107    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6108            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6109        boolean success = false;
6110        try {
6111            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6112                    currentTime, user);
6113            success = true;
6114            return res;
6115        } finally {
6116            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6117                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6118            }
6119        }
6120    }
6121
6122    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6123            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6124        final File scanFile = new File(pkg.codePath);
6125        if (pkg.applicationInfo.getCodePath() == null ||
6126                pkg.applicationInfo.getResourcePath() == null) {
6127            // Bail out. The resource and code paths haven't been set.
6128            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6129                    "Code and resource paths haven't been set correctly");
6130        }
6131
6132        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6133            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6134        } else {
6135            // Only allow system apps to be flagged as core apps.
6136            pkg.coreApp = false;
6137        }
6138
6139        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6140            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6141        }
6142
6143        if (mCustomResolverComponentName != null &&
6144                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6145            setUpCustomResolverActivity(pkg);
6146        }
6147
6148        if (pkg.packageName.equals("android")) {
6149            synchronized (mPackages) {
6150                if (mAndroidApplication != null) {
6151                    Slog.w(TAG, "*************************************************");
6152                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6153                    Slog.w(TAG, " file=" + scanFile);
6154                    Slog.w(TAG, "*************************************************");
6155                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6156                            "Core android package being redefined.  Skipping.");
6157                }
6158
6159                // Set up information for our fall-back user intent resolution activity.
6160                mPlatformPackage = pkg;
6161                pkg.mVersionCode = mSdkVersion;
6162                mAndroidApplication = pkg.applicationInfo;
6163
6164                if (!mResolverReplaced) {
6165                    mResolveActivity.applicationInfo = mAndroidApplication;
6166                    mResolveActivity.name = ResolverActivity.class.getName();
6167                    mResolveActivity.packageName = mAndroidApplication.packageName;
6168                    mResolveActivity.processName = "system:ui";
6169                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6170                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6171                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6172                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6173                    mResolveActivity.exported = true;
6174                    mResolveActivity.enabled = true;
6175                    mResolveInfo.activityInfo = mResolveActivity;
6176                    mResolveInfo.priority = 0;
6177                    mResolveInfo.preferredOrder = 0;
6178                    mResolveInfo.match = 0;
6179                    mResolveComponentName = new ComponentName(
6180                            mAndroidApplication.packageName, mResolveActivity.name);
6181                }
6182            }
6183        }
6184
6185        if (DEBUG_PACKAGE_SCANNING) {
6186            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6187                Log.d(TAG, "Scanning package " + pkg.packageName);
6188        }
6189
6190        if (mPackages.containsKey(pkg.packageName)
6191                || mSharedLibraries.containsKey(pkg.packageName)) {
6192            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6193                    "Application package " + pkg.packageName
6194                    + " already installed.  Skipping duplicate.");
6195        }
6196
6197        // If we're only installing presumed-existing packages, require that the
6198        // scanned APK is both already known and at the path previously established
6199        // for it.  Previously unknown packages we pick up normally, but if we have an
6200        // a priori expectation about this package's install presence, enforce it.
6201        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6202            PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6203            if (known != null) {
6204                if (DEBUG_PACKAGE_SCANNING) {
6205                    Log.d(TAG, "Examining " + pkg.codePath
6206                            + " and requiring known paths " + known.codePathString
6207                            + " & " + known.resourcePathString);
6208                }
6209                if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6210                        || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6211                    throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6212                            "Application package " + pkg.packageName
6213                            + " found at " + pkg.applicationInfo.getCodePath()
6214                            + " but expected at " + known.codePathString + "; ignoring.");
6215                }
6216            }
6217        }
6218
6219        // Initialize package source and resource directories
6220        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6221        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6222
6223        SharedUserSetting suid = null;
6224        PackageSetting pkgSetting = null;
6225
6226        if (!isSystemApp(pkg)) {
6227            // Only system apps can use these features.
6228            pkg.mOriginalPackages = null;
6229            pkg.mRealPackage = null;
6230            pkg.mAdoptPermissions = null;
6231        }
6232
6233        // writer
6234        synchronized (mPackages) {
6235            if (pkg.mSharedUserId != null) {
6236                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6237                if (suid == null) {
6238                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6239                            "Creating application package " + pkg.packageName
6240                            + " for shared user failed");
6241                }
6242                if (DEBUG_PACKAGE_SCANNING) {
6243                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6244                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6245                                + "): packages=" + suid.packages);
6246                }
6247            }
6248
6249            // Check if we are renaming from an original package name.
6250            PackageSetting origPackage = null;
6251            String realName = null;
6252            if (pkg.mOriginalPackages != null) {
6253                // This package may need to be renamed to a previously
6254                // installed name.  Let's check on that...
6255                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
6256                if (pkg.mOriginalPackages.contains(renamed)) {
6257                    // This package had originally been installed as the
6258                    // original name, and we have already taken care of
6259                    // transitioning to the new one.  Just update the new
6260                    // one to continue using the old name.
6261                    realName = pkg.mRealPackage;
6262                    if (!pkg.packageName.equals(renamed)) {
6263                        // Callers into this function may have already taken
6264                        // care of renaming the package; only do it here if
6265                        // it is not already done.
6266                        pkg.setPackageName(renamed);
6267                    }
6268
6269                } else {
6270                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
6271                        if ((origPackage = mSettings.peekPackageLPr(
6272                                pkg.mOriginalPackages.get(i))) != null) {
6273                            // We do have the package already installed under its
6274                            // original name...  should we use it?
6275                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
6276                                // New package is not compatible with original.
6277                                origPackage = null;
6278                                continue;
6279                            } else if (origPackage.sharedUser != null) {
6280                                // Make sure uid is compatible between packages.
6281                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6282                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6283                                            + " to " + pkg.packageName + ": old uid "
6284                                            + origPackage.sharedUser.name
6285                                            + " differs from " + pkg.mSharedUserId);
6286                                    origPackage = null;
6287                                    continue;
6288                                }
6289                            } else {
6290                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6291                                        + pkg.packageName + " to old name " + origPackage.name);
6292                            }
6293                            break;
6294                        }
6295                    }
6296                }
6297            }
6298
6299            if (mTransferedPackages.contains(pkg.packageName)) {
6300                Slog.w(TAG, "Package " + pkg.packageName
6301                        + " was transferred to another, but its .apk remains");
6302            }
6303
6304            // Just create the setting, don't add it yet. For already existing packages
6305            // the PkgSetting exists already and doesn't have to be created.
6306            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6307                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6308                    pkg.applicationInfo.primaryCpuAbi,
6309                    pkg.applicationInfo.secondaryCpuAbi,
6310                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6311                    user, false);
6312            if (pkgSetting == null) {
6313                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6314                        "Creating application package " + pkg.packageName + " failed");
6315            }
6316
6317            if (pkgSetting.origPackage != null) {
6318                // If we are first transitioning from an original package,
6319                // fix up the new package's name now.  We need to do this after
6320                // looking up the package under its new name, so getPackageLP
6321                // can take care of fiddling things correctly.
6322                pkg.setPackageName(origPackage.name);
6323
6324                // File a report about this.
6325                String msg = "New package " + pkgSetting.realName
6326                        + " renamed to replace old package " + pkgSetting.name;
6327                reportSettingsProblem(Log.WARN, msg);
6328
6329                // Make a note of it.
6330                mTransferedPackages.add(origPackage.name);
6331
6332                // No longer need to retain this.
6333                pkgSetting.origPackage = null;
6334            }
6335
6336            if (realName != null) {
6337                // Make a note of it.
6338                mTransferedPackages.add(pkg.packageName);
6339            }
6340
6341            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6342                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6343            }
6344
6345            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6346                // Check all shared libraries and map to their actual file path.
6347                // We only do this here for apps not on a system dir, because those
6348                // are the only ones that can fail an install due to this.  We
6349                // will take care of the system apps by updating all of their
6350                // library paths after the scan is done.
6351                updateSharedLibrariesLPw(pkg, null);
6352            }
6353
6354            if (mFoundPolicyFile) {
6355                SELinuxMMAC.assignSeinfoValue(pkg);
6356            }
6357
6358            pkg.applicationInfo.uid = pkgSetting.appId;
6359            pkg.mExtras = pkgSetting;
6360            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
6361                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
6362                    // We just determined the app is signed correctly, so bring
6363                    // over the latest parsed certs.
6364                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6365                } else {
6366                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6367                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6368                                "Package " + pkg.packageName + " upgrade keys do not match the "
6369                                + "previously installed version");
6370                    } else {
6371                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
6372                        String msg = "System package " + pkg.packageName
6373                            + " signature changed; retaining data.";
6374                        reportSettingsProblem(Log.WARN, msg);
6375                    }
6376                }
6377            } else {
6378                try {
6379                    verifySignaturesLP(pkgSetting, pkg);
6380                    // We just determined the app is signed correctly, so bring
6381                    // over the latest parsed certs.
6382                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6383                } catch (PackageManagerException e) {
6384                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6385                        throw e;
6386                    }
6387                    // The signature has changed, but this package is in the system
6388                    // image...  let's recover!
6389                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6390                    // However...  if this package is part of a shared user, but it
6391                    // doesn't match the signature of the shared user, let's fail.
6392                    // What this means is that you can't change the signatures
6393                    // associated with an overall shared user, which doesn't seem all
6394                    // that unreasonable.
6395                    if (pkgSetting.sharedUser != null) {
6396                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6397                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
6398                            throw new PackageManagerException(
6399                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
6400                                            "Signature mismatch for shared user : "
6401                                            + pkgSetting.sharedUser);
6402                        }
6403                    }
6404                    // File a report about this.
6405                    String msg = "System package " + pkg.packageName
6406                        + " signature changed; retaining data.";
6407                    reportSettingsProblem(Log.WARN, msg);
6408                }
6409            }
6410            // Verify that this new package doesn't have any content providers
6411            // that conflict with existing packages.  Only do this if the
6412            // package isn't already installed, since we don't want to break
6413            // things that are installed.
6414            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6415                final int N = pkg.providers.size();
6416                int i;
6417                for (i=0; i<N; i++) {
6418                    PackageParser.Provider p = pkg.providers.get(i);
6419                    if (p.info.authority != null) {
6420                        String names[] = p.info.authority.split(";");
6421                        for (int j = 0; j < names.length; j++) {
6422                            if (mProvidersByAuthority.containsKey(names[j])) {
6423                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6424                                final String otherPackageName =
6425                                        ((other != null && other.getComponentName() != null) ?
6426                                                other.getComponentName().getPackageName() : "?");
6427                                throw new PackageManagerException(
6428                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
6429                                                "Can't install because provider name " + names[j]
6430                                                + " (in package " + pkg.applicationInfo.packageName
6431                                                + ") is already used by " + otherPackageName);
6432                            }
6433                        }
6434                    }
6435                }
6436            }
6437
6438            if (pkg.mAdoptPermissions != null) {
6439                // This package wants to adopt ownership of permissions from
6440                // another package.
6441                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6442                    final String origName = pkg.mAdoptPermissions.get(i);
6443                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
6444                    if (orig != null) {
6445                        if (verifyPackageUpdateLPr(orig, pkg)) {
6446                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
6447                                    + pkg.packageName);
6448                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
6449                        }
6450                    }
6451                }
6452            }
6453        }
6454
6455        final String pkgName = pkg.packageName;
6456
6457        final long scanFileTime = scanFile.lastModified();
6458        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6459        pkg.applicationInfo.processName = fixProcessName(
6460                pkg.applicationInfo.packageName,
6461                pkg.applicationInfo.processName,
6462                pkg.applicationInfo.uid);
6463
6464        File dataPath;
6465        if (mPlatformPackage == pkg) {
6466            // The system package is special.
6467            dataPath = new File(Environment.getDataDirectory(), "system");
6468
6469            pkg.applicationInfo.dataDir = dataPath.getPath();
6470
6471        } else {
6472            // This is a normal package, need to make its data directory.
6473            dataPath = PackageManager.getDataDirForUser(pkg.volumeUuid, pkg.packageName,
6474                    UserHandle.USER_OWNER);
6475
6476            boolean uidError = false;
6477            if (dataPath.exists()) {
6478                int currentUid = 0;
6479                try {
6480                    StructStat stat = Os.stat(dataPath.getPath());
6481                    currentUid = stat.st_uid;
6482                } catch (ErrnoException e) {
6483                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6484                }
6485
6486                // If we have mismatched owners for the data path, we have a problem.
6487                if (currentUid != pkg.applicationInfo.uid) {
6488                    boolean recovered = false;
6489                    if (currentUid == 0) {
6490                        // The directory somehow became owned by root.  Wow.
6491                        // This is probably because the system was stopped while
6492                        // installd was in the middle of messing with its libs
6493                        // directory.  Ask installd to fix that.
6494                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
6495                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
6496                        if (ret >= 0) {
6497                            recovered = true;
6498                            String msg = "Package " + pkg.packageName
6499                                    + " unexpectedly changed to uid 0; recovered to " +
6500                                    + pkg.applicationInfo.uid;
6501                            reportSettingsProblem(Log.WARN, msg);
6502                        }
6503                    }
6504                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6505                            || (scanFlags&SCAN_BOOTING) != 0)) {
6506                        // If this is a system app, we can at least delete its
6507                        // current data so the application will still work.
6508                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
6509                        if (ret >= 0) {
6510                            // TODO: Kill the processes first
6511                            // Old data gone!
6512                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6513                                    ? "System package " : "Third party package ";
6514                            String msg = prefix + pkg.packageName
6515                                    + " has changed from uid: "
6516                                    + currentUid + " to "
6517                                    + pkg.applicationInfo.uid + "; old data erased";
6518                            reportSettingsProblem(Log.WARN, msg);
6519                            recovered = true;
6520
6521                            // And now re-install the app.
6522                            ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6523                                    pkg.applicationInfo.seinfo);
6524                            if (ret == -1) {
6525                                // Ack should not happen!
6526                                msg = prefix + pkg.packageName
6527                                        + " could not have data directory re-created after delete.";
6528                                reportSettingsProblem(Log.WARN, msg);
6529                                throw new PackageManagerException(
6530                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6531                            }
6532                        }
6533                        if (!recovered) {
6534                            mHasSystemUidErrors = true;
6535                        }
6536                    } else if (!recovered) {
6537                        // If we allow this install to proceed, we will be broken.
6538                        // Abort, abort!
6539                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
6540                                "scanPackageLI");
6541                    }
6542                    if (!recovered) {
6543                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
6544                            + pkg.applicationInfo.uid + "/fs_"
6545                            + currentUid;
6546                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
6547                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
6548                        String msg = "Package " + pkg.packageName
6549                                + " has mismatched uid: "
6550                                + currentUid + " on disk, "
6551                                + pkg.applicationInfo.uid + " in settings";
6552                        // writer
6553                        synchronized (mPackages) {
6554                            mSettings.mReadMessages.append(msg);
6555                            mSettings.mReadMessages.append('\n');
6556                            uidError = true;
6557                            if (!pkgSetting.uidError) {
6558                                reportSettingsProblem(Log.ERROR, msg);
6559                            }
6560                        }
6561                    }
6562                }
6563                pkg.applicationInfo.dataDir = dataPath.getPath();
6564                if (mShouldRestoreconData) {
6565                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
6566                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
6567                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
6568                }
6569            } else {
6570                if (DEBUG_PACKAGE_SCANNING) {
6571                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6572                        Log.v(TAG, "Want this data dir: " + dataPath);
6573                }
6574                //invoke installer to do the actual installation
6575                int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6576                        pkg.applicationInfo.seinfo);
6577                if (ret < 0) {
6578                    // Error from installer
6579                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6580                            "Unable to create data dirs [errorCode=" + ret + "]");
6581                }
6582
6583                if (dataPath.exists()) {
6584                    pkg.applicationInfo.dataDir = dataPath.getPath();
6585                } else {
6586                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
6587                    pkg.applicationInfo.dataDir = null;
6588                }
6589            }
6590
6591            pkgSetting.uidError = uidError;
6592        }
6593
6594        final String path = scanFile.getPath();
6595        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
6596
6597        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
6598            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
6599
6600            // Some system apps still use directory structure for native libraries
6601            // in which case we might end up not detecting abi solely based on apk
6602            // structure. Try to detect abi based on directory structure.
6603            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
6604                    pkg.applicationInfo.primaryCpuAbi == null) {
6605                setBundledAppAbisAndRoots(pkg, pkgSetting);
6606                setNativeLibraryPaths(pkg);
6607            }
6608
6609        } else {
6610            if ((scanFlags & SCAN_MOVE) != 0) {
6611                // We haven't run dex-opt for this move (since we've moved the compiled output too)
6612                // but we already have this packages package info in the PackageSetting. We just
6613                // use that and derive the native library path based on the new codepath.
6614                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
6615                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
6616            }
6617
6618            // Set native library paths again. For moves, the path will be updated based on the
6619            // ABIs we've determined above. For non-moves, the path will be updated based on the
6620            // ABIs we determined during compilation, but the path will depend on the final
6621            // package path (after the rename away from the stage path).
6622            setNativeLibraryPaths(pkg);
6623        }
6624
6625        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
6626        final int[] userIds = sUserManager.getUserIds();
6627        synchronized (mInstallLock) {
6628            // Create a native library symlink only if we have native libraries
6629            // and if the native libraries are 32 bit libraries. We do not provide
6630            // this symlink for 64 bit libraries.
6631            if (pkg.applicationInfo.primaryCpuAbi != null &&
6632                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
6633                final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
6634                for (int userId : userIds) {
6635                    if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
6636                            nativeLibPath, userId) < 0) {
6637                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
6638                                "Failed linking native library dir (user=" + userId + ")");
6639                    }
6640                }
6641            }
6642        }
6643
6644        // This is a special case for the "system" package, where the ABI is
6645        // dictated by the zygote configuration (and init.rc). We should keep track
6646        // of this ABI so that we can deal with "normal" applications that run under
6647        // the same UID correctly.
6648        if (mPlatformPackage == pkg) {
6649            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
6650                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
6651        }
6652
6653        // If there's a mismatch between the abi-override in the package setting
6654        // and the abiOverride specified for the install. Warn about this because we
6655        // would've already compiled the app without taking the package setting into
6656        // account.
6657        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
6658            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
6659                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
6660                        " for package: " + pkg.packageName);
6661            }
6662        }
6663
6664        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6665        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6666        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
6667
6668        // Copy the derived override back to the parsed package, so that we can
6669        // update the package settings accordingly.
6670        pkg.cpuAbiOverride = cpuAbiOverride;
6671
6672        if (DEBUG_ABI_SELECTION) {
6673            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
6674                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
6675                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
6676        }
6677
6678        // Push the derived path down into PackageSettings so we know what to
6679        // clean up at uninstall time.
6680        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
6681
6682        if (DEBUG_ABI_SELECTION) {
6683            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
6684                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
6685                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
6686        }
6687
6688        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
6689            // We don't do this here during boot because we can do it all
6690            // at once after scanning all existing packages.
6691            //
6692            // We also do this *before* we perform dexopt on this package, so that
6693            // we can avoid redundant dexopts, and also to make sure we've got the
6694            // code and package path correct.
6695            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
6696                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
6697        }
6698
6699        if ((scanFlags & SCAN_NO_DEX) == 0) {
6700            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
6701                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */);
6702            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6703                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
6704            }
6705        }
6706        if (mFactoryTest && pkg.requestedPermissions.contains(
6707                android.Manifest.permission.FACTORY_TEST)) {
6708            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
6709        }
6710
6711        ArrayList<PackageParser.Package> clientLibPkgs = null;
6712
6713        // writer
6714        synchronized (mPackages) {
6715            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6716                // Only system apps can add new shared libraries.
6717                if (pkg.libraryNames != null) {
6718                    for (int i=0; i<pkg.libraryNames.size(); i++) {
6719                        String name = pkg.libraryNames.get(i);
6720                        boolean allowed = false;
6721                        if (pkg.isUpdatedSystemApp()) {
6722                            // New library entries can only be added through the
6723                            // system image.  This is important to get rid of a lot
6724                            // of nasty edge cases: for example if we allowed a non-
6725                            // system update of the app to add a library, then uninstalling
6726                            // the update would make the library go away, and assumptions
6727                            // we made such as through app install filtering would now
6728                            // have allowed apps on the device which aren't compatible
6729                            // with it.  Better to just have the restriction here, be
6730                            // conservative, and create many fewer cases that can negatively
6731                            // impact the user experience.
6732                            final PackageSetting sysPs = mSettings
6733                                    .getDisabledSystemPkgLPr(pkg.packageName);
6734                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
6735                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
6736                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
6737                                        allowed = true;
6738                                        allowed = true;
6739                                        break;
6740                                    }
6741                                }
6742                            }
6743                        } else {
6744                            allowed = true;
6745                        }
6746                        if (allowed) {
6747                            if (!mSharedLibraries.containsKey(name)) {
6748                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
6749                            } else if (!name.equals(pkg.packageName)) {
6750                                Slog.w(TAG, "Package " + pkg.packageName + " library "
6751                                        + name + " already exists; skipping");
6752                            }
6753                        } else {
6754                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
6755                                    + name + " that is not declared on system image; skipping");
6756                        }
6757                    }
6758                    if ((scanFlags&SCAN_BOOTING) == 0) {
6759                        // If we are not booting, we need to update any applications
6760                        // that are clients of our shared library.  If we are booting,
6761                        // this will all be done once the scan is complete.
6762                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
6763                    }
6764                }
6765            }
6766        }
6767
6768        // We also need to dexopt any apps that are dependent on this library.  Note that
6769        // if these fail, we should abort the install since installing the library will
6770        // result in some apps being broken.
6771        if (clientLibPkgs != null) {
6772            if ((scanFlags & SCAN_NO_DEX) == 0) {
6773                for (int i = 0; i < clientLibPkgs.size(); i++) {
6774                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
6775                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
6776                            null /* instruction sets */, forceDex,
6777                            (scanFlags & SCAN_DEFER_DEX) != 0, false);
6778                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6779                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
6780                                "scanPackageLI failed to dexopt clientLibPkgs");
6781                    }
6782                }
6783            }
6784        }
6785
6786        // Also need to kill any apps that are dependent on the library.
6787        if (clientLibPkgs != null) {
6788            for (int i=0; i<clientLibPkgs.size(); i++) {
6789                PackageParser.Package clientPkg = clientLibPkgs.get(i);
6790                killApplication(clientPkg.applicationInfo.packageName,
6791                        clientPkg.applicationInfo.uid, "update lib");
6792            }
6793        }
6794
6795        // Make sure we're not adding any bogus keyset info
6796        KeySetManagerService ksms = mSettings.mKeySetManagerService;
6797        ksms.assertScannedPackageValid(pkg);
6798
6799        // writer
6800        synchronized (mPackages) {
6801            // We don't expect installation to fail beyond this point
6802
6803            // Add the new setting to mSettings
6804            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
6805            // Add the new setting to mPackages
6806            mPackages.put(pkg.applicationInfo.packageName, pkg);
6807            // Make sure we don't accidentally delete its data.
6808            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
6809            while (iter.hasNext()) {
6810                PackageCleanItem item = iter.next();
6811                if (pkgName.equals(item.packageName)) {
6812                    iter.remove();
6813                }
6814            }
6815
6816            // Take care of first install / last update times.
6817            if (currentTime != 0) {
6818                if (pkgSetting.firstInstallTime == 0) {
6819                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
6820                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
6821                    pkgSetting.lastUpdateTime = currentTime;
6822                }
6823            } else if (pkgSetting.firstInstallTime == 0) {
6824                // We need *something*.  Take time time stamp of the file.
6825                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
6826            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
6827                if (scanFileTime != pkgSetting.timeStamp) {
6828                    // A package on the system image has changed; consider this
6829                    // to be an update.
6830                    pkgSetting.lastUpdateTime = scanFileTime;
6831                }
6832            }
6833
6834            // Add the package's KeySets to the global KeySetManagerService
6835            ksms.addScannedPackageLPw(pkg);
6836
6837            int N = pkg.providers.size();
6838            StringBuilder r = null;
6839            int i;
6840            for (i=0; i<N; i++) {
6841                PackageParser.Provider p = pkg.providers.get(i);
6842                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
6843                        p.info.processName, pkg.applicationInfo.uid);
6844                mProviders.addProvider(p);
6845                p.syncable = p.info.isSyncable;
6846                if (p.info.authority != null) {
6847                    String names[] = p.info.authority.split(";");
6848                    p.info.authority = null;
6849                    for (int j = 0; j < names.length; j++) {
6850                        if (j == 1 && p.syncable) {
6851                            // We only want the first authority for a provider to possibly be
6852                            // syncable, so if we already added this provider using a different
6853                            // authority clear the syncable flag. We copy the provider before
6854                            // changing it because the mProviders object contains a reference
6855                            // to a provider that we don't want to change.
6856                            // Only do this for the second authority since the resulting provider
6857                            // object can be the same for all future authorities for this provider.
6858                            p = new PackageParser.Provider(p);
6859                            p.syncable = false;
6860                        }
6861                        if (!mProvidersByAuthority.containsKey(names[j])) {
6862                            mProvidersByAuthority.put(names[j], p);
6863                            if (p.info.authority == null) {
6864                                p.info.authority = names[j];
6865                            } else {
6866                                p.info.authority = p.info.authority + ";" + names[j];
6867                            }
6868                            if (DEBUG_PACKAGE_SCANNING) {
6869                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6870                                    Log.d(TAG, "Registered content provider: " + names[j]
6871                                            + ", className = " + p.info.name + ", isSyncable = "
6872                                            + p.info.isSyncable);
6873                            }
6874                        } else {
6875                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6876                            Slog.w(TAG, "Skipping provider name " + names[j] +
6877                                    " (in package " + pkg.applicationInfo.packageName +
6878                                    "): name already used by "
6879                                    + ((other != null && other.getComponentName() != null)
6880                                            ? other.getComponentName().getPackageName() : "?"));
6881                        }
6882                    }
6883                }
6884                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6885                    if (r == null) {
6886                        r = new StringBuilder(256);
6887                    } else {
6888                        r.append(' ');
6889                    }
6890                    r.append(p.info.name);
6891                }
6892            }
6893            if (r != null) {
6894                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
6895            }
6896
6897            N = pkg.services.size();
6898            r = null;
6899            for (i=0; i<N; i++) {
6900                PackageParser.Service s = pkg.services.get(i);
6901                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
6902                        s.info.processName, pkg.applicationInfo.uid);
6903                mServices.addService(s);
6904                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6905                    if (r == null) {
6906                        r = new StringBuilder(256);
6907                    } else {
6908                        r.append(' ');
6909                    }
6910                    r.append(s.info.name);
6911                }
6912            }
6913            if (r != null) {
6914                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
6915            }
6916
6917            N = pkg.receivers.size();
6918            r = null;
6919            for (i=0; i<N; i++) {
6920                PackageParser.Activity a = pkg.receivers.get(i);
6921                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6922                        a.info.processName, pkg.applicationInfo.uid);
6923                mReceivers.addActivity(a, "receiver");
6924                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6925                    if (r == null) {
6926                        r = new StringBuilder(256);
6927                    } else {
6928                        r.append(' ');
6929                    }
6930                    r.append(a.info.name);
6931                }
6932            }
6933            if (r != null) {
6934                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
6935            }
6936
6937            N = pkg.activities.size();
6938            r = null;
6939            for (i=0; i<N; i++) {
6940                PackageParser.Activity a = pkg.activities.get(i);
6941                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6942                        a.info.processName, pkg.applicationInfo.uid);
6943                mActivities.addActivity(a, "activity");
6944                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6945                    if (r == null) {
6946                        r = new StringBuilder(256);
6947                    } else {
6948                        r.append(' ');
6949                    }
6950                    r.append(a.info.name);
6951                }
6952            }
6953            if (r != null) {
6954                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
6955            }
6956
6957            N = pkg.permissionGroups.size();
6958            r = null;
6959            for (i=0; i<N; i++) {
6960                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
6961                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
6962                if (cur == null) {
6963                    mPermissionGroups.put(pg.info.name, pg);
6964                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6965                        if (r == null) {
6966                            r = new StringBuilder(256);
6967                        } else {
6968                            r.append(' ');
6969                        }
6970                        r.append(pg.info.name);
6971                    }
6972                } else {
6973                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
6974                            + pg.info.packageName + " ignored: original from "
6975                            + cur.info.packageName);
6976                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6977                        if (r == null) {
6978                            r = new StringBuilder(256);
6979                        } else {
6980                            r.append(' ');
6981                        }
6982                        r.append("DUP:");
6983                        r.append(pg.info.name);
6984                    }
6985                }
6986            }
6987            if (r != null) {
6988                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
6989            }
6990
6991            N = pkg.permissions.size();
6992            r = null;
6993            for (i=0; i<N; i++) {
6994                PackageParser.Permission p = pkg.permissions.get(i);
6995
6996                // Now that permission groups have a special meaning, we ignore permission
6997                // groups for legacy apps to prevent unexpected behavior. In particular,
6998                // permissions for one app being granted to someone just becuase they happen
6999                // to be in a group defined by another app (before this had no implications).
7000                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7001                    p.group = mPermissionGroups.get(p.info.group);
7002                    // Warn for a permission in an unknown group.
7003                    if (p.info.group != null && p.group == null) {
7004                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7005                                + p.info.packageName + " in an unknown group " + p.info.group);
7006                    }
7007                }
7008
7009                ArrayMap<String, BasePermission> permissionMap =
7010                        p.tree ? mSettings.mPermissionTrees
7011                                : mSettings.mPermissions;
7012                BasePermission bp = permissionMap.get(p.info.name);
7013
7014                // Allow system apps to redefine non-system permissions
7015                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7016                    final boolean currentOwnerIsSystem = (bp.perm != null
7017                            && isSystemApp(bp.perm.owner));
7018                    if (isSystemApp(p.owner)) {
7019                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7020                            // It's a built-in permission and no owner, take ownership now
7021                            bp.packageSetting = pkgSetting;
7022                            bp.perm = p;
7023                            bp.uid = pkg.applicationInfo.uid;
7024                            bp.sourcePackage = p.info.packageName;
7025                        } else if (!currentOwnerIsSystem) {
7026                            String msg = "New decl " + p.owner + " of permission  "
7027                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7028                            reportSettingsProblem(Log.WARN, msg);
7029                            bp = null;
7030                        }
7031                    }
7032                }
7033
7034                if (bp == null) {
7035                    bp = new BasePermission(p.info.name, p.info.packageName,
7036                            BasePermission.TYPE_NORMAL);
7037                    permissionMap.put(p.info.name, bp);
7038                }
7039
7040                if (bp.perm == null) {
7041                    if (bp.sourcePackage == null
7042                            || bp.sourcePackage.equals(p.info.packageName)) {
7043                        BasePermission tree = findPermissionTreeLP(p.info.name);
7044                        if (tree == null
7045                                || tree.sourcePackage.equals(p.info.packageName)) {
7046                            bp.packageSetting = pkgSetting;
7047                            bp.perm = p;
7048                            bp.uid = pkg.applicationInfo.uid;
7049                            bp.sourcePackage = p.info.packageName;
7050                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7051                                if (r == null) {
7052                                    r = new StringBuilder(256);
7053                                } else {
7054                                    r.append(' ');
7055                                }
7056                                r.append(p.info.name);
7057                            }
7058                        } else {
7059                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7060                                    + p.info.packageName + " ignored: base tree "
7061                                    + tree.name + " is from package "
7062                                    + tree.sourcePackage);
7063                        }
7064                    } else {
7065                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7066                                + p.info.packageName + " ignored: original from "
7067                                + bp.sourcePackage);
7068                    }
7069                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7070                    if (r == null) {
7071                        r = new StringBuilder(256);
7072                    } else {
7073                        r.append(' ');
7074                    }
7075                    r.append("DUP:");
7076                    r.append(p.info.name);
7077                }
7078                if (bp.perm == p) {
7079                    bp.protectionLevel = p.info.protectionLevel;
7080                }
7081            }
7082
7083            if (r != null) {
7084                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7085            }
7086
7087            N = pkg.instrumentation.size();
7088            r = null;
7089            for (i=0; i<N; i++) {
7090                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7091                a.info.packageName = pkg.applicationInfo.packageName;
7092                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7093                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7094                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7095                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7096                a.info.dataDir = pkg.applicationInfo.dataDir;
7097
7098                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7099                // need other information about the application, like the ABI and what not ?
7100                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7101                mInstrumentation.put(a.getComponentName(), a);
7102                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7103                    if (r == null) {
7104                        r = new StringBuilder(256);
7105                    } else {
7106                        r.append(' ');
7107                    }
7108                    r.append(a.info.name);
7109                }
7110            }
7111            if (r != null) {
7112                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7113            }
7114
7115            if (pkg.protectedBroadcasts != null) {
7116                N = pkg.protectedBroadcasts.size();
7117                for (i=0; i<N; i++) {
7118                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7119                }
7120            }
7121
7122            pkgSetting.setTimeStamp(scanFileTime);
7123
7124            // Create idmap files for pairs of (packages, overlay packages).
7125            // Note: "android", ie framework-res.apk, is handled by native layers.
7126            if (pkg.mOverlayTarget != null) {
7127                // This is an overlay package.
7128                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7129                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7130                        mOverlays.put(pkg.mOverlayTarget,
7131                                new ArrayMap<String, PackageParser.Package>());
7132                    }
7133                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7134                    map.put(pkg.packageName, pkg);
7135                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7136                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7137                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7138                                "scanPackageLI failed to createIdmap");
7139                    }
7140                }
7141            } else if (mOverlays.containsKey(pkg.packageName) &&
7142                    !pkg.packageName.equals("android")) {
7143                // This is a regular package, with one or more known overlay packages.
7144                createIdmapsForPackageLI(pkg);
7145            }
7146        }
7147
7148        return pkg;
7149    }
7150
7151    /**
7152     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7153     * is derived purely on the basis of the contents of {@code scanFile} and
7154     * {@code cpuAbiOverride}.
7155     *
7156     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7157     */
7158    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7159                                 String cpuAbiOverride, boolean extractLibs)
7160            throws PackageManagerException {
7161        // TODO: We can probably be smarter about this stuff. For installed apps,
7162        // we can calculate this information at install time once and for all. For
7163        // system apps, we can probably assume that this information doesn't change
7164        // after the first boot scan. As things stand, we do lots of unnecessary work.
7165
7166        // Give ourselves some initial paths; we'll come back for another
7167        // pass once we've determined ABI below.
7168        setNativeLibraryPaths(pkg);
7169
7170        // We would never need to extract libs for forward-locked and external packages,
7171        // since the container service will do it for us. We shouldn't attempt to
7172        // extract libs from system app when it was not updated.
7173        if (pkg.isForwardLocked() || isExternal(pkg) ||
7174            (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) {
7175            extractLibs = false;
7176        }
7177
7178        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7179        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7180
7181        NativeLibraryHelper.Handle handle = null;
7182        try {
7183            handle = NativeLibraryHelper.Handle.create(scanFile);
7184            // TODO(multiArch): This can be null for apps that didn't go through the
7185            // usual installation process. We can calculate it again, like we
7186            // do during install time.
7187            //
7188            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7189            // unnecessary.
7190            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7191
7192            // Null out the abis so that they can be recalculated.
7193            pkg.applicationInfo.primaryCpuAbi = null;
7194            pkg.applicationInfo.secondaryCpuAbi = null;
7195            if (isMultiArch(pkg.applicationInfo)) {
7196                // Warn if we've set an abiOverride for multi-lib packages..
7197                // By definition, we need to copy both 32 and 64 bit libraries for
7198                // such packages.
7199                if (pkg.cpuAbiOverride != null
7200                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7201                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7202                }
7203
7204                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7205                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7206                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7207                    if (extractLibs) {
7208                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7209                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7210                                useIsaSpecificSubdirs);
7211                    } else {
7212                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7213                    }
7214                }
7215
7216                maybeThrowExceptionForMultiArchCopy(
7217                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7218
7219                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7220                    if (extractLibs) {
7221                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7222                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7223                                useIsaSpecificSubdirs);
7224                    } else {
7225                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7226                    }
7227                }
7228
7229                maybeThrowExceptionForMultiArchCopy(
7230                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7231
7232                if (abi64 >= 0) {
7233                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7234                }
7235
7236                if (abi32 >= 0) {
7237                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7238                    if (abi64 >= 0) {
7239                        pkg.applicationInfo.secondaryCpuAbi = abi;
7240                    } else {
7241                        pkg.applicationInfo.primaryCpuAbi = abi;
7242                    }
7243                }
7244            } else {
7245                String[] abiList = (cpuAbiOverride != null) ?
7246                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7247
7248                // Enable gross and lame hacks for apps that are built with old
7249                // SDK tools. We must scan their APKs for renderscript bitcode and
7250                // not launch them if it's present. Don't bother checking on devices
7251                // that don't have 64 bit support.
7252                boolean needsRenderScriptOverride = false;
7253                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7254                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7255                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7256                    needsRenderScriptOverride = true;
7257                }
7258
7259                final int copyRet;
7260                if (extractLibs) {
7261                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7262                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7263                } else {
7264                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7265                }
7266
7267                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7268                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7269                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7270                }
7271
7272                if (copyRet >= 0) {
7273                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7274                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7275                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7276                } else if (needsRenderScriptOverride) {
7277                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7278                }
7279            }
7280        } catch (IOException ioe) {
7281            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7282        } finally {
7283            IoUtils.closeQuietly(handle);
7284        }
7285
7286        // Now that we've calculated the ABIs and determined if it's an internal app,
7287        // we will go ahead and populate the nativeLibraryPath.
7288        setNativeLibraryPaths(pkg);
7289    }
7290
7291    /**
7292     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7293     * i.e, so that all packages can be run inside a single process if required.
7294     *
7295     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7296     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7297     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7298     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7299     * updating a package that belongs to a shared user.
7300     *
7301     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7302     * adds unnecessary complexity.
7303     */
7304    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7305            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
7306        String requiredInstructionSet = null;
7307        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7308            requiredInstructionSet = VMRuntime.getInstructionSet(
7309                     scannedPackage.applicationInfo.primaryCpuAbi);
7310        }
7311
7312        PackageSetting requirer = null;
7313        for (PackageSetting ps : packagesForUser) {
7314            // If packagesForUser contains scannedPackage, we skip it. This will happen
7315            // when scannedPackage is an update of an existing package. Without this check,
7316            // we will never be able to change the ABI of any package belonging to a shared
7317            // user, even if it's compatible with other packages.
7318            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7319                if (ps.primaryCpuAbiString == null) {
7320                    continue;
7321                }
7322
7323                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7324                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7325                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7326                    // this but there's not much we can do.
7327                    String errorMessage = "Instruction set mismatch, "
7328                            + ((requirer == null) ? "[caller]" : requirer)
7329                            + " requires " + requiredInstructionSet + " whereas " + ps
7330                            + " requires " + instructionSet;
7331                    Slog.w(TAG, errorMessage);
7332                }
7333
7334                if (requiredInstructionSet == null) {
7335                    requiredInstructionSet = instructionSet;
7336                    requirer = ps;
7337                }
7338            }
7339        }
7340
7341        if (requiredInstructionSet != null) {
7342            String adjustedAbi;
7343            if (requirer != null) {
7344                // requirer != null implies that either scannedPackage was null or that scannedPackage
7345                // did not require an ABI, in which case we have to adjust scannedPackage to match
7346                // the ABI of the set (which is the same as requirer's ABI)
7347                adjustedAbi = requirer.primaryCpuAbiString;
7348                if (scannedPackage != null) {
7349                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7350                }
7351            } else {
7352                // requirer == null implies that we're updating all ABIs in the set to
7353                // match scannedPackage.
7354                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7355            }
7356
7357            for (PackageSetting ps : packagesForUser) {
7358                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7359                    if (ps.primaryCpuAbiString != null) {
7360                        continue;
7361                    }
7362
7363                    ps.primaryCpuAbiString = adjustedAbi;
7364                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7365                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7366                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7367
7368                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
7369                                null /* instruction sets */, forceDexOpt, deferDexOpt, true);
7370                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7371                            ps.primaryCpuAbiString = null;
7372                            ps.pkg.applicationInfo.primaryCpuAbi = null;
7373                            return;
7374                        } else {
7375                            mInstaller.rmdex(ps.codePathString,
7376                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
7377                        }
7378                    }
7379                }
7380            }
7381        }
7382    }
7383
7384    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7385        synchronized (mPackages) {
7386            mResolverReplaced = true;
7387            // Set up information for custom user intent resolution activity.
7388            mResolveActivity.applicationInfo = pkg.applicationInfo;
7389            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7390            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7391            mResolveActivity.processName = pkg.applicationInfo.packageName;
7392            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7393            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7394                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7395            mResolveActivity.theme = 0;
7396            mResolveActivity.exported = true;
7397            mResolveActivity.enabled = true;
7398            mResolveInfo.activityInfo = mResolveActivity;
7399            mResolveInfo.priority = 0;
7400            mResolveInfo.preferredOrder = 0;
7401            mResolveInfo.match = 0;
7402            mResolveComponentName = mCustomResolverComponentName;
7403            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7404                    mResolveComponentName);
7405        }
7406    }
7407
7408    private static String calculateBundledApkRoot(final String codePathString) {
7409        final File codePath = new File(codePathString);
7410        final File codeRoot;
7411        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7412            codeRoot = Environment.getRootDirectory();
7413        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7414            codeRoot = Environment.getOemDirectory();
7415        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7416            codeRoot = Environment.getVendorDirectory();
7417        } else {
7418            // Unrecognized code path; take its top real segment as the apk root:
7419            // e.g. /something/app/blah.apk => /something
7420            try {
7421                File f = codePath.getCanonicalFile();
7422                File parent = f.getParentFile();    // non-null because codePath is a file
7423                File tmp;
7424                while ((tmp = parent.getParentFile()) != null) {
7425                    f = parent;
7426                    parent = tmp;
7427                }
7428                codeRoot = f;
7429                Slog.w(TAG, "Unrecognized code path "
7430                        + codePath + " - using " + codeRoot);
7431            } catch (IOException e) {
7432                // Can't canonicalize the code path -- shenanigans?
7433                Slog.w(TAG, "Can't canonicalize code path " + codePath);
7434                return Environment.getRootDirectory().getPath();
7435            }
7436        }
7437        return codeRoot.getPath();
7438    }
7439
7440    /**
7441     * Derive and set the location of native libraries for the given package,
7442     * which varies depending on where and how the package was installed.
7443     */
7444    private void setNativeLibraryPaths(PackageParser.Package pkg) {
7445        final ApplicationInfo info = pkg.applicationInfo;
7446        final String codePath = pkg.codePath;
7447        final File codeFile = new File(codePath);
7448        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7449        final boolean asecApp = info.isForwardLocked() || isExternal(info);
7450
7451        info.nativeLibraryRootDir = null;
7452        info.nativeLibraryRootRequiresIsa = false;
7453        info.nativeLibraryDir = null;
7454        info.secondaryNativeLibraryDir = null;
7455
7456        if (isApkFile(codeFile)) {
7457            // Monolithic install
7458            if (bundledApp) {
7459                // If "/system/lib64/apkname" exists, assume that is the per-package
7460                // native library directory to use; otherwise use "/system/lib/apkname".
7461                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
7462                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
7463                        getPrimaryInstructionSet(info));
7464
7465                // This is a bundled system app so choose the path based on the ABI.
7466                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
7467                // is just the default path.
7468                final String apkName = deriveCodePathName(codePath);
7469                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
7470                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
7471                        apkName).getAbsolutePath();
7472
7473                if (info.secondaryCpuAbi != null) {
7474                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7475                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7476                            secondaryLibDir, apkName).getAbsolutePath();
7477                }
7478            } else if (asecApp) {
7479                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
7480                        .getAbsolutePath();
7481            } else {
7482                final String apkName = deriveCodePathName(codePath);
7483                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
7484                        .getAbsolutePath();
7485            }
7486
7487            info.nativeLibraryRootRequiresIsa = false;
7488            info.nativeLibraryDir = info.nativeLibraryRootDir;
7489        } else {
7490            // Cluster install
7491            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7492            info.nativeLibraryRootRequiresIsa = true;
7493
7494            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7495                    getPrimaryInstructionSet(info)).getAbsolutePath();
7496
7497            if (info.secondaryCpuAbi != null) {
7498                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7499                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7500            }
7501        }
7502    }
7503
7504    /**
7505     * Calculate the abis and roots for a bundled app. These can uniquely
7506     * be determined from the contents of the system partition, i.e whether
7507     * it contains 64 or 32 bit shared libraries etc. We do not validate any
7508     * of this information, and instead assume that the system was built
7509     * sensibly.
7510     */
7511    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
7512                                           PackageSetting pkgSetting) {
7513        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
7514
7515        // If "/system/lib64/apkname" exists, assume that is the per-package
7516        // native library directory to use; otherwise use "/system/lib/apkname".
7517        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
7518        setBundledAppAbi(pkg, apkRoot, apkName);
7519        // pkgSetting might be null during rescan following uninstall of updates
7520        // to a bundled app, so accommodate that possibility.  The settings in
7521        // that case will be established later from the parsed package.
7522        //
7523        // If the settings aren't null, sync them up with what we've just derived.
7524        // note that apkRoot isn't stored in the package settings.
7525        if (pkgSetting != null) {
7526            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7527            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7528        }
7529    }
7530
7531    /**
7532     * Deduces the ABI of a bundled app and sets the relevant fields on the
7533     * parsed pkg object.
7534     *
7535     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
7536     *        under which system libraries are installed.
7537     * @param apkName the name of the installed package.
7538     */
7539    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7540        final File codeFile = new File(pkg.codePath);
7541
7542        final boolean has64BitLibs;
7543        final boolean has32BitLibs;
7544        if (isApkFile(codeFile)) {
7545            // Monolithic install
7546            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7547            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7548        } else {
7549            // Cluster install
7550            final File rootDir = new File(codeFile, LIB_DIR_NAME);
7551            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7552                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7553                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7554                has64BitLibs = (new File(rootDir, isa)).exists();
7555            } else {
7556                has64BitLibs = false;
7557            }
7558            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7559                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7560                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7561                has32BitLibs = (new File(rootDir, isa)).exists();
7562            } else {
7563                has32BitLibs = false;
7564            }
7565        }
7566
7567        if (has64BitLibs && !has32BitLibs) {
7568            // The package has 64 bit libs, but not 32 bit libs. Its primary
7569            // ABI should be 64 bit. We can safely assume here that the bundled
7570            // native libraries correspond to the most preferred ABI in the list.
7571
7572            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7573            pkg.applicationInfo.secondaryCpuAbi = null;
7574        } else if (has32BitLibs && !has64BitLibs) {
7575            // The package has 32 bit libs but not 64 bit libs. Its primary
7576            // ABI should be 32 bit.
7577
7578            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7579            pkg.applicationInfo.secondaryCpuAbi = null;
7580        } else if (has32BitLibs && has64BitLibs) {
7581            // The application has both 64 and 32 bit bundled libraries. We check
7582            // here that the app declares multiArch support, and warn if it doesn't.
7583            //
7584            // We will be lenient here and record both ABIs. The primary will be the
7585            // ABI that's higher on the list, i.e, a device that's configured to prefer
7586            // 64 bit apps will see a 64 bit primary ABI,
7587
7588            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
7589                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
7590            }
7591
7592            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
7593                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7594                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7595            } else {
7596                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7597                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7598            }
7599        } else {
7600            pkg.applicationInfo.primaryCpuAbi = null;
7601            pkg.applicationInfo.secondaryCpuAbi = null;
7602        }
7603    }
7604
7605    private void killApplication(String pkgName, int appId, String reason) {
7606        // Request the ActivityManager to kill the process(only for existing packages)
7607        // so that we do not end up in a confused state while the user is still using the older
7608        // version of the application while the new one gets installed.
7609        IActivityManager am = ActivityManagerNative.getDefault();
7610        if (am != null) {
7611            try {
7612                am.killApplicationWithAppId(pkgName, appId, reason);
7613            } catch (RemoteException e) {
7614            }
7615        }
7616    }
7617
7618    void removePackageLI(PackageSetting ps, boolean chatty) {
7619        if (DEBUG_INSTALL) {
7620            if (chatty)
7621                Log.d(TAG, "Removing package " + ps.name);
7622        }
7623
7624        // writer
7625        synchronized (mPackages) {
7626            mPackages.remove(ps.name);
7627            final PackageParser.Package pkg = ps.pkg;
7628            if (pkg != null) {
7629                cleanPackageDataStructuresLILPw(pkg, chatty);
7630            }
7631        }
7632    }
7633
7634    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
7635        if (DEBUG_INSTALL) {
7636            if (chatty)
7637                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
7638        }
7639
7640        // writer
7641        synchronized (mPackages) {
7642            mPackages.remove(pkg.applicationInfo.packageName);
7643            cleanPackageDataStructuresLILPw(pkg, chatty);
7644        }
7645    }
7646
7647    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
7648        int N = pkg.providers.size();
7649        StringBuilder r = null;
7650        int i;
7651        for (i=0; i<N; i++) {
7652            PackageParser.Provider p = pkg.providers.get(i);
7653            mProviders.removeProvider(p);
7654            if (p.info.authority == null) {
7655
7656                /* There was another ContentProvider with this authority when
7657                 * this app was installed so this authority is null,
7658                 * Ignore it as we don't have to unregister the provider.
7659                 */
7660                continue;
7661            }
7662            String names[] = p.info.authority.split(";");
7663            for (int j = 0; j < names.length; j++) {
7664                if (mProvidersByAuthority.get(names[j]) == p) {
7665                    mProvidersByAuthority.remove(names[j]);
7666                    if (DEBUG_REMOVE) {
7667                        if (chatty)
7668                            Log.d(TAG, "Unregistered content provider: " + names[j]
7669                                    + ", className = " + p.info.name + ", isSyncable = "
7670                                    + p.info.isSyncable);
7671                    }
7672                }
7673            }
7674            if (DEBUG_REMOVE && chatty) {
7675                if (r == null) {
7676                    r = new StringBuilder(256);
7677                } else {
7678                    r.append(' ');
7679                }
7680                r.append(p.info.name);
7681            }
7682        }
7683        if (r != null) {
7684            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
7685        }
7686
7687        N = pkg.services.size();
7688        r = null;
7689        for (i=0; i<N; i++) {
7690            PackageParser.Service s = pkg.services.get(i);
7691            mServices.removeService(s);
7692            if (chatty) {
7693                if (r == null) {
7694                    r = new StringBuilder(256);
7695                } else {
7696                    r.append(' ');
7697                }
7698                r.append(s.info.name);
7699            }
7700        }
7701        if (r != null) {
7702            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
7703        }
7704
7705        N = pkg.receivers.size();
7706        r = null;
7707        for (i=0; i<N; i++) {
7708            PackageParser.Activity a = pkg.receivers.get(i);
7709            mReceivers.removeActivity(a, "receiver");
7710            if (DEBUG_REMOVE && chatty) {
7711                if (r == null) {
7712                    r = new StringBuilder(256);
7713                } else {
7714                    r.append(' ');
7715                }
7716                r.append(a.info.name);
7717            }
7718        }
7719        if (r != null) {
7720            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
7721        }
7722
7723        N = pkg.activities.size();
7724        r = null;
7725        for (i=0; i<N; i++) {
7726            PackageParser.Activity a = pkg.activities.get(i);
7727            mActivities.removeActivity(a, "activity");
7728            if (DEBUG_REMOVE && chatty) {
7729                if (r == null) {
7730                    r = new StringBuilder(256);
7731                } else {
7732                    r.append(' ');
7733                }
7734                r.append(a.info.name);
7735            }
7736        }
7737        if (r != null) {
7738            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
7739        }
7740
7741        N = pkg.permissions.size();
7742        r = null;
7743        for (i=0; i<N; i++) {
7744            PackageParser.Permission p = pkg.permissions.get(i);
7745            BasePermission bp = mSettings.mPermissions.get(p.info.name);
7746            if (bp == null) {
7747                bp = mSettings.mPermissionTrees.get(p.info.name);
7748            }
7749            if (bp != null && bp.perm == p) {
7750                bp.perm = null;
7751                if (DEBUG_REMOVE && chatty) {
7752                    if (r == null) {
7753                        r = new StringBuilder(256);
7754                    } else {
7755                        r.append(' ');
7756                    }
7757                    r.append(p.info.name);
7758                }
7759            }
7760            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7761                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
7762                if (appOpPerms != null) {
7763                    appOpPerms.remove(pkg.packageName);
7764                }
7765            }
7766        }
7767        if (r != null) {
7768            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
7769        }
7770
7771        N = pkg.requestedPermissions.size();
7772        r = null;
7773        for (i=0; i<N; i++) {
7774            String perm = pkg.requestedPermissions.get(i);
7775            BasePermission bp = mSettings.mPermissions.get(perm);
7776            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7777                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
7778                if (appOpPerms != null) {
7779                    appOpPerms.remove(pkg.packageName);
7780                    if (appOpPerms.isEmpty()) {
7781                        mAppOpPermissionPackages.remove(perm);
7782                    }
7783                }
7784            }
7785        }
7786        if (r != null) {
7787            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
7788        }
7789
7790        N = pkg.instrumentation.size();
7791        r = null;
7792        for (i=0; i<N; i++) {
7793            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7794            mInstrumentation.remove(a.getComponentName());
7795            if (DEBUG_REMOVE && chatty) {
7796                if (r == null) {
7797                    r = new StringBuilder(256);
7798                } else {
7799                    r.append(' ');
7800                }
7801                r.append(a.info.name);
7802            }
7803        }
7804        if (r != null) {
7805            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
7806        }
7807
7808        r = null;
7809        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7810            // Only system apps can hold shared libraries.
7811            if (pkg.libraryNames != null) {
7812                for (i=0; i<pkg.libraryNames.size(); i++) {
7813                    String name = pkg.libraryNames.get(i);
7814                    SharedLibraryEntry cur = mSharedLibraries.get(name);
7815                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
7816                        mSharedLibraries.remove(name);
7817                        if (DEBUG_REMOVE && chatty) {
7818                            if (r == null) {
7819                                r = new StringBuilder(256);
7820                            } else {
7821                                r.append(' ');
7822                            }
7823                            r.append(name);
7824                        }
7825                    }
7826                }
7827            }
7828        }
7829        if (r != null) {
7830            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
7831        }
7832    }
7833
7834    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
7835        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
7836            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
7837                return true;
7838            }
7839        }
7840        return false;
7841    }
7842
7843    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
7844    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
7845    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
7846
7847    private void updatePermissionsLPw(String changingPkg,
7848            PackageParser.Package pkgInfo, int flags) {
7849        // Make sure there are no dangling permission trees.
7850        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
7851        while (it.hasNext()) {
7852            final BasePermission bp = it.next();
7853            if (bp.packageSetting == null) {
7854                // We may not yet have parsed the package, so just see if
7855                // we still know about its settings.
7856                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
7857            }
7858            if (bp.packageSetting == null) {
7859                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
7860                        + " from package " + bp.sourcePackage);
7861                it.remove();
7862            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
7863                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
7864                    Slog.i(TAG, "Removing old permission tree: " + bp.name
7865                            + " from package " + bp.sourcePackage);
7866                    flags |= UPDATE_PERMISSIONS_ALL;
7867                    it.remove();
7868                }
7869            }
7870        }
7871
7872        // Make sure all dynamic permissions have been assigned to a package,
7873        // and make sure there are no dangling permissions.
7874        it = mSettings.mPermissions.values().iterator();
7875        while (it.hasNext()) {
7876            final BasePermission bp = it.next();
7877            if (bp.type == BasePermission.TYPE_DYNAMIC) {
7878                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
7879                        + bp.name + " pkg=" + bp.sourcePackage
7880                        + " info=" + bp.pendingInfo);
7881                if (bp.packageSetting == null && bp.pendingInfo != null) {
7882                    final BasePermission tree = findPermissionTreeLP(bp.name);
7883                    if (tree != null && tree.perm != null) {
7884                        bp.packageSetting = tree.packageSetting;
7885                        bp.perm = new PackageParser.Permission(tree.perm.owner,
7886                                new PermissionInfo(bp.pendingInfo));
7887                        bp.perm.info.packageName = tree.perm.info.packageName;
7888                        bp.perm.info.name = bp.name;
7889                        bp.uid = tree.uid;
7890                    }
7891                }
7892            }
7893            if (bp.packageSetting == null) {
7894                // We may not yet have parsed the package, so just see if
7895                // we still know about its settings.
7896                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
7897            }
7898            if (bp.packageSetting == null) {
7899                Slog.w(TAG, "Removing dangling permission: " + bp.name
7900                        + " from package " + bp.sourcePackage);
7901                it.remove();
7902            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
7903                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
7904                    Slog.i(TAG, "Removing old permission: " + bp.name
7905                            + " from package " + bp.sourcePackage);
7906                    flags |= UPDATE_PERMISSIONS_ALL;
7907                    it.remove();
7908                }
7909            }
7910        }
7911
7912        // Now update the permissions for all packages, in particular
7913        // replace the granted permissions of the system packages.
7914        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
7915            for (PackageParser.Package pkg : mPackages.values()) {
7916                if (pkg != pkgInfo) {
7917                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
7918                            changingPkg);
7919                }
7920            }
7921        }
7922
7923        if (pkgInfo != null) {
7924            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
7925        }
7926    }
7927
7928    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
7929            String packageOfInterest) {
7930        // IMPORTANT: There are two types of permissions: install and runtime.
7931        // Install time permissions are granted when the app is installed to
7932        // all device users and users added in the future. Runtime permissions
7933        // are granted at runtime explicitly to specific users. Normal and signature
7934        // protected permissions are install time permissions. Dangerous permissions
7935        // are install permissions if the app's target SDK is Lollipop MR1 or older,
7936        // otherwise they are runtime permissions. This function does not manage
7937        // runtime permissions except for the case an app targeting Lollipop MR1
7938        // being upgraded to target a newer SDK, in which case dangerous permissions
7939        // are transformed from install time to runtime ones.
7940
7941        final PackageSetting ps = (PackageSetting) pkg.mExtras;
7942        if (ps == null) {
7943            return;
7944        }
7945
7946        PermissionsState permissionsState = ps.getPermissionsState();
7947        PermissionsState origPermissions = permissionsState;
7948
7949        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
7950
7951        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
7952
7953        boolean changedInstallPermission = false;
7954
7955        if (replace) {
7956            ps.installPermissionsFixed = false;
7957            if (!ps.isSharedUser()) {
7958                origPermissions = new PermissionsState(permissionsState);
7959                permissionsState.reset();
7960            }
7961        }
7962
7963        permissionsState.setGlobalGids(mGlobalGids);
7964
7965        final int N = pkg.requestedPermissions.size();
7966        for (int i=0; i<N; i++) {
7967            final String name = pkg.requestedPermissions.get(i);
7968            final BasePermission bp = mSettings.mPermissions.get(name);
7969
7970            if (DEBUG_INSTALL) {
7971                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
7972            }
7973
7974            if (bp == null || bp.packageSetting == null) {
7975                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7976                    Slog.w(TAG, "Unknown permission " + name
7977                            + " in package " + pkg.packageName);
7978                }
7979                continue;
7980            }
7981
7982            final String perm = bp.name;
7983            boolean allowedSig = false;
7984            int grant = GRANT_DENIED;
7985
7986            // Keep track of app op permissions.
7987            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7988                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
7989                if (pkgs == null) {
7990                    pkgs = new ArraySet<>();
7991                    mAppOpPermissionPackages.put(bp.name, pkgs);
7992                }
7993                pkgs.add(pkg.packageName);
7994            }
7995
7996            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
7997            switch (level) {
7998                case PermissionInfo.PROTECTION_NORMAL: {
7999                    // For all apps normal permissions are install time ones.
8000                    grant = GRANT_INSTALL;
8001                } break;
8002
8003                case PermissionInfo.PROTECTION_DANGEROUS: {
8004                    if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
8005                        // For legacy apps dangerous permissions are install time ones.
8006                        grant = GRANT_INSTALL_LEGACY;
8007                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8008                        // For legacy apps that became modern, install becomes runtime.
8009                        grant = GRANT_UPGRADE;
8010                    } else {
8011                        // For modern apps keep runtime permissions unchanged.
8012                        grant = GRANT_RUNTIME;
8013                    }
8014                } break;
8015
8016                case PermissionInfo.PROTECTION_SIGNATURE: {
8017                    // For all apps signature permissions are install time ones.
8018                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8019                    if (allowedSig) {
8020                        grant = GRANT_INSTALL;
8021                    }
8022                } break;
8023            }
8024
8025            if (DEBUG_INSTALL) {
8026                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8027            }
8028
8029            if (grant != GRANT_DENIED) {
8030                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8031                    // If this is an existing, non-system package, then
8032                    // we can't add any new permissions to it.
8033                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8034                        // Except...  if this is a permission that was added
8035                        // to the platform (note: need to only do this when
8036                        // updating the platform).
8037                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8038                            grant = GRANT_DENIED;
8039                        }
8040                    }
8041                }
8042
8043                switch (grant) {
8044                    case GRANT_INSTALL: {
8045                        // Revoke this as runtime permission to handle the case of
8046                        // a runtime permission being downgraded to an install one.
8047                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8048                            if (origPermissions.getRuntimePermissionState(
8049                                    bp.name, userId) != null) {
8050                                // Revoke the runtime permission and clear the flags.
8051                                origPermissions.revokeRuntimePermission(bp, userId);
8052                                origPermissions.updatePermissionFlags(bp, userId,
8053                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8054                                // If we revoked a permission permission, we have to write.
8055                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8056                                        changedRuntimePermissionUserIds, userId);
8057                            }
8058                        }
8059                        // Grant an install permission.
8060                        if (permissionsState.grantInstallPermission(bp) !=
8061                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8062                            changedInstallPermission = true;
8063                        }
8064                    } break;
8065
8066                    case GRANT_INSTALL_LEGACY: {
8067                        // Grant an install permission.
8068                        if (permissionsState.grantInstallPermission(bp) !=
8069                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8070                            changedInstallPermission = true;
8071                        }
8072                    } break;
8073
8074                    case GRANT_RUNTIME: {
8075                        // Grant previously granted runtime permissions.
8076                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8077                            PermissionState permissionState = origPermissions
8078                                    .getRuntimePermissionState(bp.name, userId);
8079                            final int flags = permissionState != null
8080                                    ? permissionState.getFlags() : 0;
8081                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8082                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8083                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8084                                    // If we cannot put the permission as it was, we have to write.
8085                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8086                                            changedRuntimePermissionUserIds, userId);
8087                                }
8088                            }
8089                            // Propagate the permission flags.
8090                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8091                        }
8092                    } break;
8093
8094                    case GRANT_UPGRADE: {
8095                        // Grant runtime permissions for a previously held install permission.
8096                        PermissionState permissionState = origPermissions
8097                                .getInstallPermissionState(bp.name);
8098                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8099
8100                        if (origPermissions.revokeInstallPermission(bp)
8101                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8102                            // We will be transferring the permission flags, so clear them.
8103                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8104                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8105                            changedInstallPermission = true;
8106                        }
8107
8108                        // If the permission is not to be promoted to runtime we ignore it and
8109                        // also its other flags as they are not applicable to install permissions.
8110                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8111                            for (int userId : currentUserIds) {
8112                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8113                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8114                                    // Transfer the permission flags.
8115                                    permissionsState.updatePermissionFlags(bp, userId,
8116                                            flags, flags);
8117                                    // If we granted the permission, we have to write.
8118                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8119                                            changedRuntimePermissionUserIds, userId);
8120                                }
8121                            }
8122                        }
8123                    } break;
8124
8125                    default: {
8126                        if (packageOfInterest == null
8127                                || packageOfInterest.equals(pkg.packageName)) {
8128                            Slog.w(TAG, "Not granting permission " + perm
8129                                    + " to package " + pkg.packageName
8130                                    + " because it was previously installed without");
8131                        }
8132                    } break;
8133                }
8134            } else {
8135                if (permissionsState.revokeInstallPermission(bp) !=
8136                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8137                    // Also drop the permission flags.
8138                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8139                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8140                    changedInstallPermission = true;
8141                    Slog.i(TAG, "Un-granting permission " + perm
8142                            + " from package " + pkg.packageName
8143                            + " (protectionLevel=" + bp.protectionLevel
8144                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8145                            + ")");
8146                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8147                    // Don't print warning for app op permissions, since it is fine for them
8148                    // not to be granted, there is a UI for the user to decide.
8149                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8150                        Slog.w(TAG, "Not granting permission " + perm
8151                                + " to package " + pkg.packageName
8152                                + " (protectionLevel=" + bp.protectionLevel
8153                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8154                                + ")");
8155                    }
8156                }
8157            }
8158        }
8159
8160        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8161                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8162            // This is the first that we have heard about this package, so the
8163            // permissions we have now selected are fixed until explicitly
8164            // changed.
8165            ps.installPermissionsFixed = true;
8166        }
8167
8168        // Persist the runtime permissions state for users with changes.
8169        for (int userId : changedRuntimePermissionUserIds) {
8170            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
8171        }
8172    }
8173
8174    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8175        boolean allowed = false;
8176        final int NP = PackageParser.NEW_PERMISSIONS.length;
8177        for (int ip=0; ip<NP; ip++) {
8178            final PackageParser.NewPermissionInfo npi
8179                    = PackageParser.NEW_PERMISSIONS[ip];
8180            if (npi.name.equals(perm)
8181                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8182                allowed = true;
8183                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8184                        + pkg.packageName);
8185                break;
8186            }
8187        }
8188        return allowed;
8189    }
8190
8191    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8192            BasePermission bp, PermissionsState origPermissions) {
8193        boolean allowed;
8194        allowed = (compareSignatures(
8195                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8196                        == PackageManager.SIGNATURE_MATCH)
8197                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8198                        == PackageManager.SIGNATURE_MATCH);
8199        if (!allowed && (bp.protectionLevel
8200                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
8201            if (isSystemApp(pkg)) {
8202                // For updated system applications, a system permission
8203                // is granted only if it had been defined by the original application.
8204                if (pkg.isUpdatedSystemApp()) {
8205                    final PackageSetting sysPs = mSettings
8206                            .getDisabledSystemPkgLPr(pkg.packageName);
8207                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8208                        // If the original was granted this permission, we take
8209                        // that grant decision as read and propagate it to the
8210                        // update.
8211                        if (sysPs.isPrivileged()) {
8212                            allowed = true;
8213                        }
8214                    } else {
8215                        // The system apk may have been updated with an older
8216                        // version of the one on the data partition, but which
8217                        // granted a new system permission that it didn't have
8218                        // before.  In this case we do want to allow the app to
8219                        // now get the new permission if the ancestral apk is
8220                        // privileged to get it.
8221                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
8222                            for (int j=0;
8223                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
8224                                if (perm.equals(
8225                                        sysPs.pkg.requestedPermissions.get(j))) {
8226                                    allowed = true;
8227                                    break;
8228                                }
8229                            }
8230                        }
8231                    }
8232                } else {
8233                    allowed = isPrivilegedApp(pkg);
8234                }
8235            }
8236        }
8237        if (!allowed && (bp.protectionLevel
8238                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8239            // For development permissions, a development permission
8240            // is granted only if it was already granted.
8241            allowed = origPermissions.hasInstallPermission(perm);
8242        }
8243        return allowed;
8244    }
8245
8246    final class ActivityIntentResolver
8247            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8248        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8249                boolean defaultOnly, int userId) {
8250            if (!sUserManager.exists(userId)) return null;
8251            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8252            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8253        }
8254
8255        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8256                int userId) {
8257            if (!sUserManager.exists(userId)) return null;
8258            mFlags = flags;
8259            return super.queryIntent(intent, resolvedType,
8260                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8261        }
8262
8263        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8264                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8265            if (!sUserManager.exists(userId)) return null;
8266            if (packageActivities == null) {
8267                return null;
8268            }
8269            mFlags = flags;
8270            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8271            final int N = packageActivities.size();
8272            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8273                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8274
8275            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8276            for (int i = 0; i < N; ++i) {
8277                intentFilters = packageActivities.get(i).intents;
8278                if (intentFilters != null && intentFilters.size() > 0) {
8279                    PackageParser.ActivityIntentInfo[] array =
8280                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
8281                    intentFilters.toArray(array);
8282                    listCut.add(array);
8283                }
8284            }
8285            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8286        }
8287
8288        public final void addActivity(PackageParser.Activity a, String type) {
8289            final boolean systemApp = a.info.applicationInfo.isSystemApp();
8290            mActivities.put(a.getComponentName(), a);
8291            if (DEBUG_SHOW_INFO)
8292                Log.v(
8293                TAG, "  " + type + " " +
8294                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8295            if (DEBUG_SHOW_INFO)
8296                Log.v(TAG, "    Class=" + a.info.name);
8297            final int NI = a.intents.size();
8298            for (int j=0; j<NI; j++) {
8299                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8300                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
8301                    intent.setPriority(0);
8302                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
8303                            + a.className + " with priority > 0, forcing to 0");
8304                }
8305                if (DEBUG_SHOW_INFO) {
8306                    Log.v(TAG, "    IntentFilter:");
8307                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8308                }
8309                if (!intent.debugCheck()) {
8310                    Log.w(TAG, "==> For Activity " + a.info.name);
8311                }
8312                addFilter(intent);
8313            }
8314        }
8315
8316        public final void removeActivity(PackageParser.Activity a, String type) {
8317            mActivities.remove(a.getComponentName());
8318            if (DEBUG_SHOW_INFO) {
8319                Log.v(TAG, "  " + type + " "
8320                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
8321                                : a.info.name) + ":");
8322                Log.v(TAG, "    Class=" + a.info.name);
8323            }
8324            final int NI = a.intents.size();
8325            for (int j=0; j<NI; j++) {
8326                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8327                if (DEBUG_SHOW_INFO) {
8328                    Log.v(TAG, "    IntentFilter:");
8329                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8330                }
8331                removeFilter(intent);
8332            }
8333        }
8334
8335        @Override
8336        protected boolean allowFilterResult(
8337                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
8338            ActivityInfo filterAi = filter.activity.info;
8339            for (int i=dest.size()-1; i>=0; i--) {
8340                ActivityInfo destAi = dest.get(i).activityInfo;
8341                if (destAi.name == filterAi.name
8342                        && destAi.packageName == filterAi.packageName) {
8343                    return false;
8344                }
8345            }
8346            return true;
8347        }
8348
8349        @Override
8350        protected ActivityIntentInfo[] newArray(int size) {
8351            return new ActivityIntentInfo[size];
8352        }
8353
8354        @Override
8355        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
8356            if (!sUserManager.exists(userId)) return true;
8357            PackageParser.Package p = filter.activity.owner;
8358            if (p != null) {
8359                PackageSetting ps = (PackageSetting)p.mExtras;
8360                if (ps != null) {
8361                    // System apps are never considered stopped for purposes of
8362                    // filtering, because there may be no way for the user to
8363                    // actually re-launch them.
8364                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
8365                            && ps.getStopped(userId);
8366                }
8367            }
8368            return false;
8369        }
8370
8371        @Override
8372        protected boolean isPackageForFilter(String packageName,
8373                PackageParser.ActivityIntentInfo info) {
8374            return packageName.equals(info.activity.owner.packageName);
8375        }
8376
8377        @Override
8378        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
8379                int match, int userId) {
8380            if (!sUserManager.exists(userId)) return null;
8381            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
8382                return null;
8383            }
8384            final PackageParser.Activity activity = info.activity;
8385            if (mSafeMode && (activity.info.applicationInfo.flags
8386                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8387                return null;
8388            }
8389            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
8390            if (ps == null) {
8391                return null;
8392            }
8393            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
8394                    ps.readUserState(userId), userId);
8395            if (ai == null) {
8396                return null;
8397            }
8398            final ResolveInfo res = new ResolveInfo();
8399            res.activityInfo = ai;
8400            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8401                res.filter = info;
8402            }
8403            if (info != null) {
8404                res.handleAllWebDataURI = info.handleAllWebDataURI();
8405            }
8406            res.priority = info.getPriority();
8407            res.preferredOrder = activity.owner.mPreferredOrder;
8408            //System.out.println("Result: " + res.activityInfo.className +
8409            //                   " = " + res.priority);
8410            res.match = match;
8411            res.isDefault = info.hasDefault;
8412            res.labelRes = info.labelRes;
8413            res.nonLocalizedLabel = info.nonLocalizedLabel;
8414            if (userNeedsBadging(userId)) {
8415                res.noResourceId = true;
8416            } else {
8417                res.icon = info.icon;
8418            }
8419            res.iconResourceId = info.icon;
8420            res.system = res.activityInfo.applicationInfo.isSystemApp();
8421            return res;
8422        }
8423
8424        @Override
8425        protected void sortResults(List<ResolveInfo> results) {
8426            Collections.sort(results, mResolvePrioritySorter);
8427        }
8428
8429        @Override
8430        protected void dumpFilter(PrintWriter out, String prefix,
8431                PackageParser.ActivityIntentInfo filter) {
8432            out.print(prefix); out.print(
8433                    Integer.toHexString(System.identityHashCode(filter.activity)));
8434                    out.print(' ');
8435                    filter.activity.printComponentShortName(out);
8436                    out.print(" filter ");
8437                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8438        }
8439
8440        @Override
8441        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
8442            return filter.activity;
8443        }
8444
8445        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8446            PackageParser.Activity activity = (PackageParser.Activity)label;
8447            out.print(prefix); out.print(
8448                    Integer.toHexString(System.identityHashCode(activity)));
8449                    out.print(' ');
8450                    activity.printComponentShortName(out);
8451            if (count > 1) {
8452                out.print(" ("); out.print(count); out.print(" filters)");
8453            }
8454            out.println();
8455        }
8456
8457//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8458//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8459//            final List<ResolveInfo> retList = Lists.newArrayList();
8460//            while (i.hasNext()) {
8461//                final ResolveInfo resolveInfo = i.next();
8462//                if (isEnabledLP(resolveInfo.activityInfo)) {
8463//                    retList.add(resolveInfo);
8464//                }
8465//            }
8466//            return retList;
8467//        }
8468
8469        // Keys are String (activity class name), values are Activity.
8470        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
8471                = new ArrayMap<ComponentName, PackageParser.Activity>();
8472        private int mFlags;
8473    }
8474
8475    private final class ServiceIntentResolver
8476            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
8477        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8478                boolean defaultOnly, int userId) {
8479            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8480            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8481        }
8482
8483        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8484                int userId) {
8485            if (!sUserManager.exists(userId)) return null;
8486            mFlags = flags;
8487            return super.queryIntent(intent, resolvedType,
8488                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8489        }
8490
8491        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8492                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
8493            if (!sUserManager.exists(userId)) return null;
8494            if (packageServices == null) {
8495                return null;
8496            }
8497            mFlags = flags;
8498            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8499            final int N = packageServices.size();
8500            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
8501                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
8502
8503            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
8504            for (int i = 0; i < N; ++i) {
8505                intentFilters = packageServices.get(i).intents;
8506                if (intentFilters != null && intentFilters.size() > 0) {
8507                    PackageParser.ServiceIntentInfo[] array =
8508                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
8509                    intentFilters.toArray(array);
8510                    listCut.add(array);
8511                }
8512            }
8513            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8514        }
8515
8516        public final void addService(PackageParser.Service s) {
8517            mServices.put(s.getComponentName(), s);
8518            if (DEBUG_SHOW_INFO) {
8519                Log.v(TAG, "  "
8520                        + (s.info.nonLocalizedLabel != null
8521                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8522                Log.v(TAG, "    Class=" + s.info.name);
8523            }
8524            final int NI = s.intents.size();
8525            int j;
8526            for (j=0; j<NI; j++) {
8527                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8528                if (DEBUG_SHOW_INFO) {
8529                    Log.v(TAG, "    IntentFilter:");
8530                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8531                }
8532                if (!intent.debugCheck()) {
8533                    Log.w(TAG, "==> For Service " + s.info.name);
8534                }
8535                addFilter(intent);
8536            }
8537        }
8538
8539        public final void removeService(PackageParser.Service s) {
8540            mServices.remove(s.getComponentName());
8541            if (DEBUG_SHOW_INFO) {
8542                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
8543                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8544                Log.v(TAG, "    Class=" + s.info.name);
8545            }
8546            final int NI = s.intents.size();
8547            int j;
8548            for (j=0; j<NI; j++) {
8549                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8550                if (DEBUG_SHOW_INFO) {
8551                    Log.v(TAG, "    IntentFilter:");
8552                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8553                }
8554                removeFilter(intent);
8555            }
8556        }
8557
8558        @Override
8559        protected boolean allowFilterResult(
8560                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
8561            ServiceInfo filterSi = filter.service.info;
8562            for (int i=dest.size()-1; i>=0; i--) {
8563                ServiceInfo destAi = dest.get(i).serviceInfo;
8564                if (destAi.name == filterSi.name
8565                        && destAi.packageName == filterSi.packageName) {
8566                    return false;
8567                }
8568            }
8569            return true;
8570        }
8571
8572        @Override
8573        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
8574            return new PackageParser.ServiceIntentInfo[size];
8575        }
8576
8577        @Override
8578        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
8579            if (!sUserManager.exists(userId)) return true;
8580            PackageParser.Package p = filter.service.owner;
8581            if (p != null) {
8582                PackageSetting ps = (PackageSetting)p.mExtras;
8583                if (ps != null) {
8584                    // System apps are never considered stopped for purposes of
8585                    // filtering, because there may be no way for the user to
8586                    // actually re-launch them.
8587                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8588                            && ps.getStopped(userId);
8589                }
8590            }
8591            return false;
8592        }
8593
8594        @Override
8595        protected boolean isPackageForFilter(String packageName,
8596                PackageParser.ServiceIntentInfo info) {
8597            return packageName.equals(info.service.owner.packageName);
8598        }
8599
8600        @Override
8601        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
8602                int match, int userId) {
8603            if (!sUserManager.exists(userId)) return null;
8604            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
8605            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
8606                return null;
8607            }
8608            final PackageParser.Service service = info.service;
8609            if (mSafeMode && (service.info.applicationInfo.flags
8610                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8611                return null;
8612            }
8613            PackageSetting ps = (PackageSetting) service.owner.mExtras;
8614            if (ps == null) {
8615                return null;
8616            }
8617            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
8618                    ps.readUserState(userId), userId);
8619            if (si == null) {
8620                return null;
8621            }
8622            final ResolveInfo res = new ResolveInfo();
8623            res.serviceInfo = si;
8624            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8625                res.filter = filter;
8626            }
8627            res.priority = info.getPriority();
8628            res.preferredOrder = service.owner.mPreferredOrder;
8629            res.match = match;
8630            res.isDefault = info.hasDefault;
8631            res.labelRes = info.labelRes;
8632            res.nonLocalizedLabel = info.nonLocalizedLabel;
8633            res.icon = info.icon;
8634            res.system = res.serviceInfo.applicationInfo.isSystemApp();
8635            return res;
8636        }
8637
8638        @Override
8639        protected void sortResults(List<ResolveInfo> results) {
8640            Collections.sort(results, mResolvePrioritySorter);
8641        }
8642
8643        @Override
8644        protected void dumpFilter(PrintWriter out, String prefix,
8645                PackageParser.ServiceIntentInfo filter) {
8646            out.print(prefix); out.print(
8647                    Integer.toHexString(System.identityHashCode(filter.service)));
8648                    out.print(' ');
8649                    filter.service.printComponentShortName(out);
8650                    out.print(" filter ");
8651                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8652        }
8653
8654        @Override
8655        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
8656            return filter.service;
8657        }
8658
8659        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8660            PackageParser.Service service = (PackageParser.Service)label;
8661            out.print(prefix); out.print(
8662                    Integer.toHexString(System.identityHashCode(service)));
8663                    out.print(' ');
8664                    service.printComponentShortName(out);
8665            if (count > 1) {
8666                out.print(" ("); out.print(count); out.print(" filters)");
8667            }
8668            out.println();
8669        }
8670
8671//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8672//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8673//            final List<ResolveInfo> retList = Lists.newArrayList();
8674//            while (i.hasNext()) {
8675//                final ResolveInfo resolveInfo = (ResolveInfo) i;
8676//                if (isEnabledLP(resolveInfo.serviceInfo)) {
8677//                    retList.add(resolveInfo);
8678//                }
8679//            }
8680//            return retList;
8681//        }
8682
8683        // Keys are String (activity class name), values are Activity.
8684        private final ArrayMap<ComponentName, PackageParser.Service> mServices
8685                = new ArrayMap<ComponentName, PackageParser.Service>();
8686        private int mFlags;
8687    };
8688
8689    private final class ProviderIntentResolver
8690            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
8691        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8692                boolean defaultOnly, int userId) {
8693            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8694            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8695        }
8696
8697        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8698                int userId) {
8699            if (!sUserManager.exists(userId))
8700                return null;
8701            mFlags = flags;
8702            return super.queryIntent(intent, resolvedType,
8703                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8704        }
8705
8706        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8707                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
8708            if (!sUserManager.exists(userId))
8709                return null;
8710            if (packageProviders == null) {
8711                return null;
8712            }
8713            mFlags = flags;
8714            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
8715            final int N = packageProviders.size();
8716            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
8717                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
8718
8719            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
8720            for (int i = 0; i < N; ++i) {
8721                intentFilters = packageProviders.get(i).intents;
8722                if (intentFilters != null && intentFilters.size() > 0) {
8723                    PackageParser.ProviderIntentInfo[] array =
8724                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
8725                    intentFilters.toArray(array);
8726                    listCut.add(array);
8727                }
8728            }
8729            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8730        }
8731
8732        public final void addProvider(PackageParser.Provider p) {
8733            if (mProviders.containsKey(p.getComponentName())) {
8734                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
8735                return;
8736            }
8737
8738            mProviders.put(p.getComponentName(), p);
8739            if (DEBUG_SHOW_INFO) {
8740                Log.v(TAG, "  "
8741                        + (p.info.nonLocalizedLabel != null
8742                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
8743                Log.v(TAG, "    Class=" + p.info.name);
8744            }
8745            final int NI = p.intents.size();
8746            int j;
8747            for (j = 0; j < NI; j++) {
8748                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
8749                if (DEBUG_SHOW_INFO) {
8750                    Log.v(TAG, "    IntentFilter:");
8751                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8752                }
8753                if (!intent.debugCheck()) {
8754                    Log.w(TAG, "==> For Provider " + p.info.name);
8755                }
8756                addFilter(intent);
8757            }
8758        }
8759
8760        public final void removeProvider(PackageParser.Provider p) {
8761            mProviders.remove(p.getComponentName());
8762            if (DEBUG_SHOW_INFO) {
8763                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
8764                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
8765                Log.v(TAG, "    Class=" + p.info.name);
8766            }
8767            final int NI = p.intents.size();
8768            int j;
8769            for (j = 0; j < NI; j++) {
8770                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
8771                if (DEBUG_SHOW_INFO) {
8772                    Log.v(TAG, "    IntentFilter:");
8773                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8774                }
8775                removeFilter(intent);
8776            }
8777        }
8778
8779        @Override
8780        protected boolean allowFilterResult(
8781                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
8782            ProviderInfo filterPi = filter.provider.info;
8783            for (int i = dest.size() - 1; i >= 0; i--) {
8784                ProviderInfo destPi = dest.get(i).providerInfo;
8785                if (destPi.name == filterPi.name
8786                        && destPi.packageName == filterPi.packageName) {
8787                    return false;
8788                }
8789            }
8790            return true;
8791        }
8792
8793        @Override
8794        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
8795            return new PackageParser.ProviderIntentInfo[size];
8796        }
8797
8798        @Override
8799        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
8800            if (!sUserManager.exists(userId))
8801                return true;
8802            PackageParser.Package p = filter.provider.owner;
8803            if (p != null) {
8804                PackageSetting ps = (PackageSetting) p.mExtras;
8805                if (ps != null) {
8806                    // System apps are never considered stopped for purposes of
8807                    // filtering, because there may be no way for the user to
8808                    // actually re-launch them.
8809                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8810                            && ps.getStopped(userId);
8811                }
8812            }
8813            return false;
8814        }
8815
8816        @Override
8817        protected boolean isPackageForFilter(String packageName,
8818                PackageParser.ProviderIntentInfo info) {
8819            return packageName.equals(info.provider.owner.packageName);
8820        }
8821
8822        @Override
8823        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
8824                int match, int userId) {
8825            if (!sUserManager.exists(userId))
8826                return null;
8827            final PackageParser.ProviderIntentInfo info = filter;
8828            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
8829                return null;
8830            }
8831            final PackageParser.Provider provider = info.provider;
8832            if (mSafeMode && (provider.info.applicationInfo.flags
8833                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
8834                return null;
8835            }
8836            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
8837            if (ps == null) {
8838                return null;
8839            }
8840            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
8841                    ps.readUserState(userId), userId);
8842            if (pi == null) {
8843                return null;
8844            }
8845            final ResolveInfo res = new ResolveInfo();
8846            res.providerInfo = pi;
8847            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
8848                res.filter = filter;
8849            }
8850            res.priority = info.getPriority();
8851            res.preferredOrder = provider.owner.mPreferredOrder;
8852            res.match = match;
8853            res.isDefault = info.hasDefault;
8854            res.labelRes = info.labelRes;
8855            res.nonLocalizedLabel = info.nonLocalizedLabel;
8856            res.icon = info.icon;
8857            res.system = res.providerInfo.applicationInfo.isSystemApp();
8858            return res;
8859        }
8860
8861        @Override
8862        protected void sortResults(List<ResolveInfo> results) {
8863            Collections.sort(results, mResolvePrioritySorter);
8864        }
8865
8866        @Override
8867        protected void dumpFilter(PrintWriter out, String prefix,
8868                PackageParser.ProviderIntentInfo filter) {
8869            out.print(prefix);
8870            out.print(
8871                    Integer.toHexString(System.identityHashCode(filter.provider)));
8872            out.print(' ');
8873            filter.provider.printComponentShortName(out);
8874            out.print(" filter ");
8875            out.println(Integer.toHexString(System.identityHashCode(filter)));
8876        }
8877
8878        @Override
8879        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
8880            return filter.provider;
8881        }
8882
8883        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8884            PackageParser.Provider provider = (PackageParser.Provider)label;
8885            out.print(prefix); out.print(
8886                    Integer.toHexString(System.identityHashCode(provider)));
8887                    out.print(' ');
8888                    provider.printComponentShortName(out);
8889            if (count > 1) {
8890                out.print(" ("); out.print(count); out.print(" filters)");
8891            }
8892            out.println();
8893        }
8894
8895        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
8896                = new ArrayMap<ComponentName, PackageParser.Provider>();
8897        private int mFlags;
8898    };
8899
8900    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
8901            new Comparator<ResolveInfo>() {
8902        public int compare(ResolveInfo r1, ResolveInfo r2) {
8903            int v1 = r1.priority;
8904            int v2 = r2.priority;
8905            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
8906            if (v1 != v2) {
8907                return (v1 > v2) ? -1 : 1;
8908            }
8909            v1 = r1.preferredOrder;
8910            v2 = r2.preferredOrder;
8911            if (v1 != v2) {
8912                return (v1 > v2) ? -1 : 1;
8913            }
8914            if (r1.isDefault != r2.isDefault) {
8915                return r1.isDefault ? -1 : 1;
8916            }
8917            v1 = r1.match;
8918            v2 = r2.match;
8919            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
8920            if (v1 != v2) {
8921                return (v1 > v2) ? -1 : 1;
8922            }
8923            if (r1.system != r2.system) {
8924                return r1.system ? -1 : 1;
8925            }
8926            return 0;
8927        }
8928    };
8929
8930    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
8931            new Comparator<ProviderInfo>() {
8932        public int compare(ProviderInfo p1, ProviderInfo p2) {
8933            final int v1 = p1.initOrder;
8934            final int v2 = p2.initOrder;
8935            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
8936        }
8937    };
8938
8939    final void sendPackageBroadcast(final String action, final String pkg,
8940            final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
8941            final int[] userIds) {
8942        mHandler.post(new Runnable() {
8943            @Override
8944            public void run() {
8945                try {
8946                    final IActivityManager am = ActivityManagerNative.getDefault();
8947                    if (am == null) return;
8948                    final int[] resolvedUserIds;
8949                    if (userIds == null) {
8950                        resolvedUserIds = am.getRunningUserIds();
8951                    } else {
8952                        resolvedUserIds = userIds;
8953                    }
8954                    for (int id : resolvedUserIds) {
8955                        final Intent intent = new Intent(action,
8956                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
8957                        if (extras != null) {
8958                            intent.putExtras(extras);
8959                        }
8960                        if (targetPkg != null) {
8961                            intent.setPackage(targetPkg);
8962                        }
8963                        // Modify the UID when posting to other users
8964                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
8965                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
8966                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
8967                            intent.putExtra(Intent.EXTRA_UID, uid);
8968                        }
8969                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
8970                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
8971                        if (DEBUG_BROADCASTS) {
8972                            RuntimeException here = new RuntimeException("here");
8973                            here.fillInStackTrace();
8974                            Slog.d(TAG, "Sending to user " + id + ": "
8975                                    + intent.toShortString(false, true, false, false)
8976                                    + " " + intent.getExtras(), here);
8977                        }
8978                        am.broadcastIntent(null, intent, null, finishedReceiver,
8979                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
8980                                null, finishedReceiver != null, false, id);
8981                    }
8982                } catch (RemoteException ex) {
8983                }
8984            }
8985        });
8986    }
8987
8988    /**
8989     * Check if the external storage media is available. This is true if there
8990     * is a mounted external storage medium or if the external storage is
8991     * emulated.
8992     */
8993    private boolean isExternalMediaAvailable() {
8994        return mMediaMounted || Environment.isExternalStorageEmulated();
8995    }
8996
8997    @Override
8998    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
8999        // writer
9000        synchronized (mPackages) {
9001            if (!isExternalMediaAvailable()) {
9002                // If the external storage is no longer mounted at this point,
9003                // the caller may not have been able to delete all of this
9004                // packages files and can not delete any more.  Bail.
9005                return null;
9006            }
9007            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9008            if (lastPackage != null) {
9009                pkgs.remove(lastPackage);
9010            }
9011            if (pkgs.size() > 0) {
9012                return pkgs.get(0);
9013            }
9014        }
9015        return null;
9016    }
9017
9018    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9019        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9020                userId, andCode ? 1 : 0, packageName);
9021        if (mSystemReady) {
9022            msg.sendToTarget();
9023        } else {
9024            if (mPostSystemReadyMessages == null) {
9025                mPostSystemReadyMessages = new ArrayList<>();
9026            }
9027            mPostSystemReadyMessages.add(msg);
9028        }
9029    }
9030
9031    void startCleaningPackages() {
9032        // reader
9033        synchronized (mPackages) {
9034            if (!isExternalMediaAvailable()) {
9035                return;
9036            }
9037            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9038                return;
9039            }
9040        }
9041        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9042        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9043        IActivityManager am = ActivityManagerNative.getDefault();
9044        if (am != null) {
9045            try {
9046                am.startService(null, intent, null, UserHandle.USER_OWNER);
9047            } catch (RemoteException e) {
9048            }
9049        }
9050    }
9051
9052    @Override
9053    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9054            int installFlags, String installerPackageName, VerificationParams verificationParams,
9055            String packageAbiOverride) {
9056        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9057                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9058    }
9059
9060    @Override
9061    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9062            int installFlags, String installerPackageName, VerificationParams verificationParams,
9063            String packageAbiOverride, int userId) {
9064        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9065
9066        final int callingUid = Binder.getCallingUid();
9067        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9068
9069        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9070            try {
9071                if (observer != null) {
9072                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9073                }
9074            } catch (RemoteException re) {
9075            }
9076            return;
9077        }
9078
9079        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9080            installFlags |= PackageManager.INSTALL_FROM_ADB;
9081
9082        } else {
9083            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9084            // about installerPackageName.
9085
9086            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9087            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9088        }
9089
9090        UserHandle user;
9091        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9092            user = UserHandle.ALL;
9093        } else {
9094            user = new UserHandle(userId);
9095        }
9096
9097        // Only system components can circumvent runtime permissions when installing.
9098        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9099                && mContext.checkCallingOrSelfPermission(Manifest.permission
9100                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9101            throw new SecurityException("You need the "
9102                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9103                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9104        }
9105
9106        verificationParams.setInstallerUid(callingUid);
9107
9108        final File originFile = new File(originPath);
9109        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9110
9111        final Message msg = mHandler.obtainMessage(INIT_COPY);
9112        msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName,
9113                null, verificationParams, user, packageAbiOverride);
9114        mHandler.sendMessage(msg);
9115    }
9116
9117    void installStage(String packageName, File stagedDir, String stagedCid,
9118            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
9119            String installerPackageName, int installerUid, UserHandle user) {
9120        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
9121                params.referrerUri, installerUid, null);
9122
9123        final OriginInfo origin;
9124        if (stagedDir != null) {
9125            origin = OriginInfo.fromStagedFile(stagedDir);
9126        } else {
9127            origin = OriginInfo.fromStagedContainer(stagedCid);
9128        }
9129
9130        final Message msg = mHandler.obtainMessage(INIT_COPY);
9131        msg.obj = new InstallParams(origin, null, observer, params.installFlags,
9132                installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride);
9133        mHandler.sendMessage(msg);
9134    }
9135
9136    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
9137        Bundle extras = new Bundle(1);
9138        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
9139
9140        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
9141                packageName, extras, null, null, new int[] {userId});
9142        try {
9143            IActivityManager am = ActivityManagerNative.getDefault();
9144            final boolean isSystem =
9145                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
9146            if (isSystem && am.isUserRunning(userId, false)) {
9147                // The just-installed/enabled app is bundled on the system, so presumed
9148                // to be able to run automatically without needing an explicit launch.
9149                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
9150                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
9151                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
9152                        .setPackage(packageName);
9153                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
9154                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
9155            }
9156        } catch (RemoteException e) {
9157            // shouldn't happen
9158            Slog.w(TAG, "Unable to bootstrap installed package", e);
9159        }
9160    }
9161
9162    @Override
9163    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9164            int userId) {
9165        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9166        PackageSetting pkgSetting;
9167        final int uid = Binder.getCallingUid();
9168        enforceCrossUserPermission(uid, userId, true, true,
9169                "setApplicationHiddenSetting for user " + userId);
9170
9171        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9172            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9173            return false;
9174        }
9175
9176        long callingId = Binder.clearCallingIdentity();
9177        try {
9178            boolean sendAdded = false;
9179            boolean sendRemoved = false;
9180            // writer
9181            synchronized (mPackages) {
9182                pkgSetting = mSettings.mPackages.get(packageName);
9183                if (pkgSetting == null) {
9184                    return false;
9185                }
9186                if (pkgSetting.getHidden(userId) != hidden) {
9187                    pkgSetting.setHidden(hidden, userId);
9188                    mSettings.writePackageRestrictionsLPr(userId);
9189                    if (hidden) {
9190                        sendRemoved = true;
9191                    } else {
9192                        sendAdded = true;
9193                    }
9194                }
9195            }
9196            if (sendAdded) {
9197                sendPackageAddedForUser(packageName, pkgSetting, userId);
9198                return true;
9199            }
9200            if (sendRemoved) {
9201                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
9202                        "hiding pkg");
9203                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
9204            }
9205        } finally {
9206            Binder.restoreCallingIdentity(callingId);
9207        }
9208        return false;
9209    }
9210
9211    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9212            int userId) {
9213        final PackageRemovedInfo info = new PackageRemovedInfo();
9214        info.removedPackage = packageName;
9215        info.removedUsers = new int[] {userId};
9216        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9217        info.sendBroadcast(false, false, false);
9218    }
9219
9220    /**
9221     * Returns true if application is not found or there was an error. Otherwise it returns
9222     * the hidden state of the package for the given user.
9223     */
9224    @Override
9225    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9226        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9227        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9228                false, "getApplicationHidden for user " + userId);
9229        PackageSetting pkgSetting;
9230        long callingId = Binder.clearCallingIdentity();
9231        try {
9232            // writer
9233            synchronized (mPackages) {
9234                pkgSetting = mSettings.mPackages.get(packageName);
9235                if (pkgSetting == null) {
9236                    return true;
9237                }
9238                return pkgSetting.getHidden(userId);
9239            }
9240        } finally {
9241            Binder.restoreCallingIdentity(callingId);
9242        }
9243    }
9244
9245    /**
9246     * @hide
9247     */
9248    @Override
9249    public int installExistingPackageAsUser(String packageName, int userId) {
9250        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9251                null);
9252        PackageSetting pkgSetting;
9253        final int uid = Binder.getCallingUid();
9254        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9255                + userId);
9256        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9257            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9258        }
9259
9260        long callingId = Binder.clearCallingIdentity();
9261        try {
9262            boolean sendAdded = false;
9263
9264            // writer
9265            synchronized (mPackages) {
9266                pkgSetting = mSettings.mPackages.get(packageName);
9267                if (pkgSetting == null) {
9268                    return PackageManager.INSTALL_FAILED_INVALID_URI;
9269                }
9270                if (!pkgSetting.getInstalled(userId)) {
9271                    pkgSetting.setInstalled(true, userId);
9272                    pkgSetting.setHidden(false, userId);
9273                    mSettings.writePackageRestrictionsLPr(userId);
9274                    sendAdded = true;
9275                }
9276            }
9277
9278            if (sendAdded) {
9279                sendPackageAddedForUser(packageName, pkgSetting, userId);
9280            }
9281        } finally {
9282            Binder.restoreCallingIdentity(callingId);
9283        }
9284
9285        return PackageManager.INSTALL_SUCCEEDED;
9286    }
9287
9288    boolean isUserRestricted(int userId, String restrictionKey) {
9289        Bundle restrictions = sUserManager.getUserRestrictions(userId);
9290        if (restrictions.getBoolean(restrictionKey, false)) {
9291            Log.w(TAG, "User is restricted: " + restrictionKey);
9292            return true;
9293        }
9294        return false;
9295    }
9296
9297    @Override
9298    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
9299        mContext.enforceCallingOrSelfPermission(
9300                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9301                "Only package verification agents can verify applications");
9302
9303        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9304        final PackageVerificationResponse response = new PackageVerificationResponse(
9305                verificationCode, Binder.getCallingUid());
9306        msg.arg1 = id;
9307        msg.obj = response;
9308        mHandler.sendMessage(msg);
9309    }
9310
9311    @Override
9312    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
9313            long millisecondsToDelay) {
9314        mContext.enforceCallingOrSelfPermission(
9315                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9316                "Only package verification agents can extend verification timeouts");
9317
9318        final PackageVerificationState state = mPendingVerification.get(id);
9319        final PackageVerificationResponse response = new PackageVerificationResponse(
9320                verificationCodeAtTimeout, Binder.getCallingUid());
9321
9322        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
9323            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
9324        }
9325        if (millisecondsToDelay < 0) {
9326            millisecondsToDelay = 0;
9327        }
9328        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9329                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9330            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9331        }
9332
9333        if ((state != null) && !state.timeoutExtended()) {
9334            state.extendTimeout();
9335
9336            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9337            msg.arg1 = id;
9338            msg.obj = response;
9339            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
9340        }
9341    }
9342
9343    private void broadcastPackageVerified(int verificationId, Uri packageUri,
9344            int verificationCode, UserHandle user) {
9345        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
9346        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
9347        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9348        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9349        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
9350
9351        mContext.sendBroadcastAsUser(intent, user,
9352                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
9353    }
9354
9355    private ComponentName matchComponentForVerifier(String packageName,
9356            List<ResolveInfo> receivers) {
9357        ActivityInfo targetReceiver = null;
9358
9359        final int NR = receivers.size();
9360        for (int i = 0; i < NR; i++) {
9361            final ResolveInfo info = receivers.get(i);
9362            if (info.activityInfo == null) {
9363                continue;
9364            }
9365
9366            if (packageName.equals(info.activityInfo.packageName)) {
9367                targetReceiver = info.activityInfo;
9368                break;
9369            }
9370        }
9371
9372        if (targetReceiver == null) {
9373            return null;
9374        }
9375
9376        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
9377    }
9378
9379    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
9380            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
9381        if (pkgInfo.verifiers.length == 0) {
9382            return null;
9383        }
9384
9385        final int N = pkgInfo.verifiers.length;
9386        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
9387        for (int i = 0; i < N; i++) {
9388            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
9389
9390            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
9391                    receivers);
9392            if (comp == null) {
9393                continue;
9394            }
9395
9396            final int verifierUid = getUidForVerifier(verifierInfo);
9397            if (verifierUid == -1) {
9398                continue;
9399            }
9400
9401            if (DEBUG_VERIFY) {
9402                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
9403                        + " with the correct signature");
9404            }
9405            sufficientVerifiers.add(comp);
9406            verificationState.addSufficientVerifier(verifierUid);
9407        }
9408
9409        return sufficientVerifiers;
9410    }
9411
9412    private int getUidForVerifier(VerifierInfo verifierInfo) {
9413        synchronized (mPackages) {
9414            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
9415            if (pkg == null) {
9416                return -1;
9417            } else if (pkg.mSignatures.length != 1) {
9418                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9419                        + " has more than one signature; ignoring");
9420                return -1;
9421            }
9422
9423            /*
9424             * If the public key of the package's signature does not match
9425             * our expected public key, then this is a different package and
9426             * we should skip.
9427             */
9428
9429            final byte[] expectedPublicKey;
9430            try {
9431                final Signature verifierSig = pkg.mSignatures[0];
9432                final PublicKey publicKey = verifierSig.getPublicKey();
9433                expectedPublicKey = publicKey.getEncoded();
9434            } catch (CertificateException e) {
9435                return -1;
9436            }
9437
9438            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
9439
9440            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
9441                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9442                        + " does not have the expected public key; ignoring");
9443                return -1;
9444            }
9445
9446            return pkg.applicationInfo.uid;
9447        }
9448    }
9449
9450    @Override
9451    public void finishPackageInstall(int token) {
9452        enforceSystemOrRoot("Only the system is allowed to finish installs");
9453
9454        if (DEBUG_INSTALL) {
9455            Slog.v(TAG, "BM finishing package install for " + token);
9456        }
9457
9458        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9459        mHandler.sendMessage(msg);
9460    }
9461
9462    /**
9463     * Get the verification agent timeout.
9464     *
9465     * @return verification timeout in milliseconds
9466     */
9467    private long getVerificationTimeout() {
9468        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
9469                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
9470                DEFAULT_VERIFICATION_TIMEOUT);
9471    }
9472
9473    /**
9474     * Get the default verification agent response code.
9475     *
9476     * @return default verification response code
9477     */
9478    private int getDefaultVerificationResponse() {
9479        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9480                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
9481                DEFAULT_VERIFICATION_RESPONSE);
9482    }
9483
9484    /**
9485     * Check whether or not package verification has been enabled.
9486     *
9487     * @return true if verification should be performed
9488     */
9489    private boolean isVerificationEnabled(int userId, int installFlags) {
9490        if (!DEFAULT_VERIFY_ENABLE) {
9491            return false;
9492        }
9493
9494        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
9495
9496        // Check if installing from ADB
9497        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
9498            // Do not run verification in a test harness environment
9499            if (ActivityManager.isRunningInTestHarness()) {
9500                return false;
9501            }
9502            if (ensureVerifyAppsEnabled) {
9503                return true;
9504            }
9505            // Check if the developer does not want package verification for ADB installs
9506            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9507                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
9508                return false;
9509            }
9510        }
9511
9512        if (ensureVerifyAppsEnabled) {
9513            return true;
9514        }
9515
9516        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9517                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9518    }
9519
9520    @Override
9521    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9522            throws RemoteException {
9523        mContext.enforceCallingOrSelfPermission(
9524                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9525                "Only intentfilter verification agents can verify applications");
9526
9527        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9528        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9529                Binder.getCallingUid(), verificationCode, failedDomains);
9530        msg.arg1 = id;
9531        msg.obj = response;
9532        mHandler.sendMessage(msg);
9533    }
9534
9535    @Override
9536    public int getIntentVerificationStatus(String packageName, int userId) {
9537        synchronized (mPackages) {
9538            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
9539        }
9540    }
9541
9542    @Override
9543    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
9544        boolean result = false;
9545        synchronized (mPackages) {
9546            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
9547        }
9548        if (result) {
9549            scheduleWritePackageRestrictionsLocked(userId);
9550        }
9551        return result;
9552    }
9553
9554    @Override
9555    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
9556        synchronized (mPackages) {
9557            return mSettings.getIntentFilterVerificationsLPr(packageName);
9558        }
9559    }
9560
9561    @Override
9562    public List<IntentFilter> getAllIntentFilters(String packageName) {
9563        if (TextUtils.isEmpty(packageName)) {
9564            return Collections.<IntentFilter>emptyList();
9565        }
9566        synchronized (mPackages) {
9567            PackageParser.Package pkg = mPackages.get(packageName);
9568            if (pkg == null || pkg.activities == null) {
9569                return Collections.<IntentFilter>emptyList();
9570            }
9571            final int count = pkg.activities.size();
9572            ArrayList<IntentFilter> result = new ArrayList<>();
9573            for (int n=0; n<count; n++) {
9574                PackageParser.Activity activity = pkg.activities.get(n);
9575                if (activity.intents != null || activity.intents.size() > 0) {
9576                    result.addAll(activity.intents);
9577                }
9578            }
9579            return result;
9580        }
9581    }
9582
9583    @Override
9584    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
9585        synchronized (mPackages) {
9586            boolean result = mSettings.setDefaultBrowserPackageNameLPr(packageName, userId);
9587            if (packageName != null) {
9588                result |= updateIntentVerificationStatus(packageName,
9589                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
9590                        UserHandle.myUserId());
9591            }
9592            return result;
9593        }
9594    }
9595
9596    @Override
9597    public String getDefaultBrowserPackageName(int userId) {
9598        synchronized (mPackages) {
9599            return mSettings.getDefaultBrowserPackageNameLPw(userId);
9600        }
9601    }
9602
9603    /**
9604     * Get the "allow unknown sources" setting.
9605     *
9606     * @return the current "allow unknown sources" setting
9607     */
9608    private int getUnknownSourcesSettings() {
9609        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9610                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
9611                -1);
9612    }
9613
9614    @Override
9615    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
9616        final int uid = Binder.getCallingUid();
9617        // writer
9618        synchronized (mPackages) {
9619            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
9620            if (targetPackageSetting == null) {
9621                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
9622            }
9623
9624            PackageSetting installerPackageSetting;
9625            if (installerPackageName != null) {
9626                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
9627                if (installerPackageSetting == null) {
9628                    throw new IllegalArgumentException("Unknown installer package: "
9629                            + installerPackageName);
9630                }
9631            } else {
9632                installerPackageSetting = null;
9633            }
9634
9635            Signature[] callerSignature;
9636            Object obj = mSettings.getUserIdLPr(uid);
9637            if (obj != null) {
9638                if (obj instanceof SharedUserSetting) {
9639                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
9640                } else if (obj instanceof PackageSetting) {
9641                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
9642                } else {
9643                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
9644                }
9645            } else {
9646                throw new SecurityException("Unknown calling uid " + uid);
9647            }
9648
9649            // Verify: can't set installerPackageName to a package that is
9650            // not signed with the same cert as the caller.
9651            if (installerPackageSetting != null) {
9652                if (compareSignatures(callerSignature,
9653                        installerPackageSetting.signatures.mSignatures)
9654                        != PackageManager.SIGNATURE_MATCH) {
9655                    throw new SecurityException(
9656                            "Caller does not have same cert as new installer package "
9657                            + installerPackageName);
9658                }
9659            }
9660
9661            // Verify: if target already has an installer package, it must
9662            // be signed with the same cert as the caller.
9663            if (targetPackageSetting.installerPackageName != null) {
9664                PackageSetting setting = mSettings.mPackages.get(
9665                        targetPackageSetting.installerPackageName);
9666                // If the currently set package isn't valid, then it's always
9667                // okay to change it.
9668                if (setting != null) {
9669                    if (compareSignatures(callerSignature,
9670                            setting.signatures.mSignatures)
9671                            != PackageManager.SIGNATURE_MATCH) {
9672                        throw new SecurityException(
9673                                "Caller does not have same cert as old installer package "
9674                                + targetPackageSetting.installerPackageName);
9675                    }
9676                }
9677            }
9678
9679            // Okay!
9680            targetPackageSetting.installerPackageName = installerPackageName;
9681            scheduleWriteSettingsLocked();
9682        }
9683    }
9684
9685    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
9686        // Queue up an async operation since the package installation may take a little while.
9687        mHandler.post(new Runnable() {
9688            public void run() {
9689                mHandler.removeCallbacks(this);
9690                 // Result object to be returned
9691                PackageInstalledInfo res = new PackageInstalledInfo();
9692                res.returnCode = currentStatus;
9693                res.uid = -1;
9694                res.pkg = null;
9695                res.removedInfo = new PackageRemovedInfo();
9696                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
9697                    args.doPreInstall(res.returnCode);
9698                    synchronized (mInstallLock) {
9699                        installPackageLI(args, res);
9700                    }
9701                    args.doPostInstall(res.returnCode, res.uid);
9702                }
9703
9704                // A restore should be performed at this point if (a) the install
9705                // succeeded, (b) the operation is not an update, and (c) the new
9706                // package has not opted out of backup participation.
9707                final boolean update = res.removedInfo.removedPackage != null;
9708                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
9709                boolean doRestore = !update
9710                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
9711
9712                // Set up the post-install work request bookkeeping.  This will be used
9713                // and cleaned up by the post-install event handling regardless of whether
9714                // there's a restore pass performed.  Token values are >= 1.
9715                int token;
9716                if (mNextInstallToken < 0) mNextInstallToken = 1;
9717                token = mNextInstallToken++;
9718
9719                PostInstallData data = new PostInstallData(args, res);
9720                mRunningInstalls.put(token, data);
9721                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
9722
9723                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
9724                    // Pass responsibility to the Backup Manager.  It will perform a
9725                    // restore if appropriate, then pass responsibility back to the
9726                    // Package Manager to run the post-install observer callbacks
9727                    // and broadcasts.
9728                    IBackupManager bm = IBackupManager.Stub.asInterface(
9729                            ServiceManager.getService(Context.BACKUP_SERVICE));
9730                    if (bm != null) {
9731                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
9732                                + " to BM for possible restore");
9733                        try {
9734                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
9735                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
9736                            } else {
9737                                doRestore = false;
9738                            }
9739                        } catch (RemoteException e) {
9740                            // can't happen; the backup manager is local
9741                        } catch (Exception e) {
9742                            Slog.e(TAG, "Exception trying to enqueue restore", e);
9743                            doRestore = false;
9744                        }
9745                    } else {
9746                        Slog.e(TAG, "Backup Manager not found!");
9747                        doRestore = false;
9748                    }
9749                }
9750
9751                if (!doRestore) {
9752                    // No restore possible, or the Backup Manager was mysteriously not
9753                    // available -- just fire the post-install work request directly.
9754                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
9755                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9756                    mHandler.sendMessage(msg);
9757                }
9758            }
9759        });
9760    }
9761
9762    private abstract class HandlerParams {
9763        private static final int MAX_RETRIES = 4;
9764
9765        /**
9766         * Number of times startCopy() has been attempted and had a non-fatal
9767         * error.
9768         */
9769        private int mRetries = 0;
9770
9771        /** User handle for the user requesting the information or installation. */
9772        private final UserHandle mUser;
9773
9774        HandlerParams(UserHandle user) {
9775            mUser = user;
9776        }
9777
9778        UserHandle getUser() {
9779            return mUser;
9780        }
9781
9782        final boolean startCopy() {
9783            boolean res;
9784            try {
9785                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
9786
9787                if (++mRetries > MAX_RETRIES) {
9788                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
9789                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
9790                    handleServiceError();
9791                    return false;
9792                } else {
9793                    handleStartCopy();
9794                    res = true;
9795                }
9796            } catch (RemoteException e) {
9797                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
9798                mHandler.sendEmptyMessage(MCS_RECONNECT);
9799                res = false;
9800            }
9801            handleReturnCode();
9802            return res;
9803        }
9804
9805        final void serviceError() {
9806            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
9807            handleServiceError();
9808            handleReturnCode();
9809        }
9810
9811        abstract void handleStartCopy() throws RemoteException;
9812        abstract void handleServiceError();
9813        abstract void handleReturnCode();
9814    }
9815
9816    class MeasureParams extends HandlerParams {
9817        private final PackageStats mStats;
9818        private boolean mSuccess;
9819
9820        private final IPackageStatsObserver mObserver;
9821
9822        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
9823            super(new UserHandle(stats.userHandle));
9824            mObserver = observer;
9825            mStats = stats;
9826        }
9827
9828        @Override
9829        public String toString() {
9830            return "MeasureParams{"
9831                + Integer.toHexString(System.identityHashCode(this))
9832                + " " + mStats.packageName + "}";
9833        }
9834
9835        @Override
9836        void handleStartCopy() throws RemoteException {
9837            synchronized (mInstallLock) {
9838                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
9839            }
9840
9841            if (mSuccess) {
9842                final boolean mounted;
9843                if (Environment.isExternalStorageEmulated()) {
9844                    mounted = true;
9845                } else {
9846                    final String status = Environment.getExternalStorageState();
9847                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
9848                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
9849                }
9850
9851                if (mounted) {
9852                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
9853
9854                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
9855                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
9856
9857                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
9858                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
9859
9860                    // Always subtract cache size, since it's a subdirectory
9861                    mStats.externalDataSize -= mStats.externalCacheSize;
9862
9863                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
9864                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
9865
9866                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
9867                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
9868                }
9869            }
9870        }
9871
9872        @Override
9873        void handleReturnCode() {
9874            if (mObserver != null) {
9875                try {
9876                    mObserver.onGetStatsCompleted(mStats, mSuccess);
9877                } catch (RemoteException e) {
9878                    Slog.i(TAG, "Observer no longer exists.");
9879                }
9880            }
9881        }
9882
9883        @Override
9884        void handleServiceError() {
9885            Slog.e(TAG, "Could not measure application " + mStats.packageName
9886                            + " external storage");
9887        }
9888    }
9889
9890    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
9891            throws RemoteException {
9892        long result = 0;
9893        for (File path : paths) {
9894            result += mcs.calculateDirectorySize(path.getAbsolutePath());
9895        }
9896        return result;
9897    }
9898
9899    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
9900        for (File path : paths) {
9901            try {
9902                mcs.clearDirectory(path.getAbsolutePath());
9903            } catch (RemoteException e) {
9904            }
9905        }
9906    }
9907
9908    static class OriginInfo {
9909        /**
9910         * Location where install is coming from, before it has been
9911         * copied/renamed into place. This could be a single monolithic APK
9912         * file, or a cluster directory. This location may be untrusted.
9913         */
9914        final File file;
9915        final String cid;
9916
9917        /**
9918         * Flag indicating that {@link #file} or {@link #cid} has already been
9919         * staged, meaning downstream users don't need to defensively copy the
9920         * contents.
9921         */
9922        final boolean staged;
9923
9924        /**
9925         * Flag indicating that {@link #file} or {@link #cid} is an already
9926         * installed app that is being moved.
9927         */
9928        final boolean existing;
9929
9930        final String resolvedPath;
9931        final File resolvedFile;
9932
9933        static OriginInfo fromNothing() {
9934            return new OriginInfo(null, null, false, false);
9935        }
9936
9937        static OriginInfo fromUntrustedFile(File file) {
9938            return new OriginInfo(file, null, false, false);
9939        }
9940
9941        static OriginInfo fromExistingFile(File file) {
9942            return new OriginInfo(file, null, false, true);
9943        }
9944
9945        static OriginInfo fromStagedFile(File file) {
9946            return new OriginInfo(file, null, true, false);
9947        }
9948
9949        static OriginInfo fromStagedContainer(String cid) {
9950            return new OriginInfo(null, cid, true, false);
9951        }
9952
9953        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
9954            this.file = file;
9955            this.cid = cid;
9956            this.staged = staged;
9957            this.existing = existing;
9958
9959            if (cid != null) {
9960                resolvedPath = PackageHelper.getSdDir(cid);
9961                resolvedFile = new File(resolvedPath);
9962            } else if (file != null) {
9963                resolvedPath = file.getAbsolutePath();
9964                resolvedFile = file;
9965            } else {
9966                resolvedPath = null;
9967                resolvedFile = null;
9968            }
9969        }
9970    }
9971
9972    class MoveInfo {
9973        final int moveId;
9974        final String fromUuid;
9975        final String toUuid;
9976        final String packageName;
9977        final String dataAppName;
9978        final int appId;
9979        final String seinfo;
9980
9981        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
9982                String dataAppName, int appId, String seinfo) {
9983            this.moveId = moveId;
9984            this.fromUuid = fromUuid;
9985            this.toUuid = toUuid;
9986            this.packageName = packageName;
9987            this.dataAppName = dataAppName;
9988            this.appId = appId;
9989            this.seinfo = seinfo;
9990        }
9991    }
9992
9993    class InstallParams extends HandlerParams {
9994        final OriginInfo origin;
9995        final MoveInfo move;
9996        final IPackageInstallObserver2 observer;
9997        int installFlags;
9998        final String installerPackageName;
9999        final String volumeUuid;
10000        final VerificationParams verificationParams;
10001        private InstallArgs mArgs;
10002        private int mRet;
10003        final String packageAbiOverride;
10004
10005        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10006                int installFlags, String installerPackageName, String volumeUuid,
10007                VerificationParams verificationParams, UserHandle user, String packageAbiOverride) {
10008            super(user);
10009            this.origin = origin;
10010            this.move = move;
10011            this.observer = observer;
10012            this.installFlags = installFlags;
10013            this.installerPackageName = installerPackageName;
10014            this.volumeUuid = volumeUuid;
10015            this.verificationParams = verificationParams;
10016            this.packageAbiOverride = packageAbiOverride;
10017        }
10018
10019        @Override
10020        public String toString() {
10021            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10022                    + " file=" + origin.file + " cid=" + origin.cid + "}";
10023        }
10024
10025        public ManifestDigest getManifestDigest() {
10026            if (verificationParams == null) {
10027                return null;
10028            }
10029            return verificationParams.getManifestDigest();
10030        }
10031
10032        private int installLocationPolicy(PackageInfoLite pkgLite) {
10033            String packageName = pkgLite.packageName;
10034            int installLocation = pkgLite.installLocation;
10035            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10036            // reader
10037            synchronized (mPackages) {
10038                PackageParser.Package pkg = mPackages.get(packageName);
10039                if (pkg != null) {
10040                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10041                        // Check for downgrading.
10042                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10043                            try {
10044                                checkDowngrade(pkg, pkgLite);
10045                            } catch (PackageManagerException e) {
10046                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10047                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
10048                            }
10049                        }
10050                        // Check for updated system application.
10051                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10052                            if (onSd) {
10053                                Slog.w(TAG, "Cannot install update to system app on sdcard");
10054                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
10055                            }
10056                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10057                        } else {
10058                            if (onSd) {
10059                                // Install flag overrides everything.
10060                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10061                            }
10062                            // If current upgrade specifies particular preference
10063                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
10064                                // Application explicitly specified internal.
10065                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10066                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
10067                                // App explictly prefers external. Let policy decide
10068                            } else {
10069                                // Prefer previous location
10070                                if (isExternal(pkg)) {
10071                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10072                                }
10073                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10074                            }
10075                        }
10076                    } else {
10077                        // Invalid install. Return error code
10078                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
10079                    }
10080                }
10081            }
10082            // All the special cases have been taken care of.
10083            // Return result based on recommended install location.
10084            if (onSd) {
10085                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10086            }
10087            return pkgLite.recommendedInstallLocation;
10088        }
10089
10090        /*
10091         * Invoke remote method to get package information and install
10092         * location values. Override install location based on default
10093         * policy if needed and then create install arguments based
10094         * on the install location.
10095         */
10096        public void handleStartCopy() throws RemoteException {
10097            int ret = PackageManager.INSTALL_SUCCEEDED;
10098
10099            // If we're already staged, we've firmly committed to an install location
10100            if (origin.staged) {
10101                if (origin.file != null) {
10102                    installFlags |= PackageManager.INSTALL_INTERNAL;
10103                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10104                } else if (origin.cid != null) {
10105                    installFlags |= PackageManager.INSTALL_EXTERNAL;
10106                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
10107                } else {
10108                    throw new IllegalStateException("Invalid stage location");
10109                }
10110            }
10111
10112            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10113            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
10114
10115            PackageInfoLite pkgLite = null;
10116
10117            if (onInt && onSd) {
10118                // Check if both bits are set.
10119                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
10120                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10121            } else {
10122                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
10123                        packageAbiOverride);
10124
10125                /*
10126                 * If we have too little free space, try to free cache
10127                 * before giving up.
10128                 */
10129                if (!origin.staged && pkgLite.recommendedInstallLocation
10130                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10131                    // TODO: focus freeing disk space on the target device
10132                    final StorageManager storage = StorageManager.from(mContext);
10133                    final long lowThreshold = storage.getStorageLowBytes(
10134                            Environment.getDataDirectory());
10135
10136                    final long sizeBytes = mContainerService.calculateInstalledSize(
10137                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
10138
10139                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
10140                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
10141                                installFlags, packageAbiOverride);
10142                    }
10143
10144                    /*
10145                     * The cache free must have deleted the file we
10146                     * downloaded to install.
10147                     *
10148                     * TODO: fix the "freeCache" call to not delete
10149                     *       the file we care about.
10150                     */
10151                    if (pkgLite.recommendedInstallLocation
10152                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10153                        pkgLite.recommendedInstallLocation
10154                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
10155                    }
10156                }
10157            }
10158
10159            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10160                int loc = pkgLite.recommendedInstallLocation;
10161                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
10162                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10163                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
10164                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
10165                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10166                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10167                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
10168                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
10169                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10170                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
10171                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
10172                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
10173                } else {
10174                    // Override with defaults if needed.
10175                    loc = installLocationPolicy(pkgLite);
10176                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
10177                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
10178                    } else if (!onSd && !onInt) {
10179                        // Override install location with flags
10180                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
10181                            // Set the flag to install on external media.
10182                            installFlags |= PackageManager.INSTALL_EXTERNAL;
10183                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
10184                        } else {
10185                            // Make sure the flag for installing on external
10186                            // media is unset
10187                            installFlags |= PackageManager.INSTALL_INTERNAL;
10188                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10189                        }
10190                    }
10191                }
10192            }
10193
10194            final InstallArgs args = createInstallArgs(this);
10195            mArgs = args;
10196
10197            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10198                 /*
10199                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
10200                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
10201                 */
10202                int userIdentifier = getUser().getIdentifier();
10203                if (userIdentifier == UserHandle.USER_ALL
10204                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
10205                    userIdentifier = UserHandle.USER_OWNER;
10206                }
10207
10208                /*
10209                 * Determine if we have any installed package verifiers. If we
10210                 * do, then we'll defer to them to verify the packages.
10211                 */
10212                final int requiredUid = mRequiredVerifierPackage == null ? -1
10213                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
10214                if (!origin.existing && requiredUid != -1
10215                        && isVerificationEnabled(userIdentifier, installFlags)) {
10216                    final Intent verification = new Intent(
10217                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
10218                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10219                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
10220                            PACKAGE_MIME_TYPE);
10221                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10222
10223                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
10224                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10225                            0 /* TODO: Which userId? */);
10226
10227                    if (DEBUG_VERIFY) {
10228                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10229                                + verification.toString() + " with " + pkgLite.verifiers.length
10230                                + " optional verifiers");
10231                    }
10232
10233                    final int verificationId = mPendingVerificationToken++;
10234
10235                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10236
10237                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10238                            installerPackageName);
10239
10240                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10241                            installFlags);
10242
10243                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10244                            pkgLite.packageName);
10245
10246                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10247                            pkgLite.versionCode);
10248
10249                    if (verificationParams != null) {
10250                        if (verificationParams.getVerificationURI() != null) {
10251                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10252                                 verificationParams.getVerificationURI());
10253                        }
10254                        if (verificationParams.getOriginatingURI() != null) {
10255                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10256                                  verificationParams.getOriginatingURI());
10257                        }
10258                        if (verificationParams.getReferrer() != null) {
10259                            verification.putExtra(Intent.EXTRA_REFERRER,
10260                                  verificationParams.getReferrer());
10261                        }
10262                        if (verificationParams.getOriginatingUid() >= 0) {
10263                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
10264                                  verificationParams.getOriginatingUid());
10265                        }
10266                        if (verificationParams.getInstallerUid() >= 0) {
10267                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
10268                                  verificationParams.getInstallerUid());
10269                        }
10270                    }
10271
10272                    final PackageVerificationState verificationState = new PackageVerificationState(
10273                            requiredUid, args);
10274
10275                    mPendingVerification.append(verificationId, verificationState);
10276
10277                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
10278                            receivers, verificationState);
10279
10280                    /*
10281                     * If any sufficient verifiers were listed in the package
10282                     * manifest, attempt to ask them.
10283                     */
10284                    if (sufficientVerifiers != null) {
10285                        final int N = sufficientVerifiers.size();
10286                        if (N == 0) {
10287                            Slog.i(TAG, "Additional verifiers required, but none installed.");
10288                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
10289                        } else {
10290                            for (int i = 0; i < N; i++) {
10291                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
10292
10293                                final Intent sufficientIntent = new Intent(verification);
10294                                sufficientIntent.setComponent(verifierComponent);
10295
10296                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
10297                            }
10298                        }
10299                    }
10300
10301                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
10302                            mRequiredVerifierPackage, receivers);
10303                    if (ret == PackageManager.INSTALL_SUCCEEDED
10304                            && mRequiredVerifierPackage != null) {
10305                        /*
10306                         * Send the intent to the required verification agent,
10307                         * but only start the verification timeout after the
10308                         * target BroadcastReceivers have run.
10309                         */
10310                        verification.setComponent(requiredVerifierComponent);
10311                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
10312                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10313                                new BroadcastReceiver() {
10314                                    @Override
10315                                    public void onReceive(Context context, Intent intent) {
10316                                        final Message msg = mHandler
10317                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
10318                                        msg.arg1 = verificationId;
10319                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
10320                                    }
10321                                }, null, 0, null, null);
10322
10323                        /*
10324                         * We don't want the copy to proceed until verification
10325                         * succeeds, so null out this field.
10326                         */
10327                        mArgs = null;
10328                    }
10329                } else {
10330                    /*
10331                     * No package verification is enabled, so immediately start
10332                     * the remote call to initiate copy using temporary file.
10333                     */
10334                    ret = args.copyApk(mContainerService, true);
10335                }
10336            }
10337
10338            mRet = ret;
10339        }
10340
10341        @Override
10342        void handleReturnCode() {
10343            // If mArgs is null, then MCS couldn't be reached. When it
10344            // reconnects, it will try again to install. At that point, this
10345            // will succeed.
10346            if (mArgs != null) {
10347                processPendingInstall(mArgs, mRet);
10348            }
10349        }
10350
10351        @Override
10352        void handleServiceError() {
10353            mArgs = createInstallArgs(this);
10354            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10355        }
10356
10357        public boolean isForwardLocked() {
10358            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10359        }
10360    }
10361
10362    /**
10363     * Used during creation of InstallArgs
10364     *
10365     * @param installFlags package installation flags
10366     * @return true if should be installed on external storage
10367     */
10368    private static boolean installOnExternalAsec(int installFlags) {
10369        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
10370            return false;
10371        }
10372        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
10373            return true;
10374        }
10375        return false;
10376    }
10377
10378    /**
10379     * Used during creation of InstallArgs
10380     *
10381     * @param installFlags package installation flags
10382     * @return true if should be installed as forward locked
10383     */
10384    private static boolean installForwardLocked(int installFlags) {
10385        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10386    }
10387
10388    private InstallArgs createInstallArgs(InstallParams params) {
10389        if (params.move != null) {
10390            return new MoveInstallArgs(params);
10391        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
10392            return new AsecInstallArgs(params);
10393        } else {
10394            return new FileInstallArgs(params);
10395        }
10396    }
10397
10398    /**
10399     * Create args that describe an existing installed package. Typically used
10400     * when cleaning up old installs, or used as a move source.
10401     */
10402    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
10403            String resourcePath, String[] instructionSets) {
10404        final boolean isInAsec;
10405        if (installOnExternalAsec(installFlags)) {
10406            /* Apps on SD card are always in ASEC containers. */
10407            isInAsec = true;
10408        } else if (installForwardLocked(installFlags)
10409                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
10410            /*
10411             * Forward-locked apps are only in ASEC containers if they're the
10412             * new style
10413             */
10414            isInAsec = true;
10415        } else {
10416            isInAsec = false;
10417        }
10418
10419        if (isInAsec) {
10420            return new AsecInstallArgs(codePath, instructionSets,
10421                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
10422        } else {
10423            return new FileInstallArgs(codePath, resourcePath, instructionSets);
10424        }
10425    }
10426
10427    static abstract class InstallArgs {
10428        /** @see InstallParams#origin */
10429        final OriginInfo origin;
10430        /** @see InstallParams#move */
10431        final MoveInfo move;
10432
10433        final IPackageInstallObserver2 observer;
10434        // Always refers to PackageManager flags only
10435        final int installFlags;
10436        final String installerPackageName;
10437        final String volumeUuid;
10438        final ManifestDigest manifestDigest;
10439        final UserHandle user;
10440        final String abiOverride;
10441
10442        // The list of instruction sets supported by this app. This is currently
10443        // only used during the rmdex() phase to clean up resources. We can get rid of this
10444        // if we move dex files under the common app path.
10445        /* nullable */ String[] instructionSets;
10446
10447        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10448                int installFlags, String installerPackageName, String volumeUuid,
10449                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
10450                String abiOverride) {
10451            this.origin = origin;
10452            this.move = move;
10453            this.installFlags = installFlags;
10454            this.observer = observer;
10455            this.installerPackageName = installerPackageName;
10456            this.volumeUuid = volumeUuid;
10457            this.manifestDigest = manifestDigest;
10458            this.user = user;
10459            this.instructionSets = instructionSets;
10460            this.abiOverride = abiOverride;
10461        }
10462
10463        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
10464        abstract int doPreInstall(int status);
10465
10466        /**
10467         * Rename package into final resting place. All paths on the given
10468         * scanned package should be updated to reflect the rename.
10469         */
10470        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
10471        abstract int doPostInstall(int status, int uid);
10472
10473        /** @see PackageSettingBase#codePathString */
10474        abstract String getCodePath();
10475        /** @see PackageSettingBase#resourcePathString */
10476        abstract String getResourcePath();
10477
10478        // Need installer lock especially for dex file removal.
10479        abstract void cleanUpResourcesLI();
10480        abstract boolean doPostDeleteLI(boolean delete);
10481
10482        /**
10483         * Called before the source arguments are copied. This is used mostly
10484         * for MoveParams when it needs to read the source file to put it in the
10485         * destination.
10486         */
10487        int doPreCopy() {
10488            return PackageManager.INSTALL_SUCCEEDED;
10489        }
10490
10491        /**
10492         * Called after the source arguments are copied. This is used mostly for
10493         * MoveParams when it needs to read the source file to put it in the
10494         * destination.
10495         *
10496         * @return
10497         */
10498        int doPostCopy(int uid) {
10499            return PackageManager.INSTALL_SUCCEEDED;
10500        }
10501
10502        protected boolean isFwdLocked() {
10503            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10504        }
10505
10506        protected boolean isExternalAsec() {
10507            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10508        }
10509
10510        UserHandle getUser() {
10511            return user;
10512        }
10513    }
10514
10515    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
10516        if (!allCodePaths.isEmpty()) {
10517            if (instructionSets == null) {
10518                throw new IllegalStateException("instructionSet == null");
10519            }
10520            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
10521            for (String codePath : allCodePaths) {
10522                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
10523                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
10524                    if (retCode < 0) {
10525                        Slog.w(TAG, "Couldn't remove dex file for package: "
10526                                + " at location " + codePath + ", retcode=" + retCode);
10527                        // we don't consider this to be a failure of the core package deletion
10528                    }
10529                }
10530            }
10531        }
10532    }
10533
10534    /**
10535     * Logic to handle installation of non-ASEC applications, including copying
10536     * and renaming logic.
10537     */
10538    class FileInstallArgs extends InstallArgs {
10539        private File codeFile;
10540        private File resourceFile;
10541
10542        // Example topology:
10543        // /data/app/com.example/base.apk
10544        // /data/app/com.example/split_foo.apk
10545        // /data/app/com.example/lib/arm/libfoo.so
10546        // /data/app/com.example/lib/arm64/libfoo.so
10547        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
10548
10549        /** New install */
10550        FileInstallArgs(InstallParams params) {
10551            super(params.origin, params.move, params.observer, params.installFlags,
10552                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10553                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10554            if (isFwdLocked()) {
10555                throw new IllegalArgumentException("Forward locking only supported in ASEC");
10556            }
10557        }
10558
10559        /** Existing install */
10560        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
10561            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
10562                    null);
10563            this.codeFile = (codePath != null) ? new File(codePath) : null;
10564            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
10565        }
10566
10567        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10568            if (origin.staged) {
10569                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
10570                codeFile = origin.file;
10571                resourceFile = origin.file;
10572                return PackageManager.INSTALL_SUCCEEDED;
10573            }
10574
10575            try {
10576                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
10577                codeFile = tempDir;
10578                resourceFile = tempDir;
10579            } catch (IOException e) {
10580                Slog.w(TAG, "Failed to create copy file: " + e);
10581                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10582            }
10583
10584            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
10585                @Override
10586                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
10587                    if (!FileUtils.isValidExtFilename(name)) {
10588                        throw new IllegalArgumentException("Invalid filename: " + name);
10589                    }
10590                    try {
10591                        final File file = new File(codeFile, name);
10592                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
10593                                O_RDWR | O_CREAT, 0644);
10594                        Os.chmod(file.getAbsolutePath(), 0644);
10595                        return new ParcelFileDescriptor(fd);
10596                    } catch (ErrnoException e) {
10597                        throw new RemoteException("Failed to open: " + e.getMessage());
10598                    }
10599                }
10600            };
10601
10602            int ret = PackageManager.INSTALL_SUCCEEDED;
10603            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
10604            if (ret != PackageManager.INSTALL_SUCCEEDED) {
10605                Slog.e(TAG, "Failed to copy package");
10606                return ret;
10607            }
10608
10609            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
10610            NativeLibraryHelper.Handle handle = null;
10611            try {
10612                handle = NativeLibraryHelper.Handle.create(codeFile);
10613                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
10614                        abiOverride);
10615            } catch (IOException e) {
10616                Slog.e(TAG, "Copying native libraries failed", e);
10617                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10618            } finally {
10619                IoUtils.closeQuietly(handle);
10620            }
10621
10622            return ret;
10623        }
10624
10625        int doPreInstall(int status) {
10626            if (status != PackageManager.INSTALL_SUCCEEDED) {
10627                cleanUp();
10628            }
10629            return status;
10630        }
10631
10632        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10633            if (status != PackageManager.INSTALL_SUCCEEDED) {
10634                cleanUp();
10635                return false;
10636            }
10637
10638            final File targetDir = codeFile.getParentFile();
10639            final File beforeCodeFile = codeFile;
10640            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
10641
10642            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
10643            try {
10644                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
10645            } catch (ErrnoException e) {
10646                Slog.w(TAG, "Failed to rename", e);
10647                return false;
10648            }
10649
10650            if (!SELinux.restoreconRecursive(afterCodeFile)) {
10651                Slog.w(TAG, "Failed to restorecon");
10652                return false;
10653            }
10654
10655            // Reflect the rename internally
10656            codeFile = afterCodeFile;
10657            resourceFile = afterCodeFile;
10658
10659            // Reflect the rename in scanned details
10660            pkg.codePath = afterCodeFile.getAbsolutePath();
10661            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10662                    pkg.baseCodePath);
10663            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10664                    pkg.splitCodePaths);
10665
10666            // Reflect the rename in app info
10667            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10668            pkg.applicationInfo.setCodePath(pkg.codePath);
10669            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10670            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10671            pkg.applicationInfo.setResourcePath(pkg.codePath);
10672            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10673            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10674
10675            return true;
10676        }
10677
10678        int doPostInstall(int status, int uid) {
10679            if (status != PackageManager.INSTALL_SUCCEEDED) {
10680                cleanUp();
10681            }
10682            return status;
10683        }
10684
10685        @Override
10686        String getCodePath() {
10687            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
10688        }
10689
10690        @Override
10691        String getResourcePath() {
10692            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
10693        }
10694
10695        private boolean cleanUp() {
10696            if (codeFile == null || !codeFile.exists()) {
10697                return false;
10698            }
10699
10700            if (codeFile.isDirectory()) {
10701                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
10702            } else {
10703                codeFile.delete();
10704            }
10705
10706            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
10707                resourceFile.delete();
10708            }
10709
10710            return true;
10711        }
10712
10713        void cleanUpResourcesLI() {
10714            // Try enumerating all code paths before deleting
10715            List<String> allCodePaths = Collections.EMPTY_LIST;
10716            if (codeFile != null && codeFile.exists()) {
10717                try {
10718                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
10719                    allCodePaths = pkg.getAllCodePaths();
10720                } catch (PackageParserException e) {
10721                    // Ignored; we tried our best
10722                }
10723            }
10724
10725            cleanUp();
10726            removeDexFiles(allCodePaths, instructionSets);
10727        }
10728
10729        boolean doPostDeleteLI(boolean delete) {
10730            // XXX err, shouldn't we respect the delete flag?
10731            cleanUpResourcesLI();
10732            return true;
10733        }
10734    }
10735
10736    private boolean isAsecExternal(String cid) {
10737        final String asecPath = PackageHelper.getSdFilesystem(cid);
10738        return !asecPath.startsWith(mAsecInternalPath);
10739    }
10740
10741    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
10742            PackageManagerException {
10743        if (copyRet < 0) {
10744            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
10745                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
10746                throw new PackageManagerException(copyRet, message);
10747            }
10748        }
10749    }
10750
10751    /**
10752     * Extract the MountService "container ID" from the full code path of an
10753     * .apk.
10754     */
10755    static String cidFromCodePath(String fullCodePath) {
10756        int eidx = fullCodePath.lastIndexOf("/");
10757        String subStr1 = fullCodePath.substring(0, eidx);
10758        int sidx = subStr1.lastIndexOf("/");
10759        return subStr1.substring(sidx+1, eidx);
10760    }
10761
10762    /**
10763     * Logic to handle installation of ASEC applications, including copying and
10764     * renaming logic.
10765     */
10766    class AsecInstallArgs extends InstallArgs {
10767        static final String RES_FILE_NAME = "pkg.apk";
10768        static final String PUBLIC_RES_FILE_NAME = "res.zip";
10769
10770        String cid;
10771        String packagePath;
10772        String resourcePath;
10773
10774        /** New install */
10775        AsecInstallArgs(InstallParams params) {
10776            super(params.origin, params.move, params.observer, params.installFlags,
10777                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10778                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10779        }
10780
10781        /** Existing install */
10782        AsecInstallArgs(String fullCodePath, String[] instructionSets,
10783                        boolean isExternal, boolean isForwardLocked) {
10784            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
10785                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
10786                    instructionSets, null);
10787            // Hackily pretend we're still looking at a full code path
10788            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
10789                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
10790            }
10791
10792            // Extract cid from fullCodePath
10793            int eidx = fullCodePath.lastIndexOf("/");
10794            String subStr1 = fullCodePath.substring(0, eidx);
10795            int sidx = subStr1.lastIndexOf("/");
10796            cid = subStr1.substring(sidx+1, eidx);
10797            setMountPath(subStr1);
10798        }
10799
10800        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
10801            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
10802                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
10803                    instructionSets, null);
10804            this.cid = cid;
10805            setMountPath(PackageHelper.getSdDir(cid));
10806        }
10807
10808        void createCopyFile() {
10809            cid = mInstallerService.allocateExternalStageCidLegacy();
10810        }
10811
10812        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10813            if (origin.staged) {
10814                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
10815                cid = origin.cid;
10816                setMountPath(PackageHelper.getSdDir(cid));
10817                return PackageManager.INSTALL_SUCCEEDED;
10818            }
10819
10820            if (temp) {
10821                createCopyFile();
10822            } else {
10823                /*
10824                 * Pre-emptively destroy the container since it's destroyed if
10825                 * copying fails due to it existing anyway.
10826                 */
10827                PackageHelper.destroySdDir(cid);
10828            }
10829
10830            final String newMountPath = imcs.copyPackageToContainer(
10831                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
10832                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
10833
10834            if (newMountPath != null) {
10835                setMountPath(newMountPath);
10836                return PackageManager.INSTALL_SUCCEEDED;
10837            } else {
10838                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10839            }
10840        }
10841
10842        @Override
10843        String getCodePath() {
10844            return packagePath;
10845        }
10846
10847        @Override
10848        String getResourcePath() {
10849            return resourcePath;
10850        }
10851
10852        int doPreInstall(int status) {
10853            if (status != PackageManager.INSTALL_SUCCEEDED) {
10854                // Destroy container
10855                PackageHelper.destroySdDir(cid);
10856            } else {
10857                boolean mounted = PackageHelper.isContainerMounted(cid);
10858                if (!mounted) {
10859                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
10860                            Process.SYSTEM_UID);
10861                    if (newMountPath != null) {
10862                        setMountPath(newMountPath);
10863                    } else {
10864                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10865                    }
10866                }
10867            }
10868            return status;
10869        }
10870
10871        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10872            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
10873            String newMountPath = null;
10874            if (PackageHelper.isContainerMounted(cid)) {
10875                // Unmount the container
10876                if (!PackageHelper.unMountSdDir(cid)) {
10877                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
10878                    return false;
10879                }
10880            }
10881            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
10882                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
10883                        " which might be stale. Will try to clean up.");
10884                // Clean up the stale container and proceed to recreate.
10885                if (!PackageHelper.destroySdDir(newCacheId)) {
10886                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
10887                    return false;
10888                }
10889                // Successfully cleaned up stale container. Try to rename again.
10890                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
10891                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
10892                            + " inspite of cleaning it up.");
10893                    return false;
10894                }
10895            }
10896            if (!PackageHelper.isContainerMounted(newCacheId)) {
10897                Slog.w(TAG, "Mounting container " + newCacheId);
10898                newMountPath = PackageHelper.mountSdDir(newCacheId,
10899                        getEncryptKey(), Process.SYSTEM_UID);
10900            } else {
10901                newMountPath = PackageHelper.getSdDir(newCacheId);
10902            }
10903            if (newMountPath == null) {
10904                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
10905                return false;
10906            }
10907            Log.i(TAG, "Succesfully renamed " + cid +
10908                    " to " + newCacheId +
10909                    " at new path: " + newMountPath);
10910            cid = newCacheId;
10911
10912            final File beforeCodeFile = new File(packagePath);
10913            setMountPath(newMountPath);
10914            final File afterCodeFile = new File(packagePath);
10915
10916            // Reflect the rename in scanned details
10917            pkg.codePath = afterCodeFile.getAbsolutePath();
10918            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10919                    pkg.baseCodePath);
10920            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10921                    pkg.splitCodePaths);
10922
10923            // Reflect the rename in app info
10924            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10925            pkg.applicationInfo.setCodePath(pkg.codePath);
10926            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10927            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10928            pkg.applicationInfo.setResourcePath(pkg.codePath);
10929            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10930            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10931
10932            return true;
10933        }
10934
10935        private void setMountPath(String mountPath) {
10936            final File mountFile = new File(mountPath);
10937
10938            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
10939            if (monolithicFile.exists()) {
10940                packagePath = monolithicFile.getAbsolutePath();
10941                if (isFwdLocked()) {
10942                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
10943                } else {
10944                    resourcePath = packagePath;
10945                }
10946            } else {
10947                packagePath = mountFile.getAbsolutePath();
10948                resourcePath = packagePath;
10949            }
10950        }
10951
10952        int doPostInstall(int status, int uid) {
10953            if (status != PackageManager.INSTALL_SUCCEEDED) {
10954                cleanUp();
10955            } else {
10956                final int groupOwner;
10957                final String protectedFile;
10958                if (isFwdLocked()) {
10959                    groupOwner = UserHandle.getSharedAppGid(uid);
10960                    protectedFile = RES_FILE_NAME;
10961                } else {
10962                    groupOwner = -1;
10963                    protectedFile = null;
10964                }
10965
10966                if (uid < Process.FIRST_APPLICATION_UID
10967                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
10968                    Slog.e(TAG, "Failed to finalize " + cid);
10969                    PackageHelper.destroySdDir(cid);
10970                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10971                }
10972
10973                boolean mounted = PackageHelper.isContainerMounted(cid);
10974                if (!mounted) {
10975                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
10976                }
10977            }
10978            return status;
10979        }
10980
10981        private void cleanUp() {
10982            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
10983
10984            // Destroy secure container
10985            PackageHelper.destroySdDir(cid);
10986        }
10987
10988        private List<String> getAllCodePaths() {
10989            final File codeFile = new File(getCodePath());
10990            if (codeFile != null && codeFile.exists()) {
10991                try {
10992                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
10993                    return pkg.getAllCodePaths();
10994                } catch (PackageParserException e) {
10995                    // Ignored; we tried our best
10996                }
10997            }
10998            return Collections.EMPTY_LIST;
10999        }
11000
11001        void cleanUpResourcesLI() {
11002            // Enumerate all code paths before deleting
11003            cleanUpResourcesLI(getAllCodePaths());
11004        }
11005
11006        private void cleanUpResourcesLI(List<String> allCodePaths) {
11007            cleanUp();
11008            removeDexFiles(allCodePaths, instructionSets);
11009        }
11010
11011        String getPackageName() {
11012            return getAsecPackageName(cid);
11013        }
11014
11015        boolean doPostDeleteLI(boolean delete) {
11016            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
11017            final List<String> allCodePaths = getAllCodePaths();
11018            boolean mounted = PackageHelper.isContainerMounted(cid);
11019            if (mounted) {
11020                // Unmount first
11021                if (PackageHelper.unMountSdDir(cid)) {
11022                    mounted = false;
11023                }
11024            }
11025            if (!mounted && delete) {
11026                cleanUpResourcesLI(allCodePaths);
11027            }
11028            return !mounted;
11029        }
11030
11031        @Override
11032        int doPreCopy() {
11033            if (isFwdLocked()) {
11034                if (!PackageHelper.fixSdPermissions(cid,
11035                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
11036                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11037                }
11038            }
11039
11040            return PackageManager.INSTALL_SUCCEEDED;
11041        }
11042
11043        @Override
11044        int doPostCopy(int uid) {
11045            if (isFwdLocked()) {
11046                if (uid < Process.FIRST_APPLICATION_UID
11047                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
11048                                RES_FILE_NAME)) {
11049                    Slog.e(TAG, "Failed to finalize " + cid);
11050                    PackageHelper.destroySdDir(cid);
11051                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11052                }
11053            }
11054
11055            return PackageManager.INSTALL_SUCCEEDED;
11056        }
11057    }
11058
11059    /**
11060     * Logic to handle movement of existing installed applications.
11061     */
11062    class MoveInstallArgs extends InstallArgs {
11063        private File codeFile;
11064        private File resourceFile;
11065
11066        /** New install */
11067        MoveInstallArgs(InstallParams params) {
11068            super(params.origin, params.move, params.observer, params.installFlags,
11069                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11070                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
11071        }
11072
11073        int copyApk(IMediaContainerService imcs, boolean temp) {
11074            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
11075                    + move.fromUuid + " to " + move.toUuid);
11076            synchronized (mInstaller) {
11077                if (mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
11078                        move.dataAppName, move.appId, move.seinfo) != 0) {
11079                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11080                }
11081            }
11082
11083            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
11084            resourceFile = codeFile;
11085            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
11086
11087            return PackageManager.INSTALL_SUCCEEDED;
11088        }
11089
11090        int doPreInstall(int status) {
11091            if (status != PackageManager.INSTALL_SUCCEEDED) {
11092                cleanUp();
11093            }
11094            return status;
11095        }
11096
11097        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11098            if (status != PackageManager.INSTALL_SUCCEEDED) {
11099                cleanUp();
11100                return false;
11101            }
11102
11103            // Reflect the move in app info
11104            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11105            pkg.applicationInfo.setCodePath(pkg.codePath);
11106            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11107            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11108            pkg.applicationInfo.setResourcePath(pkg.codePath);
11109            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11110            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11111
11112            return true;
11113        }
11114
11115        int doPostInstall(int status, int uid) {
11116            if (status != PackageManager.INSTALL_SUCCEEDED) {
11117                cleanUp();
11118            }
11119            return status;
11120        }
11121
11122        @Override
11123        String getCodePath() {
11124            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11125        }
11126
11127        @Override
11128        String getResourcePath() {
11129            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11130        }
11131
11132        private boolean cleanUp() {
11133            if (codeFile == null || !codeFile.exists()) {
11134                return false;
11135            }
11136
11137            if (codeFile.isDirectory()) {
11138                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11139            } else {
11140                codeFile.delete();
11141            }
11142
11143            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11144                resourceFile.delete();
11145            }
11146
11147            return true;
11148        }
11149
11150        void cleanUpResourcesLI() {
11151            cleanUp();
11152        }
11153
11154        boolean doPostDeleteLI(boolean delete) {
11155            // XXX err, shouldn't we respect the delete flag?
11156            cleanUpResourcesLI();
11157            return true;
11158        }
11159    }
11160
11161    static String getAsecPackageName(String packageCid) {
11162        int idx = packageCid.lastIndexOf("-");
11163        if (idx == -1) {
11164            return packageCid;
11165        }
11166        return packageCid.substring(0, idx);
11167    }
11168
11169    // Utility method used to create code paths based on package name and available index.
11170    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
11171        String idxStr = "";
11172        int idx = 1;
11173        // Fall back to default value of idx=1 if prefix is not
11174        // part of oldCodePath
11175        if (oldCodePath != null) {
11176            String subStr = oldCodePath;
11177            // Drop the suffix right away
11178            if (suffix != null && subStr.endsWith(suffix)) {
11179                subStr = subStr.substring(0, subStr.length() - suffix.length());
11180            }
11181            // If oldCodePath already contains prefix find out the
11182            // ending index to either increment or decrement.
11183            int sidx = subStr.lastIndexOf(prefix);
11184            if (sidx != -1) {
11185                subStr = subStr.substring(sidx + prefix.length());
11186                if (subStr != null) {
11187                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
11188                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
11189                    }
11190                    try {
11191                        idx = Integer.parseInt(subStr);
11192                        if (idx <= 1) {
11193                            idx++;
11194                        } else {
11195                            idx--;
11196                        }
11197                    } catch(NumberFormatException e) {
11198                    }
11199                }
11200            }
11201        }
11202        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
11203        return prefix + idxStr;
11204    }
11205
11206    private File getNextCodePath(File targetDir, String packageName) {
11207        int suffix = 1;
11208        File result;
11209        do {
11210            result = new File(targetDir, packageName + "-" + suffix);
11211            suffix++;
11212        } while (result.exists());
11213        return result;
11214    }
11215
11216    // Utility method that returns the relative package path with respect
11217    // to the installation directory. Like say for /data/data/com.test-1.apk
11218    // string com.test-1 is returned.
11219    static String deriveCodePathName(String codePath) {
11220        if (codePath == null) {
11221            return null;
11222        }
11223        final File codeFile = new File(codePath);
11224        final String name = codeFile.getName();
11225        if (codeFile.isDirectory()) {
11226            return name;
11227        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
11228            final int lastDot = name.lastIndexOf('.');
11229            return name.substring(0, lastDot);
11230        } else {
11231            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11232            return null;
11233        }
11234    }
11235
11236    class PackageInstalledInfo {
11237        String name;
11238        int uid;
11239        // The set of users that originally had this package installed.
11240        int[] origUsers;
11241        // The set of users that now have this package installed.
11242        int[] newUsers;
11243        PackageParser.Package pkg;
11244        int returnCode;
11245        String returnMsg;
11246        PackageRemovedInfo removedInfo;
11247
11248        public void setError(int code, String msg) {
11249            returnCode = code;
11250            returnMsg = msg;
11251            Slog.w(TAG, msg);
11252        }
11253
11254        public void setError(String msg, PackageParserException e) {
11255            returnCode = e.error;
11256            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11257            Slog.w(TAG, msg, e);
11258        }
11259
11260        public void setError(String msg, PackageManagerException e) {
11261            returnCode = e.error;
11262            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11263            Slog.w(TAG, msg, e);
11264        }
11265
11266        // In some error cases we want to convey more info back to the observer
11267        String origPackage;
11268        String origPermission;
11269    }
11270
11271    /*
11272     * Install a non-existing package.
11273     */
11274    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11275            UserHandle user, String installerPackageName, String volumeUuid,
11276            PackageInstalledInfo res) {
11277        // Remember this for later, in case we need to rollback this install
11278        String pkgName = pkg.packageName;
11279
11280        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
11281        final boolean dataDirExists = PackageManager.getDataDirForUser(volumeUuid, pkgName,
11282                UserHandle.USER_OWNER).exists();
11283        synchronized(mPackages) {
11284            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
11285                // A package with the same name is already installed, though
11286                // it has been renamed to an older name.  The package we
11287                // are trying to install should be installed as an update to
11288                // the existing one, but that has not been requested, so bail.
11289                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11290                        + " without first uninstalling package running as "
11291                        + mSettings.mRenamedPackages.get(pkgName));
11292                return;
11293            }
11294            if (mPackages.containsKey(pkgName)) {
11295                // Don't allow installation over an existing package with the same name.
11296                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11297                        + " without first uninstalling.");
11298                return;
11299            }
11300        }
11301
11302        try {
11303            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
11304                    System.currentTimeMillis(), user);
11305
11306            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
11307            // delete the partially installed application. the data directory will have to be
11308            // restored if it was already existing
11309            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11310                // remove package from internal structures.  Note that we want deletePackageX to
11311                // delete the package data and cache directories that it created in
11312                // scanPackageLocked, unless those directories existed before we even tried to
11313                // install.
11314                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
11315                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
11316                                res.removedInfo, true);
11317            }
11318
11319        } catch (PackageManagerException e) {
11320            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11321        }
11322    }
11323
11324    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
11325        // Can't rotate keys during boot or if sharedUser.
11326        if (oldPs == null || (scanFlags&SCAN_BOOTING) != 0 || oldPs.sharedUser != null
11327                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
11328            return false;
11329        }
11330        // app is using upgradeKeySets; make sure all are valid
11331        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11332        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
11333        for (int i = 0; i < upgradeKeySets.length; i++) {
11334            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
11335                Slog.wtf(TAG, "Package "
11336                         + (oldPs.name != null ? oldPs.name : "<null>")
11337                         + " contains upgrade-key-set reference to unknown key-set: "
11338                         + upgradeKeySets[i]
11339                         + " reverting to signatures check.");
11340                return false;
11341            }
11342        }
11343        return true;
11344    }
11345
11346    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
11347        // Upgrade keysets are being used.  Determine if new package has a superset of the
11348        // required keys.
11349        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
11350        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11351        for (int i = 0; i < upgradeKeySets.length; i++) {
11352            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
11353            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
11354                return true;
11355            }
11356        }
11357        return false;
11358    }
11359
11360    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11361            UserHandle user, String installerPackageName, String volumeUuid,
11362            PackageInstalledInfo res) {
11363        final PackageParser.Package oldPackage;
11364        final String pkgName = pkg.packageName;
11365        final int[] allUsers;
11366        final boolean[] perUserInstalled;
11367        final boolean weFroze;
11368
11369        // First find the old package info and check signatures
11370        synchronized(mPackages) {
11371            oldPackage = mPackages.get(pkgName);
11372            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
11373            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11374            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11375                if(!checkUpgradeKeySetLP(ps, pkg)) {
11376                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11377                            "New package not signed by keys specified by upgrade-keysets: "
11378                            + pkgName);
11379                    return;
11380                }
11381            } else {
11382                // default to original signature matching
11383                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
11384                    != PackageManager.SIGNATURE_MATCH) {
11385                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11386                            "New package has a different signature: " + pkgName);
11387                    return;
11388                }
11389            }
11390
11391            // In case of rollback, remember per-user/profile install state
11392            allUsers = sUserManager.getUserIds();
11393            perUserInstalled = new boolean[allUsers.length];
11394            for (int i = 0; i < allUsers.length; i++) {
11395                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11396            }
11397
11398            // Mark the app as frozen to prevent launching during the upgrade
11399            // process, and then kill all running instances
11400            if (!ps.frozen) {
11401                ps.frozen = true;
11402                weFroze = true;
11403            } else {
11404                weFroze = false;
11405            }
11406        }
11407
11408        // Now that we're guarded by frozen state, kill app during upgrade
11409        killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg");
11410
11411        try {
11412            boolean sysPkg = (isSystemApp(oldPackage));
11413            if (sysPkg) {
11414                replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11415                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11416            } else {
11417                replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11418                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11419            }
11420        } finally {
11421            // Regardless of success or failure of upgrade steps above, always
11422            // unfreeze the package if we froze it
11423            if (weFroze) {
11424                unfreezePackage(pkgName);
11425            }
11426        }
11427    }
11428
11429    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
11430            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11431            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11432            String volumeUuid, PackageInstalledInfo res) {
11433        String pkgName = deletedPackage.packageName;
11434        boolean deletedPkg = true;
11435        boolean updatedSettings = false;
11436
11437        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
11438                + deletedPackage);
11439        long origUpdateTime;
11440        if (pkg.mExtras != null) {
11441            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
11442        } else {
11443            origUpdateTime = 0;
11444        }
11445
11446        // First delete the existing package while retaining the data directory
11447        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
11448                res.removedInfo, true)) {
11449            // If the existing package wasn't successfully deleted
11450            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
11451            deletedPkg = false;
11452        } else {
11453            // Successfully deleted the old package; proceed with replace.
11454
11455            // If deleted package lived in a container, give users a chance to
11456            // relinquish resources before killing.
11457            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
11458                if (DEBUG_INSTALL) {
11459                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
11460                }
11461                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
11462                final ArrayList<String> pkgList = new ArrayList<String>(1);
11463                pkgList.add(deletedPackage.applicationInfo.packageName);
11464                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
11465            }
11466
11467            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
11468            try {
11469                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
11470                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
11471                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11472                        perUserInstalled, res, user);
11473                updatedSettings = true;
11474            } catch (PackageManagerException e) {
11475                res.setError("Package couldn't be installed in " + pkg.codePath, e);
11476            }
11477        }
11478
11479        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11480            // remove package from internal structures.  Note that we want deletePackageX to
11481            // delete the package data and cache directories that it created in
11482            // scanPackageLocked, unless those directories existed before we even tried to
11483            // install.
11484            if(updatedSettings) {
11485                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
11486                deletePackageLI(
11487                        pkgName, null, true, allUsers, perUserInstalled,
11488                        PackageManager.DELETE_KEEP_DATA,
11489                                res.removedInfo, true);
11490            }
11491            // Since we failed to install the new package we need to restore the old
11492            // package that we deleted.
11493            if (deletedPkg) {
11494                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
11495                File restoreFile = new File(deletedPackage.codePath);
11496                // Parse old package
11497                boolean oldExternal = isExternal(deletedPackage);
11498                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
11499                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
11500                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11501                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
11502                try {
11503                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
11504                } catch (PackageManagerException e) {
11505                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
11506                            + e.getMessage());
11507                    return;
11508                }
11509                // Restore of old package succeeded. Update permissions.
11510                // writer
11511                synchronized (mPackages) {
11512                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
11513                            UPDATE_PERMISSIONS_ALL);
11514                    // can downgrade to reader
11515                    mSettings.writeLPr();
11516                }
11517                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
11518            }
11519        }
11520    }
11521
11522    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
11523            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11524            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11525            String volumeUuid, PackageInstalledInfo res) {
11526        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
11527                + ", old=" + deletedPackage);
11528        boolean disabledSystem = false;
11529        boolean updatedSettings = false;
11530        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
11531        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
11532                != 0) {
11533            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11534        }
11535        String packageName = deletedPackage.packageName;
11536        if (packageName == null) {
11537            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11538                    "Attempt to delete null packageName.");
11539            return;
11540        }
11541        PackageParser.Package oldPkg;
11542        PackageSetting oldPkgSetting;
11543        // reader
11544        synchronized (mPackages) {
11545            oldPkg = mPackages.get(packageName);
11546            oldPkgSetting = mSettings.mPackages.get(packageName);
11547            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
11548                    (oldPkgSetting == null)) {
11549                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11550                        "Couldn't find package:" + packageName + " information");
11551                return;
11552            }
11553        }
11554
11555        res.removedInfo.uid = oldPkg.applicationInfo.uid;
11556        res.removedInfo.removedPackage = packageName;
11557        // Remove existing system package
11558        removePackageLI(oldPkgSetting, true);
11559        // writer
11560        synchronized (mPackages) {
11561            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
11562            if (!disabledSystem && deletedPackage != null) {
11563                // We didn't need to disable the .apk as a current system package,
11564                // which means we are replacing another update that is already
11565                // installed.  We need to make sure to delete the older one's .apk.
11566                res.removedInfo.args = createInstallArgsForExisting(0,
11567                        deletedPackage.applicationInfo.getCodePath(),
11568                        deletedPackage.applicationInfo.getResourcePath(),
11569                        getAppDexInstructionSets(deletedPackage.applicationInfo));
11570            } else {
11571                res.removedInfo.args = null;
11572            }
11573        }
11574
11575        // Successfully disabled the old package. Now proceed with re-installation
11576        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
11577
11578        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11579        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
11580
11581        PackageParser.Package newPackage = null;
11582        try {
11583            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
11584            if (newPackage.mExtras != null) {
11585                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
11586                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
11587                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
11588
11589                // is the update attempting to change shared user? that isn't going to work...
11590                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
11591                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
11592                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
11593                            + " to " + newPkgSetting.sharedUser);
11594                    updatedSettings = true;
11595                }
11596            }
11597
11598            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11599                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11600                        perUserInstalled, res, user);
11601                updatedSettings = true;
11602            }
11603
11604        } catch (PackageManagerException e) {
11605            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11606        }
11607
11608        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11609            // Re installation failed. Restore old information
11610            // Remove new pkg information
11611            if (newPackage != null) {
11612                removeInstalledPackageLI(newPackage, true);
11613            }
11614            // Add back the old system package
11615            try {
11616                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
11617            } catch (PackageManagerException e) {
11618                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
11619            }
11620            // Restore the old system information in Settings
11621            synchronized (mPackages) {
11622                if (disabledSystem) {
11623                    mSettings.enableSystemPackageLPw(packageName);
11624                }
11625                if (updatedSettings) {
11626                    mSettings.setInstallerPackageName(packageName,
11627                            oldPkgSetting.installerPackageName);
11628                }
11629                mSettings.writeLPr();
11630            }
11631        }
11632    }
11633
11634    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
11635            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
11636            UserHandle user) {
11637        String pkgName = newPackage.packageName;
11638        synchronized (mPackages) {
11639            //write settings. the installStatus will be incomplete at this stage.
11640            //note that the new package setting would have already been
11641            //added to mPackages. It hasn't been persisted yet.
11642            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
11643            mSettings.writeLPr();
11644        }
11645
11646        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
11647
11648        synchronized (mPackages) {
11649            updatePermissionsLPw(newPackage.packageName, newPackage,
11650                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
11651                            ? UPDATE_PERMISSIONS_ALL : 0));
11652            // For system-bundled packages, we assume that installing an upgraded version
11653            // of the package implies that the user actually wants to run that new code,
11654            // so we enable the package.
11655            PackageSetting ps = mSettings.mPackages.get(pkgName);
11656            if (ps != null) {
11657                if (isSystemApp(newPackage)) {
11658                    // NB: implicit assumption that system package upgrades apply to all users
11659                    if (DEBUG_INSTALL) {
11660                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
11661                    }
11662                    if (res.origUsers != null) {
11663                        for (int userHandle : res.origUsers) {
11664                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
11665                                    userHandle, installerPackageName);
11666                        }
11667                    }
11668                    // Also convey the prior install/uninstall state
11669                    if (allUsers != null && perUserInstalled != null) {
11670                        for (int i = 0; i < allUsers.length; i++) {
11671                            if (DEBUG_INSTALL) {
11672                                Slog.d(TAG, "    user " + allUsers[i]
11673                                        + " => " + perUserInstalled[i]);
11674                            }
11675                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
11676                        }
11677                        // these install state changes will be persisted in the
11678                        // upcoming call to mSettings.writeLPr().
11679                    }
11680                }
11681                // It's implied that when a user requests installation, they want the app to be
11682                // installed and enabled.
11683                int userId = user.getIdentifier();
11684                if (userId != UserHandle.USER_ALL) {
11685                    ps.setInstalled(true, userId);
11686                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
11687                }
11688            }
11689            res.name = pkgName;
11690            res.uid = newPackage.applicationInfo.uid;
11691            res.pkg = newPackage;
11692            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
11693            mSettings.setInstallerPackageName(pkgName, installerPackageName);
11694            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11695            //to update install status
11696            mSettings.writeLPr();
11697        }
11698    }
11699
11700    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
11701        final int installFlags = args.installFlags;
11702        final String installerPackageName = args.installerPackageName;
11703        final String volumeUuid = args.volumeUuid;
11704        final File tmpPackageFile = new File(args.getCodePath());
11705        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
11706        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
11707                || (args.volumeUuid != null));
11708        boolean replace = false;
11709        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
11710        // Result object to be returned
11711        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11712
11713        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
11714        // Retrieve PackageSettings and parse package
11715        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
11716                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
11717                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11718        PackageParser pp = new PackageParser();
11719        pp.setSeparateProcesses(mSeparateProcesses);
11720        pp.setDisplayMetrics(mMetrics);
11721
11722        final PackageParser.Package pkg;
11723        try {
11724            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
11725        } catch (PackageParserException e) {
11726            res.setError("Failed parse during installPackageLI", e);
11727            return;
11728        }
11729
11730        // Mark that we have an install time CPU ABI override.
11731        pkg.cpuAbiOverride = args.abiOverride;
11732
11733        String pkgName = res.name = pkg.packageName;
11734        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
11735            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
11736                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
11737                return;
11738            }
11739        }
11740
11741        try {
11742            pp.collectCertificates(pkg, parseFlags);
11743            pp.collectManifestDigest(pkg);
11744        } catch (PackageParserException e) {
11745            res.setError("Failed collect during installPackageLI", e);
11746            return;
11747        }
11748
11749        /* If the installer passed in a manifest digest, compare it now. */
11750        if (args.manifestDigest != null) {
11751            if (DEBUG_INSTALL) {
11752                final String parsedManifest = pkg.manifestDigest == null ? "null"
11753                        : pkg.manifestDigest.toString();
11754                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
11755                        + parsedManifest);
11756            }
11757
11758            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
11759                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
11760                return;
11761            }
11762        } else if (DEBUG_INSTALL) {
11763            final String parsedManifest = pkg.manifestDigest == null
11764                    ? "null" : pkg.manifestDigest.toString();
11765            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
11766        }
11767
11768        // Get rid of all references to package scan path via parser.
11769        pp = null;
11770        String oldCodePath = null;
11771        boolean systemApp = false;
11772        synchronized (mPackages) {
11773            // Check if installing already existing package
11774            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
11775                String oldName = mSettings.mRenamedPackages.get(pkgName);
11776                if (pkg.mOriginalPackages != null
11777                        && pkg.mOriginalPackages.contains(oldName)
11778                        && mPackages.containsKey(oldName)) {
11779                    // This package is derived from an original package,
11780                    // and this device has been updating from that original
11781                    // name.  We must continue using the original name, so
11782                    // rename the new package here.
11783                    pkg.setPackageName(oldName);
11784                    pkgName = pkg.packageName;
11785                    replace = true;
11786                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
11787                            + oldName + " pkgName=" + pkgName);
11788                } else if (mPackages.containsKey(pkgName)) {
11789                    // This package, under its official name, already exists
11790                    // on the device; we should replace it.
11791                    replace = true;
11792                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
11793                }
11794
11795                // Prevent apps opting out from runtime permissions
11796                if (replace) {
11797                    PackageParser.Package oldPackage = mPackages.get(pkgName);
11798                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
11799                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
11800                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
11801                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
11802                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
11803                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
11804                                        + " doesn't support runtime permissions but the old"
11805                                        + " target SDK " + oldTargetSdk + " does.");
11806                        return;
11807                    }
11808                }
11809            }
11810
11811            PackageSetting ps = mSettings.mPackages.get(pkgName);
11812            if (ps != null) {
11813                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
11814
11815                // Quick sanity check that we're signed correctly if updating;
11816                // we'll check this again later when scanning, but we want to
11817                // bail early here before tripping over redefined permissions.
11818                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11819                    if (!checkUpgradeKeySetLP(ps, pkg)) {
11820                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
11821                                + pkg.packageName + " upgrade keys do not match the "
11822                                + "previously installed version");
11823                        return;
11824                    }
11825                } else {
11826                    try {
11827                        verifySignaturesLP(ps, pkg);
11828                    } catch (PackageManagerException e) {
11829                        res.setError(e.error, e.getMessage());
11830                        return;
11831                    }
11832                }
11833
11834                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
11835                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
11836                    systemApp = (ps.pkg.applicationInfo.flags &
11837                            ApplicationInfo.FLAG_SYSTEM) != 0;
11838                }
11839                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
11840            }
11841
11842            // Check whether the newly-scanned package wants to define an already-defined perm
11843            int N = pkg.permissions.size();
11844            for (int i = N-1; i >= 0; i--) {
11845                PackageParser.Permission perm = pkg.permissions.get(i);
11846                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
11847                if (bp != null) {
11848                    // If the defining package is signed with our cert, it's okay.  This
11849                    // also includes the "updating the same package" case, of course.
11850                    // "updating same package" could also involve key-rotation.
11851                    final boolean sigsOk;
11852                    if (bp.sourcePackage.equals(pkg.packageName)
11853                            && (bp.packageSetting instanceof PackageSetting)
11854                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
11855                                    scanFlags))) {
11856                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
11857                    } else {
11858                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
11859                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
11860                    }
11861                    if (!sigsOk) {
11862                        // If the owning package is the system itself, we log but allow
11863                        // install to proceed; we fail the install on all other permission
11864                        // redefinitions.
11865                        if (!bp.sourcePackage.equals("android")) {
11866                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
11867                                    + pkg.packageName + " attempting to redeclare permission "
11868                                    + perm.info.name + " already owned by " + bp.sourcePackage);
11869                            res.origPermission = perm.info.name;
11870                            res.origPackage = bp.sourcePackage;
11871                            return;
11872                        } else {
11873                            Slog.w(TAG, "Package " + pkg.packageName
11874                                    + " attempting to redeclare system permission "
11875                                    + perm.info.name + "; ignoring new declaration");
11876                            pkg.permissions.remove(i);
11877                        }
11878                    }
11879                }
11880            }
11881
11882        }
11883
11884        if (systemApp && onExternal) {
11885            // Disable updates to system apps on sdcard
11886            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
11887                    "Cannot install updates to system apps on sdcard");
11888            return;
11889        }
11890
11891        if (args.move != null) {
11892            // We did an in-place move, so dex is ready to roll
11893            scanFlags |= SCAN_NO_DEX;
11894            scanFlags |= SCAN_MOVE;
11895        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
11896            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
11897            scanFlags |= SCAN_NO_DEX;
11898
11899            try {
11900                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
11901                        true /* extract libs */);
11902            } catch (PackageManagerException pme) {
11903                Slog.e(TAG, "Error deriving application ABI", pme);
11904                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
11905                return;
11906            }
11907
11908            // Run dexopt before old package gets removed, to minimize time when app is unavailable
11909            int result = mPackageDexOptimizer
11910                    .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */,
11911                            false /* defer */, false /* inclDependencies */);
11912            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
11913                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
11914                return;
11915            }
11916        }
11917
11918        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
11919            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
11920            return;
11921        }
11922
11923        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
11924
11925        if (replace) {
11926            replacePackageLI(pkg, parseFlags, scanFlags, args.user,
11927                    installerPackageName, volumeUuid, res);
11928        } else {
11929            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
11930                    args.user, installerPackageName, volumeUuid, res);
11931        }
11932        synchronized (mPackages) {
11933            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11934            if (ps != null) {
11935                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
11936            }
11937        }
11938    }
11939
11940    private void startIntentFilterVerifications(int userId, boolean replacing,
11941            PackageParser.Package pkg) {
11942        if (mIntentFilterVerifierComponent == null) {
11943            Slog.w(TAG, "No IntentFilter verification will not be done as "
11944                    + "there is no IntentFilterVerifier available!");
11945            return;
11946        }
11947
11948        final int verifierUid = getPackageUid(
11949                mIntentFilterVerifierComponent.getPackageName(),
11950                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
11951
11952        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
11953        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
11954        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
11955        mHandler.sendMessage(msg);
11956    }
11957
11958    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
11959            PackageParser.Package pkg) {
11960        int size = pkg.activities.size();
11961        if (size == 0) {
11962            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
11963                    "No activity, so no need to verify any IntentFilter!");
11964            return;
11965        }
11966
11967        final boolean hasDomainURLs = hasDomainURLs(pkg);
11968        if (!hasDomainURLs) {
11969            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
11970                    "No domain URLs, so no need to verify any IntentFilter!");
11971            return;
11972        }
11973
11974        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
11975                + " if any IntentFilter from the " + size
11976                + " Activities needs verification ...");
11977
11978        int count = 0;
11979        final String packageName = pkg.packageName;
11980
11981        synchronized (mPackages) {
11982            // If this is a new install and we see that we've already run verification for this
11983            // package, we have nothing to do: it means the state was restored from backup.
11984            if (!replacing) {
11985                IntentFilterVerificationInfo ivi =
11986                        mSettings.getIntentFilterVerificationLPr(packageName);
11987                if (ivi != null) {
11988                    if (DEBUG_DOMAIN_VERIFICATION) {
11989                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
11990                                + ivi.getStatusString());
11991                    }
11992                    return;
11993                }
11994            }
11995
11996            // If any filters need to be verified, then all need to be.
11997            boolean needToVerify = false;
11998            for (PackageParser.Activity a : pkg.activities) {
11999                for (ActivityIntentInfo filter : a.intents) {
12000                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
12001                        if (DEBUG_DOMAIN_VERIFICATION) {
12002                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
12003                        }
12004                        needToVerify = true;
12005                        break;
12006                    }
12007                }
12008            }
12009
12010            if (needToVerify) {
12011                final int verificationId = mIntentFilterVerificationToken++;
12012                for (PackageParser.Activity a : pkg.activities) {
12013                    for (ActivityIntentInfo filter : a.intents) {
12014                        boolean needsFilterVerification = filter.hasWebDataURI();
12015                        if (needsFilterVerification && needsNetworkVerificationLPr(filter)) {
12016                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12017                                    "Verification needed for IntentFilter:" + filter.toString());
12018                            mIntentFilterVerifier.addOneIntentFilterVerification(
12019                                    verifierUid, userId, verificationId, filter, packageName);
12020                            count++;
12021                        }
12022                    }
12023                }
12024            }
12025        }
12026
12027        if (count > 0) {
12028            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
12029                    + " IntentFilter verification" + (count > 1 ? "s" : "")
12030                    +  " for userId:" + userId);
12031            mIntentFilterVerifier.startVerifications(userId);
12032        } else {
12033            if (DEBUG_DOMAIN_VERIFICATION) {
12034                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
12035            }
12036        }
12037    }
12038
12039    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
12040        final ComponentName cn  = filter.activity.getComponentName();
12041        final String packageName = cn.getPackageName();
12042
12043        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
12044                packageName);
12045        if (ivi == null) {
12046            return true;
12047        }
12048        int status = ivi.getStatus();
12049        switch (status) {
12050            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
12051            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
12052                return true;
12053
12054            default:
12055                // Nothing to do
12056                return false;
12057        }
12058    }
12059
12060    private static boolean isMultiArch(PackageSetting ps) {
12061        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12062    }
12063
12064    private static boolean isMultiArch(ApplicationInfo info) {
12065        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12066    }
12067
12068    private static boolean isExternal(PackageParser.Package pkg) {
12069        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12070    }
12071
12072    private static boolean isExternal(PackageSetting ps) {
12073        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12074    }
12075
12076    private static boolean isExternal(ApplicationInfo info) {
12077        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12078    }
12079
12080    private static boolean isSystemApp(PackageParser.Package pkg) {
12081        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
12082    }
12083
12084    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
12085        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
12086    }
12087
12088    private static boolean hasDomainURLs(PackageParser.Package pkg) {
12089        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
12090    }
12091
12092    private static boolean isSystemApp(PackageSetting ps) {
12093        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
12094    }
12095
12096    private static boolean isUpdatedSystemApp(PackageSetting ps) {
12097        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
12098    }
12099
12100    private int packageFlagsToInstallFlags(PackageSetting ps) {
12101        int installFlags = 0;
12102        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
12103            // This existing package was an external ASEC install when we have
12104            // the external flag without a UUID
12105            installFlags |= PackageManager.INSTALL_EXTERNAL;
12106        }
12107        if (ps.isForwardLocked()) {
12108            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12109        }
12110        return installFlags;
12111    }
12112
12113    private void deleteTempPackageFiles() {
12114        final FilenameFilter filter = new FilenameFilter() {
12115            public boolean accept(File dir, String name) {
12116                return name.startsWith("vmdl") && name.endsWith(".tmp");
12117            }
12118        };
12119        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
12120            file.delete();
12121        }
12122    }
12123
12124    @Override
12125    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
12126            int flags) {
12127        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
12128                flags);
12129    }
12130
12131    @Override
12132    public void deletePackage(final String packageName,
12133            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
12134        mContext.enforceCallingOrSelfPermission(
12135                android.Manifest.permission.DELETE_PACKAGES, null);
12136        final int uid = Binder.getCallingUid();
12137        if (UserHandle.getUserId(uid) != userId) {
12138            mContext.enforceCallingPermission(
12139                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
12140                    "deletePackage for user " + userId);
12141        }
12142        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
12143            try {
12144                observer.onPackageDeleted(packageName,
12145                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
12146            } catch (RemoteException re) {
12147            }
12148            return;
12149        }
12150
12151        boolean uninstallBlocked = false;
12152        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
12153            int[] users = sUserManager.getUserIds();
12154            for (int i = 0; i < users.length; ++i) {
12155                if (getBlockUninstallForUser(packageName, users[i])) {
12156                    uninstallBlocked = true;
12157                    break;
12158                }
12159            }
12160        } else {
12161            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
12162        }
12163        if (uninstallBlocked) {
12164            try {
12165                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
12166                        null);
12167            } catch (RemoteException re) {
12168            }
12169            return;
12170        }
12171
12172        if (DEBUG_REMOVE) {
12173            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
12174        }
12175        // Queue up an async operation since the package deletion may take a little while.
12176        mHandler.post(new Runnable() {
12177            public void run() {
12178                mHandler.removeCallbacks(this);
12179                final int returnCode = deletePackageX(packageName, userId, flags);
12180                if (observer != null) {
12181                    try {
12182                        observer.onPackageDeleted(packageName, returnCode, null);
12183                    } catch (RemoteException e) {
12184                        Log.i(TAG, "Observer no longer exists.");
12185                    } //end catch
12186                } //end if
12187            } //end run
12188        });
12189    }
12190
12191    private boolean isPackageDeviceAdmin(String packageName, int userId) {
12192        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12193                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12194        try {
12195            if (dpm != null) {
12196                if (dpm.isDeviceOwner(packageName)) {
12197                    return true;
12198                }
12199                int[] users;
12200                if (userId == UserHandle.USER_ALL) {
12201                    users = sUserManager.getUserIds();
12202                } else {
12203                    users = new int[]{userId};
12204                }
12205                for (int i = 0; i < users.length; ++i) {
12206                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
12207                        return true;
12208                    }
12209                }
12210            }
12211        } catch (RemoteException e) {
12212        }
12213        return false;
12214    }
12215
12216    /**
12217     *  This method is an internal method that could be get invoked either
12218     *  to delete an installed package or to clean up a failed installation.
12219     *  After deleting an installed package, a broadcast is sent to notify any
12220     *  listeners that the package has been installed. For cleaning up a failed
12221     *  installation, the broadcast is not necessary since the package's
12222     *  installation wouldn't have sent the initial broadcast either
12223     *  The key steps in deleting a package are
12224     *  deleting the package information in internal structures like mPackages,
12225     *  deleting the packages base directories through installd
12226     *  updating mSettings to reflect current status
12227     *  persisting settings for later use
12228     *  sending a broadcast if necessary
12229     */
12230    private int deletePackageX(String packageName, int userId, int flags) {
12231        final PackageRemovedInfo info = new PackageRemovedInfo();
12232        final boolean res;
12233
12234        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
12235                ? UserHandle.ALL : new UserHandle(userId);
12236
12237        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
12238            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
12239            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
12240        }
12241
12242        boolean removedForAllUsers = false;
12243        boolean systemUpdate = false;
12244
12245        // for the uninstall-updates case and restricted profiles, remember the per-
12246        // userhandle installed state
12247        int[] allUsers;
12248        boolean[] perUserInstalled;
12249        synchronized (mPackages) {
12250            PackageSetting ps = mSettings.mPackages.get(packageName);
12251            allUsers = sUserManager.getUserIds();
12252            perUserInstalled = new boolean[allUsers.length];
12253            for (int i = 0; i < allUsers.length; i++) {
12254                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12255            }
12256        }
12257
12258        synchronized (mInstallLock) {
12259            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
12260            res = deletePackageLI(packageName, removeForUser,
12261                    true, allUsers, perUserInstalled,
12262                    flags | REMOVE_CHATTY, info, true);
12263            systemUpdate = info.isRemovedPackageSystemUpdate;
12264            if (res && !systemUpdate && mPackages.get(packageName) == null) {
12265                removedForAllUsers = true;
12266            }
12267            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
12268                    + " removedForAllUsers=" + removedForAllUsers);
12269        }
12270
12271        if (res) {
12272            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
12273
12274            // If the removed package was a system update, the old system package
12275            // was re-enabled; we need to broadcast this information
12276            if (systemUpdate) {
12277                Bundle extras = new Bundle(1);
12278                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
12279                        ? info.removedAppId : info.uid);
12280                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12281
12282                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
12283                        extras, null, null, null);
12284                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
12285                        extras, null, null, null);
12286                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
12287                        null, packageName, null, null);
12288            }
12289        }
12290        // Force a gc here.
12291        Runtime.getRuntime().gc();
12292        // Delete the resources here after sending the broadcast to let
12293        // other processes clean up before deleting resources.
12294        if (info.args != null) {
12295            synchronized (mInstallLock) {
12296                info.args.doPostDeleteLI(true);
12297            }
12298        }
12299
12300        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
12301    }
12302
12303    class PackageRemovedInfo {
12304        String removedPackage;
12305        int uid = -1;
12306        int removedAppId = -1;
12307        int[] removedUsers = null;
12308        boolean isRemovedPackageSystemUpdate = false;
12309        // Clean up resources deleted packages.
12310        InstallArgs args = null;
12311
12312        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
12313            Bundle extras = new Bundle(1);
12314            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
12315            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
12316            if (replacing) {
12317                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12318            }
12319            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
12320            if (removedPackage != null) {
12321                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
12322                        extras, null, null, removedUsers);
12323                if (fullRemove && !replacing) {
12324                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
12325                            extras, null, null, removedUsers);
12326                }
12327            }
12328            if (removedAppId >= 0) {
12329                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
12330                        removedUsers);
12331            }
12332        }
12333    }
12334
12335    /*
12336     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
12337     * flag is not set, the data directory is removed as well.
12338     * make sure this flag is set for partially installed apps. If not its meaningless to
12339     * delete a partially installed application.
12340     */
12341    private void removePackageDataLI(PackageSetting ps,
12342            int[] allUserHandles, boolean[] perUserInstalled,
12343            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
12344        String packageName = ps.name;
12345        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
12346        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
12347        // Retrieve object to delete permissions for shared user later on
12348        final PackageSetting deletedPs;
12349        // reader
12350        synchronized (mPackages) {
12351            deletedPs = mSettings.mPackages.get(packageName);
12352            if (outInfo != null) {
12353                outInfo.removedPackage = packageName;
12354                outInfo.removedUsers = deletedPs != null
12355                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
12356                        : null;
12357            }
12358        }
12359        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12360            removeDataDirsLI(ps.volumeUuid, packageName);
12361            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
12362        }
12363        // writer
12364        synchronized (mPackages) {
12365            if (deletedPs != null) {
12366                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12367                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
12368                    clearDefaultBrowserIfNeeded(packageName);
12369                    if (outInfo != null) {
12370                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
12371                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
12372                    }
12373                    updatePermissionsLPw(deletedPs.name, null, 0);
12374                    if (deletedPs.sharedUser != null) {
12375                        // Remove permissions associated with package. Since runtime
12376                        // permissions are per user we have to kill the removed package
12377                        // or packages running under the shared user of the removed
12378                        // package if revoking the permissions requested only by the removed
12379                        // package is successful and this causes a change in gids.
12380                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12381                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
12382                                    userId);
12383                            if (userIdToKill == UserHandle.USER_ALL
12384                                    || userIdToKill >= UserHandle.USER_OWNER) {
12385                                // If gids changed for this user, kill all affected packages.
12386                                mHandler.post(new Runnable() {
12387                                    @Override
12388                                    public void run() {
12389                                        // This has to happen with no lock held.
12390                                        killSettingPackagesForUser(deletedPs, userIdToKill,
12391                                                KILL_APP_REASON_GIDS_CHANGED);
12392                                    }
12393                                });
12394                            break;
12395                            }
12396                        }
12397                    }
12398                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
12399                }
12400                // make sure to preserve per-user disabled state if this removal was just
12401                // a downgrade of a system app to the factory package
12402                if (allUserHandles != null && perUserInstalled != null) {
12403                    if (DEBUG_REMOVE) {
12404                        Slog.d(TAG, "Propagating install state across downgrade");
12405                    }
12406                    for (int i = 0; i < allUserHandles.length; i++) {
12407                        if (DEBUG_REMOVE) {
12408                            Slog.d(TAG, "    user " + allUserHandles[i]
12409                                    + " => " + perUserInstalled[i]);
12410                        }
12411                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12412                    }
12413                }
12414            }
12415            // can downgrade to reader
12416            if (writeSettings) {
12417                // Save settings now
12418                mSettings.writeLPr();
12419            }
12420        }
12421        if (outInfo != null) {
12422            // A user ID was deleted here. Go through all users and remove it
12423            // from KeyStore.
12424            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
12425        }
12426    }
12427
12428    static boolean locationIsPrivileged(File path) {
12429        try {
12430            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
12431                    .getCanonicalPath();
12432            return path.getCanonicalPath().startsWith(privilegedAppDir);
12433        } catch (IOException e) {
12434            Slog.e(TAG, "Unable to access code path " + path);
12435        }
12436        return false;
12437    }
12438
12439    /*
12440     * Tries to delete system package.
12441     */
12442    private boolean deleteSystemPackageLI(PackageSetting newPs,
12443            int[] allUserHandles, boolean[] perUserInstalled,
12444            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
12445        final boolean applyUserRestrictions
12446                = (allUserHandles != null) && (perUserInstalled != null);
12447        PackageSetting disabledPs = null;
12448        // Confirm if the system package has been updated
12449        // An updated system app can be deleted. This will also have to restore
12450        // the system pkg from system partition
12451        // reader
12452        synchronized (mPackages) {
12453            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
12454        }
12455        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
12456                + " disabledPs=" + disabledPs);
12457        if (disabledPs == null) {
12458            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
12459            return false;
12460        } else if (DEBUG_REMOVE) {
12461            Slog.d(TAG, "Deleting system pkg from data partition");
12462        }
12463        if (DEBUG_REMOVE) {
12464            if (applyUserRestrictions) {
12465                Slog.d(TAG, "Remembering install states:");
12466                for (int i = 0; i < allUserHandles.length; i++) {
12467                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
12468                }
12469            }
12470        }
12471        // Delete the updated package
12472        outInfo.isRemovedPackageSystemUpdate = true;
12473        if (disabledPs.versionCode < newPs.versionCode) {
12474            // Delete data for downgrades
12475            flags &= ~PackageManager.DELETE_KEEP_DATA;
12476        } else {
12477            // Preserve data by setting flag
12478            flags |= PackageManager.DELETE_KEEP_DATA;
12479        }
12480        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
12481                allUserHandles, perUserInstalled, outInfo, writeSettings);
12482        if (!ret) {
12483            return false;
12484        }
12485        // writer
12486        synchronized (mPackages) {
12487            // Reinstate the old system package
12488            mSettings.enableSystemPackageLPw(newPs.name);
12489            // Remove any native libraries from the upgraded package.
12490            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
12491        }
12492        // Install the system package
12493        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
12494        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
12495        if (locationIsPrivileged(disabledPs.codePath)) {
12496            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12497        }
12498
12499        final PackageParser.Package newPkg;
12500        try {
12501            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
12502        } catch (PackageManagerException e) {
12503            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
12504            return false;
12505        }
12506
12507        // writer
12508        synchronized (mPackages) {
12509            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
12510            updatePermissionsLPw(newPkg.packageName, newPkg,
12511                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
12512            if (applyUserRestrictions) {
12513                if (DEBUG_REMOVE) {
12514                    Slog.d(TAG, "Propagating install state across reinstall");
12515                }
12516                for (int i = 0; i < allUserHandles.length; i++) {
12517                    if (DEBUG_REMOVE) {
12518                        Slog.d(TAG, "    user " + allUserHandles[i]
12519                                + " => " + perUserInstalled[i]);
12520                    }
12521                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12522                }
12523                // Regardless of writeSettings we need to ensure that this restriction
12524                // state propagation is persisted
12525                mSettings.writeAllUsersPackageRestrictionsLPr();
12526            }
12527            // can downgrade to reader here
12528            if (writeSettings) {
12529                mSettings.writeLPr();
12530            }
12531        }
12532        return true;
12533    }
12534
12535    private boolean deleteInstalledPackageLI(PackageSetting ps,
12536            boolean deleteCodeAndResources, int flags,
12537            int[] allUserHandles, boolean[] perUserInstalled,
12538            PackageRemovedInfo outInfo, boolean writeSettings) {
12539        if (outInfo != null) {
12540            outInfo.uid = ps.appId;
12541        }
12542
12543        // Delete package data from internal structures and also remove data if flag is set
12544        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
12545
12546        // Delete application code and resources
12547        if (deleteCodeAndResources && (outInfo != null)) {
12548            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
12549                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
12550            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
12551        }
12552        return true;
12553    }
12554
12555    @Override
12556    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
12557            int userId) {
12558        mContext.enforceCallingOrSelfPermission(
12559                android.Manifest.permission.DELETE_PACKAGES, null);
12560        synchronized (mPackages) {
12561            PackageSetting ps = mSettings.mPackages.get(packageName);
12562            if (ps == null) {
12563                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
12564                return false;
12565            }
12566            if (!ps.getInstalled(userId)) {
12567                // Can't block uninstall for an app that is not installed or enabled.
12568                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
12569                return false;
12570            }
12571            ps.setBlockUninstall(blockUninstall, userId);
12572            mSettings.writePackageRestrictionsLPr(userId);
12573        }
12574        return true;
12575    }
12576
12577    @Override
12578    public boolean getBlockUninstallForUser(String packageName, int userId) {
12579        synchronized (mPackages) {
12580            PackageSetting ps = mSettings.mPackages.get(packageName);
12581            if (ps == null) {
12582                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
12583                return false;
12584            }
12585            return ps.getBlockUninstall(userId);
12586        }
12587    }
12588
12589    /*
12590     * This method handles package deletion in general
12591     */
12592    private boolean deletePackageLI(String packageName, UserHandle user,
12593            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
12594            int flags, PackageRemovedInfo outInfo,
12595            boolean writeSettings) {
12596        if (packageName == null) {
12597            Slog.w(TAG, "Attempt to delete null packageName.");
12598            return false;
12599        }
12600        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
12601        PackageSetting ps;
12602        boolean dataOnly = false;
12603        int removeUser = -1;
12604        int appId = -1;
12605        synchronized (mPackages) {
12606            ps = mSettings.mPackages.get(packageName);
12607            if (ps == null) {
12608                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12609                return false;
12610            }
12611            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
12612                    && user.getIdentifier() != UserHandle.USER_ALL) {
12613                // The caller is asking that the package only be deleted for a single
12614                // user.  To do this, we just mark its uninstalled state and delete
12615                // its data.  If this is a system app, we only allow this to happen if
12616                // they have set the special DELETE_SYSTEM_APP which requests different
12617                // semantics than normal for uninstalling system apps.
12618                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
12619                ps.setUserState(user.getIdentifier(),
12620                        COMPONENT_ENABLED_STATE_DEFAULT,
12621                        false, //installed
12622                        true,  //stopped
12623                        true,  //notLaunched
12624                        false, //hidden
12625                        null, null, null,
12626                        false, // blockUninstall
12627                        INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
12628                if (!isSystemApp(ps)) {
12629                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
12630                        // Other user still have this package installed, so all
12631                        // we need to do is clear this user's data and save that
12632                        // it is uninstalled.
12633                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
12634                        removeUser = user.getIdentifier();
12635                        appId = ps.appId;
12636                        scheduleWritePackageRestrictionsLocked(removeUser);
12637                    } else {
12638                        // We need to set it back to 'installed' so the uninstall
12639                        // broadcasts will be sent correctly.
12640                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
12641                        ps.setInstalled(true, user.getIdentifier());
12642                    }
12643                } else {
12644                    // This is a system app, so we assume that the
12645                    // other users still have this package installed, so all
12646                    // we need to do is clear this user's data and save that
12647                    // it is uninstalled.
12648                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
12649                    removeUser = user.getIdentifier();
12650                    appId = ps.appId;
12651                    scheduleWritePackageRestrictionsLocked(removeUser);
12652                }
12653            }
12654        }
12655
12656        if (removeUser >= 0) {
12657            // From above, we determined that we are deleting this only
12658            // for a single user.  Continue the work here.
12659            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
12660            if (outInfo != null) {
12661                outInfo.removedPackage = packageName;
12662                outInfo.removedAppId = appId;
12663                outInfo.removedUsers = new int[] {removeUser};
12664            }
12665            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
12666            removeKeystoreDataIfNeeded(removeUser, appId);
12667            schedulePackageCleaning(packageName, removeUser, false);
12668            synchronized (mPackages) {
12669                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
12670                    scheduleWritePackageRestrictionsLocked(removeUser);
12671                }
12672                revokeRuntimePermissionsAndClearAllFlagsLocked(ps.getPermissionsState(),
12673                        removeUser);
12674            }
12675            return true;
12676        }
12677
12678        if (dataOnly) {
12679            // Delete application data first
12680            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
12681            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
12682            return true;
12683        }
12684
12685        boolean ret = false;
12686        if (isSystemApp(ps)) {
12687            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
12688            // When an updated system application is deleted we delete the existing resources as well and
12689            // fall back to existing code in system partition
12690            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
12691                    flags, outInfo, writeSettings);
12692        } else {
12693            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
12694            // Kill application pre-emptively especially for apps on sd.
12695            killApplication(packageName, ps.appId, "uninstall pkg");
12696            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
12697                    allUserHandles, perUserInstalled,
12698                    outInfo, writeSettings);
12699        }
12700
12701        return ret;
12702    }
12703
12704    private final class ClearStorageConnection implements ServiceConnection {
12705        IMediaContainerService mContainerService;
12706
12707        @Override
12708        public void onServiceConnected(ComponentName name, IBinder service) {
12709            synchronized (this) {
12710                mContainerService = IMediaContainerService.Stub.asInterface(service);
12711                notifyAll();
12712            }
12713        }
12714
12715        @Override
12716        public void onServiceDisconnected(ComponentName name) {
12717        }
12718    }
12719
12720    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
12721        final boolean mounted;
12722        if (Environment.isExternalStorageEmulated()) {
12723            mounted = true;
12724        } else {
12725            final String status = Environment.getExternalStorageState();
12726
12727            mounted = status.equals(Environment.MEDIA_MOUNTED)
12728                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
12729        }
12730
12731        if (!mounted) {
12732            return;
12733        }
12734
12735        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
12736        int[] users;
12737        if (userId == UserHandle.USER_ALL) {
12738            users = sUserManager.getUserIds();
12739        } else {
12740            users = new int[] { userId };
12741        }
12742        final ClearStorageConnection conn = new ClearStorageConnection();
12743        if (mContext.bindServiceAsUser(
12744                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
12745            try {
12746                for (int curUser : users) {
12747                    long timeout = SystemClock.uptimeMillis() + 5000;
12748                    synchronized (conn) {
12749                        long now = SystemClock.uptimeMillis();
12750                        while (conn.mContainerService == null && now < timeout) {
12751                            try {
12752                                conn.wait(timeout - now);
12753                            } catch (InterruptedException e) {
12754                            }
12755                        }
12756                    }
12757                    if (conn.mContainerService == null) {
12758                        return;
12759                    }
12760
12761                    final UserEnvironment userEnv = new UserEnvironment(curUser);
12762                    clearDirectory(conn.mContainerService,
12763                            userEnv.buildExternalStorageAppCacheDirs(packageName));
12764                    if (allData) {
12765                        clearDirectory(conn.mContainerService,
12766                                userEnv.buildExternalStorageAppDataDirs(packageName));
12767                        clearDirectory(conn.mContainerService,
12768                                userEnv.buildExternalStorageAppMediaDirs(packageName));
12769                    }
12770                }
12771            } finally {
12772                mContext.unbindService(conn);
12773            }
12774        }
12775    }
12776
12777    @Override
12778    public void clearApplicationUserData(final String packageName,
12779            final IPackageDataObserver observer, final int userId) {
12780        mContext.enforceCallingOrSelfPermission(
12781                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
12782        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
12783        // Queue up an async operation since the package deletion may take a little while.
12784        mHandler.post(new Runnable() {
12785            public void run() {
12786                mHandler.removeCallbacks(this);
12787                final boolean succeeded;
12788                synchronized (mInstallLock) {
12789                    succeeded = clearApplicationUserDataLI(packageName, userId);
12790                }
12791                clearExternalStorageDataSync(packageName, userId, true);
12792                if (succeeded) {
12793                    // invoke DeviceStorageMonitor's update method to clear any notifications
12794                    DeviceStorageMonitorInternal
12795                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
12796                    if (dsm != null) {
12797                        dsm.checkMemory();
12798                    }
12799                }
12800                if(observer != null) {
12801                    try {
12802                        observer.onRemoveCompleted(packageName, succeeded);
12803                    } catch (RemoteException e) {
12804                        Log.i(TAG, "Observer no longer exists.");
12805                    }
12806                } //end if observer
12807            } //end run
12808        });
12809    }
12810
12811    private boolean clearApplicationUserDataLI(String packageName, int userId) {
12812        if (packageName == null) {
12813            Slog.w(TAG, "Attempt to delete null packageName.");
12814            return false;
12815        }
12816
12817        // Try finding details about the requested package
12818        PackageParser.Package pkg;
12819        synchronized (mPackages) {
12820            pkg = mPackages.get(packageName);
12821            if (pkg == null) {
12822                final PackageSetting ps = mSettings.mPackages.get(packageName);
12823                if (ps != null) {
12824                    pkg = ps.pkg;
12825                }
12826            }
12827
12828            if (pkg == null) {
12829                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12830                return false;
12831            }
12832
12833            PackageSetting ps = (PackageSetting) pkg.mExtras;
12834            PermissionsState permissionsState = ps.getPermissionsState();
12835            revokeRuntimePermissionsAndClearUserSetFlagsLocked(permissionsState, userId);
12836        }
12837
12838        // Always delete data directories for package, even if we found no other
12839        // record of app. This helps users recover from UID mismatches without
12840        // resorting to a full data wipe.
12841        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
12842        if (retCode < 0) {
12843            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
12844            return false;
12845        }
12846
12847        final int appId = pkg.applicationInfo.uid;
12848        removeKeystoreDataIfNeeded(userId, appId);
12849
12850        // Create a native library symlink only if we have native libraries
12851        // and if the native libraries are 32 bit libraries. We do not provide
12852        // this symlink for 64 bit libraries.
12853        if (pkg.applicationInfo.primaryCpuAbi != null &&
12854                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
12855            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
12856            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
12857                    nativeLibPath, userId) < 0) {
12858                Slog.w(TAG, "Failed linking native library dir");
12859                return false;
12860            }
12861        }
12862
12863        return true;
12864    }
12865
12866
12867    /**
12868     * Revokes granted runtime permissions and clears resettable flags
12869     * which are flags that can be set by a user interaction.
12870     *
12871     * @param permissionsState The permission state to reset.
12872     * @param userId The device user for which to do a reset.
12873     */
12874    private void revokeRuntimePermissionsAndClearUserSetFlagsLocked(
12875            PermissionsState permissionsState, int userId) {
12876        final int userSetFlags = PackageManager.FLAG_PERMISSION_USER_SET
12877                | PackageManager.FLAG_PERMISSION_USER_FIXED
12878                | PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
12879
12880        revokeRuntimePermissionsAndClearFlagsLocked(permissionsState, userId, userSetFlags);
12881    }
12882
12883    /**
12884     * Revokes granted runtime permissions and clears all flags.
12885     *
12886     * @param permissionsState The permission state to reset.
12887     * @param userId The device user for which to do a reset.
12888     */
12889    private void revokeRuntimePermissionsAndClearAllFlagsLocked(
12890            PermissionsState permissionsState, int userId) {
12891        revokeRuntimePermissionsAndClearFlagsLocked(permissionsState, userId,
12892                PackageManager.MASK_PERMISSION_FLAGS);
12893    }
12894
12895    /**
12896     * Revokes granted runtime permissions and clears certain flags.
12897     *
12898     * @param permissionsState The permission state to reset.
12899     * @param userId The device user for which to do a reset.
12900     * @param flags The flags that is going to be reset.
12901     */
12902    private void revokeRuntimePermissionsAndClearFlagsLocked(
12903            PermissionsState permissionsState, int userId, int flags) {
12904        boolean needsWrite = false;
12905
12906        for (PermissionState state : permissionsState.getRuntimePermissionStates(userId)) {
12907            BasePermission bp = mSettings.mPermissions.get(state.getName());
12908            if (bp != null) {
12909                permissionsState.revokeRuntimePermission(bp, userId);
12910                permissionsState.updatePermissionFlags(bp, userId, flags, 0);
12911                needsWrite = true;
12912            }
12913        }
12914
12915        // Ensure default permissions are never cleared.
12916        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
12917
12918        if (needsWrite) {
12919            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
12920        }
12921    }
12922
12923    /**
12924     * Remove entries from the keystore daemon. Will only remove it if the
12925     * {@code appId} is valid.
12926     */
12927    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
12928        if (appId < 0) {
12929            return;
12930        }
12931
12932        final KeyStore keyStore = KeyStore.getInstance();
12933        if (keyStore != null) {
12934            if (userId == UserHandle.USER_ALL) {
12935                for (final int individual : sUserManager.getUserIds()) {
12936                    keyStore.clearUid(UserHandle.getUid(individual, appId));
12937                }
12938            } else {
12939                keyStore.clearUid(UserHandle.getUid(userId, appId));
12940            }
12941        } else {
12942            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
12943        }
12944    }
12945
12946    @Override
12947    public void deleteApplicationCacheFiles(final String packageName,
12948            final IPackageDataObserver observer) {
12949        mContext.enforceCallingOrSelfPermission(
12950                android.Manifest.permission.DELETE_CACHE_FILES, null);
12951        // Queue up an async operation since the package deletion may take a little while.
12952        final int userId = UserHandle.getCallingUserId();
12953        mHandler.post(new Runnable() {
12954            public void run() {
12955                mHandler.removeCallbacks(this);
12956                final boolean succeded;
12957                synchronized (mInstallLock) {
12958                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
12959                }
12960                clearExternalStorageDataSync(packageName, userId, false);
12961                if (observer != null) {
12962                    try {
12963                        observer.onRemoveCompleted(packageName, succeded);
12964                    } catch (RemoteException e) {
12965                        Log.i(TAG, "Observer no longer exists.");
12966                    }
12967                } //end if observer
12968            } //end run
12969        });
12970    }
12971
12972    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
12973        if (packageName == null) {
12974            Slog.w(TAG, "Attempt to delete null packageName.");
12975            return false;
12976        }
12977        PackageParser.Package p;
12978        synchronized (mPackages) {
12979            p = mPackages.get(packageName);
12980        }
12981        if (p == null) {
12982            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
12983            return false;
12984        }
12985        final ApplicationInfo applicationInfo = p.applicationInfo;
12986        if (applicationInfo == null) {
12987            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
12988            return false;
12989        }
12990        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
12991        if (retCode < 0) {
12992            Slog.w(TAG, "Couldn't remove cache files for package: "
12993                       + packageName + " u" + userId);
12994            return false;
12995        }
12996        return true;
12997    }
12998
12999    @Override
13000    public void getPackageSizeInfo(final String packageName, int userHandle,
13001            final IPackageStatsObserver observer) {
13002        mContext.enforceCallingOrSelfPermission(
13003                android.Manifest.permission.GET_PACKAGE_SIZE, null);
13004        if (packageName == null) {
13005            throw new IllegalArgumentException("Attempt to get size of null packageName");
13006        }
13007
13008        PackageStats stats = new PackageStats(packageName, userHandle);
13009
13010        /*
13011         * Queue up an async operation since the package measurement may take a
13012         * little while.
13013         */
13014        Message msg = mHandler.obtainMessage(INIT_COPY);
13015        msg.obj = new MeasureParams(stats, observer);
13016        mHandler.sendMessage(msg);
13017    }
13018
13019    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
13020            PackageStats pStats) {
13021        if (packageName == null) {
13022            Slog.w(TAG, "Attempt to get size of null packageName.");
13023            return false;
13024        }
13025        PackageParser.Package p;
13026        boolean dataOnly = false;
13027        String libDirRoot = null;
13028        String asecPath = null;
13029        PackageSetting ps = null;
13030        synchronized (mPackages) {
13031            p = mPackages.get(packageName);
13032            ps = mSettings.mPackages.get(packageName);
13033            if(p == null) {
13034                dataOnly = true;
13035                if((ps == null) || (ps.pkg == null)) {
13036                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13037                    return false;
13038                }
13039                p = ps.pkg;
13040            }
13041            if (ps != null) {
13042                libDirRoot = ps.legacyNativeLibraryPathString;
13043            }
13044            if (p != null && (isExternal(p) || p.isForwardLocked())) {
13045                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
13046                if (secureContainerId != null) {
13047                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
13048                }
13049            }
13050        }
13051        String publicSrcDir = null;
13052        if(!dataOnly) {
13053            final ApplicationInfo applicationInfo = p.applicationInfo;
13054            if (applicationInfo == null) {
13055                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13056                return false;
13057            }
13058            if (p.isForwardLocked()) {
13059                publicSrcDir = applicationInfo.getBaseResourcePath();
13060            }
13061        }
13062        // TODO: extend to measure size of split APKs
13063        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
13064        // not just the first level.
13065        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
13066        // just the primary.
13067        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
13068        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath,
13069                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
13070        if (res < 0) {
13071            return false;
13072        }
13073
13074        // Fix-up for forward-locked applications in ASEC containers.
13075        if (!isExternal(p)) {
13076            pStats.codeSize += pStats.externalCodeSize;
13077            pStats.externalCodeSize = 0L;
13078        }
13079
13080        return true;
13081    }
13082
13083
13084    @Override
13085    public void addPackageToPreferred(String packageName) {
13086        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
13087    }
13088
13089    @Override
13090    public void removePackageFromPreferred(String packageName) {
13091        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
13092    }
13093
13094    @Override
13095    public List<PackageInfo> getPreferredPackages(int flags) {
13096        return new ArrayList<PackageInfo>();
13097    }
13098
13099    private int getUidTargetSdkVersionLockedLPr(int uid) {
13100        Object obj = mSettings.getUserIdLPr(uid);
13101        if (obj instanceof SharedUserSetting) {
13102            final SharedUserSetting sus = (SharedUserSetting) obj;
13103            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
13104            final Iterator<PackageSetting> it = sus.packages.iterator();
13105            while (it.hasNext()) {
13106                final PackageSetting ps = it.next();
13107                if (ps.pkg != null) {
13108                    int v = ps.pkg.applicationInfo.targetSdkVersion;
13109                    if (v < vers) vers = v;
13110                }
13111            }
13112            return vers;
13113        } else if (obj instanceof PackageSetting) {
13114            final PackageSetting ps = (PackageSetting) obj;
13115            if (ps.pkg != null) {
13116                return ps.pkg.applicationInfo.targetSdkVersion;
13117            }
13118        }
13119        return Build.VERSION_CODES.CUR_DEVELOPMENT;
13120    }
13121
13122    @Override
13123    public void addPreferredActivity(IntentFilter filter, int match,
13124            ComponentName[] set, ComponentName activity, int userId) {
13125        addPreferredActivityInternal(filter, match, set, activity, true, userId,
13126                "Adding preferred");
13127    }
13128
13129    private void addPreferredActivityInternal(IntentFilter filter, int match,
13130            ComponentName[] set, ComponentName activity, boolean always, int userId,
13131            String opname) {
13132        // writer
13133        int callingUid = Binder.getCallingUid();
13134        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
13135        if (filter.countActions() == 0) {
13136            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13137            return;
13138        }
13139        synchronized (mPackages) {
13140            if (mContext.checkCallingOrSelfPermission(
13141                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13142                    != PackageManager.PERMISSION_GRANTED) {
13143                if (getUidTargetSdkVersionLockedLPr(callingUid)
13144                        < Build.VERSION_CODES.FROYO) {
13145                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
13146                            + callingUid);
13147                    return;
13148                }
13149                mContext.enforceCallingOrSelfPermission(
13150                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13151            }
13152
13153            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
13154            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
13155                    + userId + ":");
13156            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13157            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
13158            scheduleWritePackageRestrictionsLocked(userId);
13159        }
13160    }
13161
13162    @Override
13163    public void replacePreferredActivity(IntentFilter filter, int match,
13164            ComponentName[] set, ComponentName activity, int userId) {
13165        if (filter.countActions() != 1) {
13166            throw new IllegalArgumentException(
13167                    "replacePreferredActivity expects filter to have only 1 action.");
13168        }
13169        if (filter.countDataAuthorities() != 0
13170                || filter.countDataPaths() != 0
13171                || filter.countDataSchemes() > 1
13172                || filter.countDataTypes() != 0) {
13173            throw new IllegalArgumentException(
13174                    "replacePreferredActivity expects filter to have no data authorities, " +
13175                    "paths, or types; and at most one scheme.");
13176        }
13177
13178        final int callingUid = Binder.getCallingUid();
13179        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
13180        synchronized (mPackages) {
13181            if (mContext.checkCallingOrSelfPermission(
13182                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13183                    != PackageManager.PERMISSION_GRANTED) {
13184                if (getUidTargetSdkVersionLockedLPr(callingUid)
13185                        < Build.VERSION_CODES.FROYO) {
13186                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
13187                            + Binder.getCallingUid());
13188                    return;
13189                }
13190                mContext.enforceCallingOrSelfPermission(
13191                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13192            }
13193
13194            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13195            if (pir != null) {
13196                // Get all of the existing entries that exactly match this filter.
13197                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
13198                if (existing != null && existing.size() == 1) {
13199                    PreferredActivity cur = existing.get(0);
13200                    if (DEBUG_PREFERRED) {
13201                        Slog.i(TAG, "Checking replace of preferred:");
13202                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13203                        if (!cur.mPref.mAlways) {
13204                            Slog.i(TAG, "  -- CUR; not mAlways!");
13205                        } else {
13206                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
13207                            Slog.i(TAG, "  -- CUR: mSet="
13208                                    + Arrays.toString(cur.mPref.mSetComponents));
13209                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
13210                            Slog.i(TAG, "  -- NEW: mMatch="
13211                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
13212                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
13213                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
13214                        }
13215                    }
13216                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
13217                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
13218                            && cur.mPref.sameSet(set)) {
13219                        // Setting the preferred activity to what it happens to be already
13220                        if (DEBUG_PREFERRED) {
13221                            Slog.i(TAG, "Replacing with same preferred activity "
13222                                    + cur.mPref.mShortComponent + " for user "
13223                                    + userId + ":");
13224                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13225                        }
13226                        return;
13227                    }
13228                }
13229
13230                if (existing != null) {
13231                    if (DEBUG_PREFERRED) {
13232                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
13233                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13234                    }
13235                    for (int i = 0; i < existing.size(); i++) {
13236                        PreferredActivity pa = existing.get(i);
13237                        if (DEBUG_PREFERRED) {
13238                            Slog.i(TAG, "Removing existing preferred activity "
13239                                    + pa.mPref.mComponent + ":");
13240                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
13241                        }
13242                        pir.removeFilter(pa);
13243                    }
13244                }
13245            }
13246            addPreferredActivityInternal(filter, match, set, activity, true, userId,
13247                    "Replacing preferred");
13248        }
13249    }
13250
13251    @Override
13252    public void clearPackagePreferredActivities(String packageName) {
13253        final int uid = Binder.getCallingUid();
13254        // writer
13255        synchronized (mPackages) {
13256            PackageParser.Package pkg = mPackages.get(packageName);
13257            if (pkg == null || pkg.applicationInfo.uid != uid) {
13258                if (mContext.checkCallingOrSelfPermission(
13259                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13260                        != PackageManager.PERMISSION_GRANTED) {
13261                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
13262                            < Build.VERSION_CODES.FROYO) {
13263                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
13264                                + Binder.getCallingUid());
13265                        return;
13266                    }
13267                    mContext.enforceCallingOrSelfPermission(
13268                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13269                }
13270            }
13271
13272            int user = UserHandle.getCallingUserId();
13273            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
13274                scheduleWritePackageRestrictionsLocked(user);
13275            }
13276        }
13277    }
13278
13279    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13280    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
13281        ArrayList<PreferredActivity> removed = null;
13282        boolean changed = false;
13283        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13284            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
13285            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13286            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
13287                continue;
13288            }
13289            Iterator<PreferredActivity> it = pir.filterIterator();
13290            while (it.hasNext()) {
13291                PreferredActivity pa = it.next();
13292                // Mark entry for removal only if it matches the package name
13293                // and the entry is of type "always".
13294                if (packageName == null ||
13295                        (pa.mPref.mComponent.getPackageName().equals(packageName)
13296                                && pa.mPref.mAlways)) {
13297                    if (removed == null) {
13298                        removed = new ArrayList<PreferredActivity>();
13299                    }
13300                    removed.add(pa);
13301                }
13302            }
13303            if (removed != null) {
13304                for (int j=0; j<removed.size(); j++) {
13305                    PreferredActivity pa = removed.get(j);
13306                    pir.removeFilter(pa);
13307                }
13308                changed = true;
13309            }
13310        }
13311        return changed;
13312    }
13313
13314    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13315    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
13316        if (userId == UserHandle.USER_ALL) {
13317            if (mSettings.removeIntentFilterVerificationLPw(packageName,
13318                    sUserManager.getUserIds())) {
13319                for (int oneUserId : sUserManager.getUserIds()) {
13320                    scheduleWritePackageRestrictionsLocked(oneUserId);
13321                }
13322            }
13323        } else {
13324            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
13325                scheduleWritePackageRestrictionsLocked(userId);
13326            }
13327        }
13328    }
13329
13330
13331    void clearDefaultBrowserIfNeeded(String packageName) {
13332        for (int oneUserId : sUserManager.getUserIds()) {
13333            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
13334            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
13335            if (packageName.equals(defaultBrowserPackageName)) {
13336                setDefaultBrowserPackageName(null, oneUserId);
13337            }
13338        }
13339    }
13340
13341    @Override
13342    public void resetPreferredActivities(int userId) {
13343        /* TODO: Actually use userId. Why is it being passed in? */
13344        mContext.enforceCallingOrSelfPermission(
13345                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13346        // writer
13347        synchronized (mPackages) {
13348            int user = UserHandle.getCallingUserId();
13349            clearPackagePreferredActivitiesLPw(null, user);
13350            mSettings.readDefaultPreferredAppsLPw(this, user);
13351            scheduleWritePackageRestrictionsLocked(user);
13352        }
13353    }
13354
13355    @Override
13356    public int getPreferredActivities(List<IntentFilter> outFilters,
13357            List<ComponentName> outActivities, String packageName) {
13358
13359        int num = 0;
13360        final int userId = UserHandle.getCallingUserId();
13361        // reader
13362        synchronized (mPackages) {
13363            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13364            if (pir != null) {
13365                final Iterator<PreferredActivity> it = pir.filterIterator();
13366                while (it.hasNext()) {
13367                    final PreferredActivity pa = it.next();
13368                    if (packageName == null
13369                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
13370                                    && pa.mPref.mAlways)) {
13371                        if (outFilters != null) {
13372                            outFilters.add(new IntentFilter(pa));
13373                        }
13374                        if (outActivities != null) {
13375                            outActivities.add(pa.mPref.mComponent);
13376                        }
13377                    }
13378                }
13379            }
13380        }
13381
13382        return num;
13383    }
13384
13385    @Override
13386    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
13387            int userId) {
13388        int callingUid = Binder.getCallingUid();
13389        if (callingUid != Process.SYSTEM_UID) {
13390            throw new SecurityException(
13391                    "addPersistentPreferredActivity can only be run by the system");
13392        }
13393        if (filter.countActions() == 0) {
13394            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13395            return;
13396        }
13397        synchronized (mPackages) {
13398            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
13399                    " :");
13400            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13401            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
13402                    new PersistentPreferredActivity(filter, activity));
13403            scheduleWritePackageRestrictionsLocked(userId);
13404        }
13405    }
13406
13407    @Override
13408    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
13409        int callingUid = Binder.getCallingUid();
13410        if (callingUid != Process.SYSTEM_UID) {
13411            throw new SecurityException(
13412                    "clearPackagePersistentPreferredActivities can only be run by the system");
13413        }
13414        ArrayList<PersistentPreferredActivity> removed = null;
13415        boolean changed = false;
13416        synchronized (mPackages) {
13417            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
13418                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
13419                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
13420                        .valueAt(i);
13421                if (userId != thisUserId) {
13422                    continue;
13423                }
13424                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
13425                while (it.hasNext()) {
13426                    PersistentPreferredActivity ppa = it.next();
13427                    // Mark entry for removal only if it matches the package name.
13428                    if (ppa.mComponent.getPackageName().equals(packageName)) {
13429                        if (removed == null) {
13430                            removed = new ArrayList<PersistentPreferredActivity>();
13431                        }
13432                        removed.add(ppa);
13433                    }
13434                }
13435                if (removed != null) {
13436                    for (int j=0; j<removed.size(); j++) {
13437                        PersistentPreferredActivity ppa = removed.get(j);
13438                        ppir.removeFilter(ppa);
13439                    }
13440                    changed = true;
13441                }
13442            }
13443
13444            if (changed) {
13445                scheduleWritePackageRestrictionsLocked(userId);
13446            }
13447        }
13448    }
13449
13450    /**
13451     * Common machinery for picking apart a restored XML blob and passing
13452     * it to a caller-supplied functor to be applied to the running system.
13453     */
13454    private void restoreFromXml(XmlPullParser parser, int userId,
13455            String expectedStartTag, BlobXmlRestorer functor)
13456            throws IOException, XmlPullParserException {
13457        int type;
13458        while ((type = parser.next()) != XmlPullParser.START_TAG
13459                && type != XmlPullParser.END_DOCUMENT) {
13460        }
13461        if (type != XmlPullParser.START_TAG) {
13462            // oops didn't find a start tag?!
13463            if (DEBUG_BACKUP) {
13464                Slog.e(TAG, "Didn't find start tag during restore");
13465            }
13466            return;
13467        }
13468
13469        // this is supposed to be TAG_PREFERRED_BACKUP
13470        if (!expectedStartTag.equals(parser.getName())) {
13471            if (DEBUG_BACKUP) {
13472                Slog.e(TAG, "Found unexpected tag " + parser.getName());
13473            }
13474            return;
13475        }
13476
13477        // skip interfering stuff, then we're aligned with the backing implementation
13478        while ((type = parser.next()) == XmlPullParser.TEXT) { }
13479        functor.apply(parser, userId);
13480    }
13481
13482    private interface BlobXmlRestorer {
13483        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
13484    }
13485
13486    /**
13487     * Non-Binder method, support for the backup/restore mechanism: write the
13488     * full set of preferred activities in its canonical XML format.  Returns the
13489     * XML output as a byte array, or null if there is none.
13490     */
13491    @Override
13492    public byte[] getPreferredActivityBackup(int userId) {
13493        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13494            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
13495        }
13496
13497        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13498        try {
13499            final XmlSerializer serializer = new FastXmlSerializer();
13500            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13501            serializer.startDocument(null, true);
13502            serializer.startTag(null, TAG_PREFERRED_BACKUP);
13503
13504            synchronized (mPackages) {
13505                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
13506            }
13507
13508            serializer.endTag(null, TAG_PREFERRED_BACKUP);
13509            serializer.endDocument();
13510            serializer.flush();
13511        } catch (Exception e) {
13512            if (DEBUG_BACKUP) {
13513                Slog.e(TAG, "Unable to write preferred activities for backup", e);
13514            }
13515            return null;
13516        }
13517
13518        return dataStream.toByteArray();
13519    }
13520
13521    @Override
13522    public void restorePreferredActivities(byte[] backup, int userId) {
13523        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13524            throw new SecurityException("Only the system may call restorePreferredActivities()");
13525        }
13526
13527        try {
13528            final XmlPullParser parser = Xml.newPullParser();
13529            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13530            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
13531                    new BlobXmlRestorer() {
13532                        @Override
13533                        public void apply(XmlPullParser parser, int userId)
13534                                throws XmlPullParserException, IOException {
13535                            synchronized (mPackages) {
13536                                mSettings.readPreferredActivitiesLPw(parser, userId);
13537                            }
13538                        }
13539                    } );
13540        } catch (Exception e) {
13541            if (DEBUG_BACKUP) {
13542                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
13543            }
13544        }
13545    }
13546
13547    /**
13548     * Non-Binder method, support for the backup/restore mechanism: write the
13549     * default browser (etc) settings in its canonical XML format.  Returns the default
13550     * browser XML representation as a byte array, or null if there is none.
13551     */
13552    @Override
13553    public byte[] getDefaultAppsBackup(int userId) {
13554        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13555            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
13556        }
13557
13558        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13559        try {
13560            final XmlSerializer serializer = new FastXmlSerializer();
13561            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13562            serializer.startDocument(null, true);
13563            serializer.startTag(null, TAG_DEFAULT_APPS);
13564
13565            synchronized (mPackages) {
13566                mSettings.writeDefaultAppsLPr(serializer, userId);
13567            }
13568
13569            serializer.endTag(null, TAG_DEFAULT_APPS);
13570            serializer.endDocument();
13571            serializer.flush();
13572        } catch (Exception e) {
13573            if (DEBUG_BACKUP) {
13574                Slog.e(TAG, "Unable to write default apps for backup", e);
13575            }
13576            return null;
13577        }
13578
13579        return dataStream.toByteArray();
13580    }
13581
13582    @Override
13583    public void restoreDefaultApps(byte[] backup, int userId) {
13584        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13585            throw new SecurityException("Only the system may call restoreDefaultApps()");
13586        }
13587
13588        try {
13589            final XmlPullParser parser = Xml.newPullParser();
13590            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13591            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
13592                    new BlobXmlRestorer() {
13593                        @Override
13594                        public void apply(XmlPullParser parser, int userId)
13595                                throws XmlPullParserException, IOException {
13596                            synchronized (mPackages) {
13597                                mSettings.readDefaultAppsLPw(parser, userId);
13598                            }
13599                        }
13600                    } );
13601        } catch (Exception e) {
13602            if (DEBUG_BACKUP) {
13603                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
13604            }
13605        }
13606    }
13607
13608    @Override
13609    public byte[] getIntentFilterVerificationBackup(int userId) {
13610        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13611            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
13612        }
13613
13614        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13615        try {
13616            final XmlSerializer serializer = new FastXmlSerializer();
13617            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13618            serializer.startDocument(null, true);
13619            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
13620
13621            synchronized (mPackages) {
13622                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
13623            }
13624
13625            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
13626            serializer.endDocument();
13627            serializer.flush();
13628        } catch (Exception e) {
13629            if (DEBUG_BACKUP) {
13630                Slog.e(TAG, "Unable to write default apps for backup", e);
13631            }
13632            return null;
13633        }
13634
13635        return dataStream.toByteArray();
13636    }
13637
13638    @Override
13639    public void restoreIntentFilterVerification(byte[] backup, int userId) {
13640        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13641            throw new SecurityException("Only the system may call restorePreferredActivities()");
13642        }
13643
13644        try {
13645            final XmlPullParser parser = Xml.newPullParser();
13646            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13647            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
13648                    new BlobXmlRestorer() {
13649                        @Override
13650                        public void apply(XmlPullParser parser, int userId)
13651                                throws XmlPullParserException, IOException {
13652                            synchronized (mPackages) {
13653                                mSettings.readAllDomainVerificationsLPr(parser, userId);
13654                                mSettings.writeLPr();
13655                            }
13656                        }
13657                    } );
13658        } catch (Exception e) {
13659            if (DEBUG_BACKUP) {
13660                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
13661            }
13662        }
13663    }
13664
13665    @Override
13666    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
13667            int sourceUserId, int targetUserId, int flags) {
13668        mContext.enforceCallingOrSelfPermission(
13669                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
13670        int callingUid = Binder.getCallingUid();
13671        enforceOwnerRights(ownerPackage, callingUid);
13672        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
13673        if (intentFilter.countActions() == 0) {
13674            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
13675            return;
13676        }
13677        synchronized (mPackages) {
13678            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
13679                    ownerPackage, targetUserId, flags);
13680            CrossProfileIntentResolver resolver =
13681                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
13682            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
13683            // We have all those whose filter is equal. Now checking if the rest is equal as well.
13684            if (existing != null) {
13685                int size = existing.size();
13686                for (int i = 0; i < size; i++) {
13687                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
13688                        return;
13689                    }
13690                }
13691            }
13692            resolver.addFilter(newFilter);
13693            scheduleWritePackageRestrictionsLocked(sourceUserId);
13694        }
13695    }
13696
13697    @Override
13698    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
13699        mContext.enforceCallingOrSelfPermission(
13700                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
13701        int callingUid = Binder.getCallingUid();
13702        enforceOwnerRights(ownerPackage, callingUid);
13703        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
13704        synchronized (mPackages) {
13705            CrossProfileIntentResolver resolver =
13706                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
13707            ArraySet<CrossProfileIntentFilter> set =
13708                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
13709            for (CrossProfileIntentFilter filter : set) {
13710                if (filter.getOwnerPackage().equals(ownerPackage)) {
13711                    resolver.removeFilter(filter);
13712                }
13713            }
13714            scheduleWritePackageRestrictionsLocked(sourceUserId);
13715        }
13716    }
13717
13718    // Enforcing that callingUid is owning pkg on userId
13719    private void enforceOwnerRights(String pkg, int callingUid) {
13720        // The system owns everything.
13721        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
13722            return;
13723        }
13724        int callingUserId = UserHandle.getUserId(callingUid);
13725        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
13726        if (pi == null) {
13727            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
13728                    + callingUserId);
13729        }
13730        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
13731            throw new SecurityException("Calling uid " + callingUid
13732                    + " does not own package " + pkg);
13733        }
13734    }
13735
13736    @Override
13737    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
13738        Intent intent = new Intent(Intent.ACTION_MAIN);
13739        intent.addCategory(Intent.CATEGORY_HOME);
13740
13741        final int callingUserId = UserHandle.getCallingUserId();
13742        List<ResolveInfo> list = queryIntentActivities(intent, null,
13743                PackageManager.GET_META_DATA, callingUserId);
13744        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
13745                true, false, false, callingUserId);
13746
13747        allHomeCandidates.clear();
13748        if (list != null) {
13749            for (ResolveInfo ri : list) {
13750                allHomeCandidates.add(ri);
13751            }
13752        }
13753        return (preferred == null || preferred.activityInfo == null)
13754                ? null
13755                : new ComponentName(preferred.activityInfo.packageName,
13756                        preferred.activityInfo.name);
13757    }
13758
13759    @Override
13760    public void setApplicationEnabledSetting(String appPackageName,
13761            int newState, int flags, int userId, String callingPackage) {
13762        if (!sUserManager.exists(userId)) return;
13763        if (callingPackage == null) {
13764            callingPackage = Integer.toString(Binder.getCallingUid());
13765        }
13766        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
13767    }
13768
13769    @Override
13770    public void setComponentEnabledSetting(ComponentName componentName,
13771            int newState, int flags, int userId) {
13772        if (!sUserManager.exists(userId)) return;
13773        setEnabledSetting(componentName.getPackageName(),
13774                componentName.getClassName(), newState, flags, userId, null);
13775    }
13776
13777    private void setEnabledSetting(final String packageName, String className, int newState,
13778            final int flags, int userId, String callingPackage) {
13779        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
13780              || newState == COMPONENT_ENABLED_STATE_ENABLED
13781              || newState == COMPONENT_ENABLED_STATE_DISABLED
13782              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
13783              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
13784            throw new IllegalArgumentException("Invalid new component state: "
13785                    + newState);
13786        }
13787        PackageSetting pkgSetting;
13788        final int uid = Binder.getCallingUid();
13789        final int permission = mContext.checkCallingOrSelfPermission(
13790                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
13791        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
13792        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
13793        boolean sendNow = false;
13794        boolean isApp = (className == null);
13795        String componentName = isApp ? packageName : className;
13796        int packageUid = -1;
13797        ArrayList<String> components;
13798
13799        // writer
13800        synchronized (mPackages) {
13801            pkgSetting = mSettings.mPackages.get(packageName);
13802            if (pkgSetting == null) {
13803                if (className == null) {
13804                    throw new IllegalArgumentException(
13805                            "Unknown package: " + packageName);
13806                }
13807                throw new IllegalArgumentException(
13808                        "Unknown component: " + packageName
13809                        + "/" + className);
13810            }
13811            // Allow root and verify that userId is not being specified by a different user
13812            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
13813                throw new SecurityException(
13814                        "Permission Denial: attempt to change component state from pid="
13815                        + Binder.getCallingPid()
13816                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
13817            }
13818            if (className == null) {
13819                // We're dealing with an application/package level state change
13820                if (pkgSetting.getEnabled(userId) == newState) {
13821                    // Nothing to do
13822                    return;
13823                }
13824                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
13825                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
13826                    // Don't care about who enables an app.
13827                    callingPackage = null;
13828                }
13829                pkgSetting.setEnabled(newState, userId, callingPackage);
13830                // pkgSetting.pkg.mSetEnabled = newState;
13831            } else {
13832                // We're dealing with a component level state change
13833                // First, verify that this is a valid class name.
13834                PackageParser.Package pkg = pkgSetting.pkg;
13835                if (pkg == null || !pkg.hasComponentClassName(className)) {
13836                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
13837                        throw new IllegalArgumentException("Component class " + className
13838                                + " does not exist in " + packageName);
13839                    } else {
13840                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
13841                                + className + " does not exist in " + packageName);
13842                    }
13843                }
13844                switch (newState) {
13845                case COMPONENT_ENABLED_STATE_ENABLED:
13846                    if (!pkgSetting.enableComponentLPw(className, userId)) {
13847                        return;
13848                    }
13849                    break;
13850                case COMPONENT_ENABLED_STATE_DISABLED:
13851                    if (!pkgSetting.disableComponentLPw(className, userId)) {
13852                        return;
13853                    }
13854                    break;
13855                case COMPONENT_ENABLED_STATE_DEFAULT:
13856                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
13857                        return;
13858                    }
13859                    break;
13860                default:
13861                    Slog.e(TAG, "Invalid new component state: " + newState);
13862                    return;
13863                }
13864            }
13865            scheduleWritePackageRestrictionsLocked(userId);
13866            components = mPendingBroadcasts.get(userId, packageName);
13867            final boolean newPackage = components == null;
13868            if (newPackage) {
13869                components = new ArrayList<String>();
13870            }
13871            if (!components.contains(componentName)) {
13872                components.add(componentName);
13873            }
13874            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
13875                sendNow = true;
13876                // Purge entry from pending broadcast list if another one exists already
13877                // since we are sending one right away.
13878                mPendingBroadcasts.remove(userId, packageName);
13879            } else {
13880                if (newPackage) {
13881                    mPendingBroadcasts.put(userId, packageName, components);
13882                }
13883                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
13884                    // Schedule a message
13885                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
13886                }
13887            }
13888        }
13889
13890        long callingId = Binder.clearCallingIdentity();
13891        try {
13892            if (sendNow) {
13893                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
13894                sendPackageChangedBroadcast(packageName,
13895                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
13896            }
13897        } finally {
13898            Binder.restoreCallingIdentity(callingId);
13899        }
13900    }
13901
13902    private void sendPackageChangedBroadcast(String packageName,
13903            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
13904        if (DEBUG_INSTALL)
13905            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
13906                    + componentNames);
13907        Bundle extras = new Bundle(4);
13908        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
13909        String nameList[] = new String[componentNames.size()];
13910        componentNames.toArray(nameList);
13911        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
13912        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
13913        extras.putInt(Intent.EXTRA_UID, packageUid);
13914        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
13915                new int[] {UserHandle.getUserId(packageUid)});
13916    }
13917
13918    @Override
13919    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
13920        if (!sUserManager.exists(userId)) return;
13921        final int uid = Binder.getCallingUid();
13922        final int permission = mContext.checkCallingOrSelfPermission(
13923                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
13924        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
13925        enforceCrossUserPermission(uid, userId, true, true, "stop package");
13926        // writer
13927        synchronized (mPackages) {
13928            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
13929                    allowedByPermission, uid, userId)) {
13930                scheduleWritePackageRestrictionsLocked(userId);
13931            }
13932        }
13933    }
13934
13935    @Override
13936    public String getInstallerPackageName(String packageName) {
13937        // reader
13938        synchronized (mPackages) {
13939            return mSettings.getInstallerPackageNameLPr(packageName);
13940        }
13941    }
13942
13943    @Override
13944    public int getApplicationEnabledSetting(String packageName, int userId) {
13945        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
13946        int uid = Binder.getCallingUid();
13947        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
13948        // reader
13949        synchronized (mPackages) {
13950            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
13951        }
13952    }
13953
13954    @Override
13955    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
13956        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
13957        int uid = Binder.getCallingUid();
13958        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
13959        // reader
13960        synchronized (mPackages) {
13961            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
13962        }
13963    }
13964
13965    @Override
13966    public void enterSafeMode() {
13967        enforceSystemOrRoot("Only the system can request entering safe mode");
13968
13969        if (!mSystemReady) {
13970            mSafeMode = true;
13971        }
13972    }
13973
13974    @Override
13975    public void systemReady() {
13976        mSystemReady = true;
13977
13978        // Read the compatibilty setting when the system is ready.
13979        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
13980                mContext.getContentResolver(),
13981                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
13982        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
13983        if (DEBUG_SETTINGS) {
13984            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
13985        }
13986
13987        synchronized (mPackages) {
13988            // Verify that all of the preferred activity components actually
13989            // exist.  It is possible for applications to be updated and at
13990            // that point remove a previously declared activity component that
13991            // had been set as a preferred activity.  We try to clean this up
13992            // the next time we encounter that preferred activity, but it is
13993            // possible for the user flow to never be able to return to that
13994            // situation so here we do a sanity check to make sure we haven't
13995            // left any junk around.
13996            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
13997            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13998                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13999                removed.clear();
14000                for (PreferredActivity pa : pir.filterSet()) {
14001                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
14002                        removed.add(pa);
14003                    }
14004                }
14005                if (removed.size() > 0) {
14006                    for (int r=0; r<removed.size(); r++) {
14007                        PreferredActivity pa = removed.get(r);
14008                        Slog.w(TAG, "Removing dangling preferred activity: "
14009                                + pa.mPref.mComponent);
14010                        pir.removeFilter(pa);
14011                    }
14012                    mSettings.writePackageRestrictionsLPr(
14013                            mSettings.mPreferredActivities.keyAt(i));
14014                }
14015            }
14016        }
14017        sUserManager.systemReady();
14018
14019        // If we upgraded grant all default permissions before kicking off.
14020        if (isFirstBoot() || (CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE && mIsUpgrade)) {
14021            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
14022            for (int userId : UserManagerService.getInstance().getUserIds()) {
14023                mDefaultPermissionPolicy.grantDefaultPermissions(userId);
14024            }
14025        }
14026
14027        // Kick off any messages waiting for system ready
14028        if (mPostSystemReadyMessages != null) {
14029            for (Message msg : mPostSystemReadyMessages) {
14030                msg.sendToTarget();
14031            }
14032            mPostSystemReadyMessages = null;
14033        }
14034
14035        // Watch for external volumes that come and go over time
14036        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14037        storage.registerListener(mStorageListener);
14038
14039        mInstallerService.systemReady();
14040        mPackageDexOptimizer.systemReady();
14041    }
14042
14043    @Override
14044    public boolean isSafeMode() {
14045        return mSafeMode;
14046    }
14047
14048    @Override
14049    public boolean hasSystemUidErrors() {
14050        return mHasSystemUidErrors;
14051    }
14052
14053    static String arrayToString(int[] array) {
14054        StringBuffer buf = new StringBuffer(128);
14055        buf.append('[');
14056        if (array != null) {
14057            for (int i=0; i<array.length; i++) {
14058                if (i > 0) buf.append(", ");
14059                buf.append(array[i]);
14060            }
14061        }
14062        buf.append(']');
14063        return buf.toString();
14064    }
14065
14066    static class DumpState {
14067        public static final int DUMP_LIBS = 1 << 0;
14068        public static final int DUMP_FEATURES = 1 << 1;
14069        public static final int DUMP_RESOLVERS = 1 << 2;
14070        public static final int DUMP_PERMISSIONS = 1 << 3;
14071        public static final int DUMP_PACKAGES = 1 << 4;
14072        public static final int DUMP_SHARED_USERS = 1 << 5;
14073        public static final int DUMP_MESSAGES = 1 << 6;
14074        public static final int DUMP_PROVIDERS = 1 << 7;
14075        public static final int DUMP_VERIFIERS = 1 << 8;
14076        public static final int DUMP_PREFERRED = 1 << 9;
14077        public static final int DUMP_PREFERRED_XML = 1 << 10;
14078        public static final int DUMP_KEYSETS = 1 << 11;
14079        public static final int DUMP_VERSION = 1 << 12;
14080        public static final int DUMP_INSTALLS = 1 << 13;
14081        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
14082        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
14083
14084        public static final int OPTION_SHOW_FILTERS = 1 << 0;
14085
14086        private int mTypes;
14087
14088        private int mOptions;
14089
14090        private boolean mTitlePrinted;
14091
14092        private SharedUserSetting mSharedUser;
14093
14094        public boolean isDumping(int type) {
14095            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
14096                return true;
14097            }
14098
14099            return (mTypes & type) != 0;
14100        }
14101
14102        public void setDump(int type) {
14103            mTypes |= type;
14104        }
14105
14106        public boolean isOptionEnabled(int option) {
14107            return (mOptions & option) != 0;
14108        }
14109
14110        public void setOptionEnabled(int option) {
14111            mOptions |= option;
14112        }
14113
14114        public boolean onTitlePrinted() {
14115            final boolean printed = mTitlePrinted;
14116            mTitlePrinted = true;
14117            return printed;
14118        }
14119
14120        public boolean getTitlePrinted() {
14121            return mTitlePrinted;
14122        }
14123
14124        public void setTitlePrinted(boolean enabled) {
14125            mTitlePrinted = enabled;
14126        }
14127
14128        public SharedUserSetting getSharedUser() {
14129            return mSharedUser;
14130        }
14131
14132        public void setSharedUser(SharedUserSetting user) {
14133            mSharedUser = user;
14134        }
14135    }
14136
14137    @Override
14138    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
14139        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
14140                != PackageManager.PERMISSION_GRANTED) {
14141            pw.println("Permission Denial: can't dump ActivityManager from from pid="
14142                    + Binder.getCallingPid()
14143                    + ", uid=" + Binder.getCallingUid()
14144                    + " without permission "
14145                    + android.Manifest.permission.DUMP);
14146            return;
14147        }
14148
14149        DumpState dumpState = new DumpState();
14150        boolean fullPreferred = false;
14151        boolean checkin = false;
14152
14153        String packageName = null;
14154
14155        int opti = 0;
14156        while (opti < args.length) {
14157            String opt = args[opti];
14158            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
14159                break;
14160            }
14161            opti++;
14162
14163            if ("-a".equals(opt)) {
14164                // Right now we only know how to print all.
14165            } else if ("-h".equals(opt)) {
14166                pw.println("Package manager dump options:");
14167                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
14168                pw.println("    --checkin: dump for a checkin");
14169                pw.println("    -f: print details of intent filters");
14170                pw.println("    -h: print this help");
14171                pw.println("  cmd may be one of:");
14172                pw.println("    l[ibraries]: list known shared libraries");
14173                pw.println("    f[ibraries]: list device features");
14174                pw.println("    k[eysets]: print known keysets");
14175                pw.println("    r[esolvers]: dump intent resolvers");
14176                pw.println("    perm[issions]: dump permissions");
14177                pw.println("    pref[erred]: print preferred package settings");
14178                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
14179                pw.println("    prov[iders]: dump content providers");
14180                pw.println("    p[ackages]: dump installed packages");
14181                pw.println("    s[hared-users]: dump shared user IDs");
14182                pw.println("    m[essages]: print collected runtime messages");
14183                pw.println("    v[erifiers]: print package verifier info");
14184                pw.println("    version: print database version info");
14185                pw.println("    write: write current settings now");
14186                pw.println("    <package.name>: info about given package");
14187                pw.println("    installs: details about install sessions");
14188                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
14189                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
14190                return;
14191            } else if ("--checkin".equals(opt)) {
14192                checkin = true;
14193            } else if ("-f".equals(opt)) {
14194                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14195            } else {
14196                pw.println("Unknown argument: " + opt + "; use -h for help");
14197            }
14198        }
14199
14200        // Is the caller requesting to dump a particular piece of data?
14201        if (opti < args.length) {
14202            String cmd = args[opti];
14203            opti++;
14204            // Is this a package name?
14205            if ("android".equals(cmd) || cmd.contains(".")) {
14206                packageName = cmd;
14207                // When dumping a single package, we always dump all of its
14208                // filter information since the amount of data will be reasonable.
14209                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14210            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
14211                dumpState.setDump(DumpState.DUMP_LIBS);
14212            } else if ("f".equals(cmd) || "features".equals(cmd)) {
14213                dumpState.setDump(DumpState.DUMP_FEATURES);
14214            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
14215                dumpState.setDump(DumpState.DUMP_RESOLVERS);
14216            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
14217                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
14218            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
14219                dumpState.setDump(DumpState.DUMP_PREFERRED);
14220            } else if ("preferred-xml".equals(cmd)) {
14221                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
14222                if (opti < args.length && "--full".equals(args[opti])) {
14223                    fullPreferred = true;
14224                    opti++;
14225                }
14226            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
14227                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
14228            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
14229                dumpState.setDump(DumpState.DUMP_PACKAGES);
14230            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
14231                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
14232            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
14233                dumpState.setDump(DumpState.DUMP_PROVIDERS);
14234            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
14235                dumpState.setDump(DumpState.DUMP_MESSAGES);
14236            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
14237                dumpState.setDump(DumpState.DUMP_VERIFIERS);
14238            } else if ("i".equals(cmd) || "ifv".equals(cmd)
14239                    || "intent-filter-verifiers".equals(cmd)) {
14240                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
14241            } else if ("version".equals(cmd)) {
14242                dumpState.setDump(DumpState.DUMP_VERSION);
14243            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
14244                dumpState.setDump(DumpState.DUMP_KEYSETS);
14245            } else if ("installs".equals(cmd)) {
14246                dumpState.setDump(DumpState.DUMP_INSTALLS);
14247            } else if ("write".equals(cmd)) {
14248                synchronized (mPackages) {
14249                    mSettings.writeLPr();
14250                    pw.println("Settings written.");
14251                    return;
14252                }
14253            }
14254        }
14255
14256        if (checkin) {
14257            pw.println("vers,1");
14258        }
14259
14260        // reader
14261        synchronized (mPackages) {
14262            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
14263                if (!checkin) {
14264                    if (dumpState.onTitlePrinted())
14265                        pw.println();
14266                    pw.println("Database versions:");
14267                    pw.print("  SDK Version:");
14268                    pw.print(" internal=");
14269                    pw.print(mSettings.mInternalSdkPlatform);
14270                    pw.print(" external=");
14271                    pw.println(mSettings.mExternalSdkPlatform);
14272                    pw.print("  DB Version:");
14273                    pw.print(" internal=");
14274                    pw.print(mSettings.mInternalDatabaseVersion);
14275                    pw.print(" external=");
14276                    pw.println(mSettings.mExternalDatabaseVersion);
14277                }
14278            }
14279
14280            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
14281                if (!checkin) {
14282                    if (dumpState.onTitlePrinted())
14283                        pw.println();
14284                    pw.println("Verifiers:");
14285                    pw.print("  Required: ");
14286                    pw.print(mRequiredVerifierPackage);
14287                    pw.print(" (uid=");
14288                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
14289                    pw.println(")");
14290                } else if (mRequiredVerifierPackage != null) {
14291                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
14292                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
14293                }
14294            }
14295
14296            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
14297                    packageName == null) {
14298                if (mIntentFilterVerifierComponent != null) {
14299                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
14300                    if (!checkin) {
14301                        if (dumpState.onTitlePrinted())
14302                            pw.println();
14303                        pw.println("Intent Filter Verifier:");
14304                        pw.print("  Using: ");
14305                        pw.print(verifierPackageName);
14306                        pw.print(" (uid=");
14307                        pw.print(getPackageUid(verifierPackageName, 0));
14308                        pw.println(")");
14309                    } else if (verifierPackageName != null) {
14310                        pw.print("ifv,"); pw.print(verifierPackageName);
14311                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
14312                    }
14313                } else {
14314                    pw.println();
14315                    pw.println("No Intent Filter Verifier available!");
14316                }
14317            }
14318
14319            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
14320                boolean printedHeader = false;
14321                final Iterator<String> it = mSharedLibraries.keySet().iterator();
14322                while (it.hasNext()) {
14323                    String name = it.next();
14324                    SharedLibraryEntry ent = mSharedLibraries.get(name);
14325                    if (!checkin) {
14326                        if (!printedHeader) {
14327                            if (dumpState.onTitlePrinted())
14328                                pw.println();
14329                            pw.println("Libraries:");
14330                            printedHeader = true;
14331                        }
14332                        pw.print("  ");
14333                    } else {
14334                        pw.print("lib,");
14335                    }
14336                    pw.print(name);
14337                    if (!checkin) {
14338                        pw.print(" -> ");
14339                    }
14340                    if (ent.path != null) {
14341                        if (!checkin) {
14342                            pw.print("(jar) ");
14343                            pw.print(ent.path);
14344                        } else {
14345                            pw.print(",jar,");
14346                            pw.print(ent.path);
14347                        }
14348                    } else {
14349                        if (!checkin) {
14350                            pw.print("(apk) ");
14351                            pw.print(ent.apk);
14352                        } else {
14353                            pw.print(",apk,");
14354                            pw.print(ent.apk);
14355                        }
14356                    }
14357                    pw.println();
14358                }
14359            }
14360
14361            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
14362                if (dumpState.onTitlePrinted())
14363                    pw.println();
14364                if (!checkin) {
14365                    pw.println("Features:");
14366                }
14367                Iterator<String> it = mAvailableFeatures.keySet().iterator();
14368                while (it.hasNext()) {
14369                    String name = it.next();
14370                    if (!checkin) {
14371                        pw.print("  ");
14372                    } else {
14373                        pw.print("feat,");
14374                    }
14375                    pw.println(name);
14376                }
14377            }
14378
14379            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
14380                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
14381                        : "Activity Resolver Table:", "  ", packageName,
14382                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14383                    dumpState.setTitlePrinted(true);
14384                }
14385                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
14386                        : "Receiver Resolver Table:", "  ", packageName,
14387                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14388                    dumpState.setTitlePrinted(true);
14389                }
14390                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
14391                        : "Service Resolver Table:", "  ", packageName,
14392                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14393                    dumpState.setTitlePrinted(true);
14394                }
14395                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
14396                        : "Provider Resolver Table:", "  ", packageName,
14397                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14398                    dumpState.setTitlePrinted(true);
14399                }
14400            }
14401
14402            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
14403                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14404                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14405                    int user = mSettings.mPreferredActivities.keyAt(i);
14406                    if (pir.dump(pw,
14407                            dumpState.getTitlePrinted()
14408                                ? "\nPreferred Activities User " + user + ":"
14409                                : "Preferred Activities User " + user + ":", "  ",
14410                            packageName, true, false)) {
14411                        dumpState.setTitlePrinted(true);
14412                    }
14413                }
14414            }
14415
14416            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
14417                pw.flush();
14418                FileOutputStream fout = new FileOutputStream(fd);
14419                BufferedOutputStream str = new BufferedOutputStream(fout);
14420                XmlSerializer serializer = new FastXmlSerializer();
14421                try {
14422                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
14423                    serializer.startDocument(null, true);
14424                    serializer.setFeature(
14425                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
14426                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
14427                    serializer.endDocument();
14428                    serializer.flush();
14429                } catch (IllegalArgumentException e) {
14430                    pw.println("Failed writing: " + e);
14431                } catch (IllegalStateException e) {
14432                    pw.println("Failed writing: " + e);
14433                } catch (IOException e) {
14434                    pw.println("Failed writing: " + e);
14435                }
14436            }
14437
14438            if (!checkin
14439                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
14440                    && packageName == null) {
14441                pw.println();
14442                int count = mSettings.mPackages.size();
14443                if (count == 0) {
14444                    pw.println("No domain preferred apps!");
14445                    pw.println();
14446                } else {
14447                    final String prefix = "  ";
14448                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
14449                    if (allPackageSettings.size() == 0) {
14450                        pw.println("No domain preferred apps!");
14451                        pw.println();
14452                    } else {
14453                        pw.println("Domain preferred apps status:");
14454                        pw.println();
14455                        count = 0;
14456                        for (PackageSetting ps : allPackageSettings) {
14457                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
14458                            if (ivi == null || ivi.getPackageName() == null) continue;
14459                            pw.println(prefix + "Package Name: " + ivi.getPackageName());
14460                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
14461                            pw.println(prefix + "Status: " + ivi.getStatusString());
14462                            pw.println();
14463                            count++;
14464                        }
14465                        if (count == 0) {
14466                            pw.println(prefix + "No domain preferred app status!");
14467                            pw.println();
14468                        }
14469                        for (int userId : sUserManager.getUserIds()) {
14470                            pw.println("Domain preferred apps for User " + userId + ":");
14471                            pw.println();
14472                            count = 0;
14473                            for (PackageSetting ps : allPackageSettings) {
14474                                IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
14475                                if (ivi == null || ivi.getPackageName() == null) {
14476                                    continue;
14477                                }
14478                                final int status = ps.getDomainVerificationStatusForUser(userId);
14479                                if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
14480                                    continue;
14481                                }
14482                                pw.println(prefix + "Package Name: " + ivi.getPackageName());
14483                                pw.println(prefix + "Domains: " + ivi.getDomainsString());
14484                                String statusStr = IntentFilterVerificationInfo.
14485                                        getStatusStringFromValue(status);
14486                                pw.println(prefix + "Status: " + statusStr);
14487                                pw.println();
14488                                count++;
14489                            }
14490                            if (count == 0) {
14491                                pw.println(prefix + "No domain preferred apps!");
14492                                pw.println();
14493                            }
14494                        }
14495                    }
14496                }
14497            }
14498
14499            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
14500                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
14501                if (packageName == null) {
14502                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
14503                        if (iperm == 0) {
14504                            if (dumpState.onTitlePrinted())
14505                                pw.println();
14506                            pw.println("AppOp Permissions:");
14507                        }
14508                        pw.print("  AppOp Permission ");
14509                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
14510                        pw.println(":");
14511                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
14512                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
14513                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
14514                        }
14515                    }
14516                }
14517            }
14518
14519            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
14520                boolean printedSomething = false;
14521                for (PackageParser.Provider p : mProviders.mProviders.values()) {
14522                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14523                        continue;
14524                    }
14525                    if (!printedSomething) {
14526                        if (dumpState.onTitlePrinted())
14527                            pw.println();
14528                        pw.println("Registered ContentProviders:");
14529                        printedSomething = true;
14530                    }
14531                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
14532                    pw.print("    "); pw.println(p.toString());
14533                }
14534                printedSomething = false;
14535                for (Map.Entry<String, PackageParser.Provider> entry :
14536                        mProvidersByAuthority.entrySet()) {
14537                    PackageParser.Provider p = entry.getValue();
14538                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14539                        continue;
14540                    }
14541                    if (!printedSomething) {
14542                        if (dumpState.onTitlePrinted())
14543                            pw.println();
14544                        pw.println("ContentProvider Authorities:");
14545                        printedSomething = true;
14546                    }
14547                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
14548                    pw.print("    "); pw.println(p.toString());
14549                    if (p.info != null && p.info.applicationInfo != null) {
14550                        final String appInfo = p.info.applicationInfo.toString();
14551                        pw.print("      applicationInfo="); pw.println(appInfo);
14552                    }
14553                }
14554            }
14555
14556            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
14557                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
14558            }
14559
14560            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
14561                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
14562            }
14563
14564            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
14565                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin);
14566            }
14567
14568            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
14569                // XXX should handle packageName != null by dumping only install data that
14570                // the given package is involved with.
14571                if (dumpState.onTitlePrinted()) pw.println();
14572                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
14573            }
14574
14575            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
14576                if (dumpState.onTitlePrinted()) pw.println();
14577                mSettings.dumpReadMessagesLPr(pw, dumpState);
14578
14579                pw.println();
14580                pw.println("Package warning messages:");
14581                BufferedReader in = null;
14582                String line = null;
14583                try {
14584                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
14585                    while ((line = in.readLine()) != null) {
14586                        if (line.contains("ignored: updated version")) continue;
14587                        pw.println(line);
14588                    }
14589                } catch (IOException ignored) {
14590                } finally {
14591                    IoUtils.closeQuietly(in);
14592                }
14593            }
14594
14595            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
14596                BufferedReader in = null;
14597                String line = null;
14598                try {
14599                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
14600                    while ((line = in.readLine()) != null) {
14601                        if (line.contains("ignored: updated version")) continue;
14602                        pw.print("msg,");
14603                        pw.println(line);
14604                    }
14605                } catch (IOException ignored) {
14606                } finally {
14607                    IoUtils.closeQuietly(in);
14608                }
14609            }
14610        }
14611    }
14612
14613    // ------- apps on sdcard specific code -------
14614    static final boolean DEBUG_SD_INSTALL = false;
14615
14616    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
14617
14618    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
14619
14620    private boolean mMediaMounted = false;
14621
14622    static String getEncryptKey() {
14623        try {
14624            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
14625                    SD_ENCRYPTION_KEYSTORE_NAME);
14626            if (sdEncKey == null) {
14627                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
14628                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
14629                if (sdEncKey == null) {
14630                    Slog.e(TAG, "Failed to create encryption keys");
14631                    return null;
14632                }
14633            }
14634            return sdEncKey;
14635        } catch (NoSuchAlgorithmException nsae) {
14636            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
14637            return null;
14638        } catch (IOException ioe) {
14639            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
14640            return null;
14641        }
14642    }
14643
14644    /*
14645     * Update media status on PackageManager.
14646     */
14647    @Override
14648    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
14649        int callingUid = Binder.getCallingUid();
14650        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
14651            throw new SecurityException("Media status can only be updated by the system");
14652        }
14653        // reader; this apparently protects mMediaMounted, but should probably
14654        // be a different lock in that case.
14655        synchronized (mPackages) {
14656            Log.i(TAG, "Updating external media status from "
14657                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
14658                    + (mediaStatus ? "mounted" : "unmounted"));
14659            if (DEBUG_SD_INSTALL)
14660                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
14661                        + ", mMediaMounted=" + mMediaMounted);
14662            if (mediaStatus == mMediaMounted) {
14663                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
14664                        : 0, -1);
14665                mHandler.sendMessage(msg);
14666                return;
14667            }
14668            mMediaMounted = mediaStatus;
14669        }
14670        // Queue up an async operation since the package installation may take a
14671        // little while.
14672        mHandler.post(new Runnable() {
14673            public void run() {
14674                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
14675            }
14676        });
14677    }
14678
14679    /**
14680     * Called by MountService when the initial ASECs to scan are available.
14681     * Should block until all the ASEC containers are finished being scanned.
14682     */
14683    public void scanAvailableAsecs() {
14684        updateExternalMediaStatusInner(true, false, false);
14685        if (mShouldRestoreconData) {
14686            SELinuxMMAC.setRestoreconDone();
14687            mShouldRestoreconData = false;
14688        }
14689    }
14690
14691    /*
14692     * Collect information of applications on external media, map them against
14693     * existing containers and update information based on current mount status.
14694     * Please note that we always have to report status if reportStatus has been
14695     * set to true especially when unloading packages.
14696     */
14697    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
14698            boolean externalStorage) {
14699        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
14700        int[] uidArr = EmptyArray.INT;
14701
14702        final String[] list = PackageHelper.getSecureContainerList();
14703        if (ArrayUtils.isEmpty(list)) {
14704            Log.i(TAG, "No secure containers found");
14705        } else {
14706            // Process list of secure containers and categorize them
14707            // as active or stale based on their package internal state.
14708
14709            // reader
14710            synchronized (mPackages) {
14711                for (String cid : list) {
14712                    // Leave stages untouched for now; installer service owns them
14713                    if (PackageInstallerService.isStageName(cid)) continue;
14714
14715                    if (DEBUG_SD_INSTALL)
14716                        Log.i(TAG, "Processing container " + cid);
14717                    String pkgName = getAsecPackageName(cid);
14718                    if (pkgName == null) {
14719                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
14720                        continue;
14721                    }
14722                    if (DEBUG_SD_INSTALL)
14723                        Log.i(TAG, "Looking for pkg : " + pkgName);
14724
14725                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
14726                    if (ps == null) {
14727                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
14728                        continue;
14729                    }
14730
14731                    /*
14732                     * Skip packages that are not external if we're unmounting
14733                     * external storage.
14734                     */
14735                    if (externalStorage && !isMounted && !isExternal(ps)) {
14736                        continue;
14737                    }
14738
14739                    final AsecInstallArgs args = new AsecInstallArgs(cid,
14740                            getAppDexInstructionSets(ps), ps.isForwardLocked());
14741                    // The package status is changed only if the code path
14742                    // matches between settings and the container id.
14743                    if (ps.codePathString != null
14744                            && ps.codePathString.startsWith(args.getCodePath())) {
14745                        if (DEBUG_SD_INSTALL) {
14746                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
14747                                    + " at code path: " + ps.codePathString);
14748                        }
14749
14750                        // We do have a valid package installed on sdcard
14751                        processCids.put(args, ps.codePathString);
14752                        final int uid = ps.appId;
14753                        if (uid != -1) {
14754                            uidArr = ArrayUtils.appendInt(uidArr, uid);
14755                        }
14756                    } else {
14757                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
14758                                + ps.codePathString);
14759                    }
14760                }
14761            }
14762
14763            Arrays.sort(uidArr);
14764        }
14765
14766        // Process packages with valid entries.
14767        if (isMounted) {
14768            if (DEBUG_SD_INSTALL)
14769                Log.i(TAG, "Loading packages");
14770            loadMediaPackages(processCids, uidArr);
14771            startCleaningPackages();
14772            mInstallerService.onSecureContainersAvailable();
14773        } else {
14774            if (DEBUG_SD_INSTALL)
14775                Log.i(TAG, "Unloading packages");
14776            unloadMediaPackages(processCids, uidArr, reportStatus);
14777        }
14778    }
14779
14780    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14781            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
14782        final int size = infos.size();
14783        final String[] packageNames = new String[size];
14784        final int[] packageUids = new int[size];
14785        for (int i = 0; i < size; i++) {
14786            final ApplicationInfo info = infos.get(i);
14787            packageNames[i] = info.packageName;
14788            packageUids[i] = info.uid;
14789        }
14790        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
14791                finishedReceiver);
14792    }
14793
14794    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14795            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
14796        sendResourcesChangedBroadcast(mediaStatus, replacing,
14797                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
14798    }
14799
14800    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14801            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
14802        int size = pkgList.length;
14803        if (size > 0) {
14804            // Send broadcasts here
14805            Bundle extras = new Bundle();
14806            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14807            if (uidArr != null) {
14808                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
14809            }
14810            if (replacing) {
14811                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
14812            }
14813            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
14814                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
14815            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
14816        }
14817    }
14818
14819   /*
14820     * Look at potentially valid container ids from processCids If package
14821     * information doesn't match the one on record or package scanning fails,
14822     * the cid is added to list of removeCids. We currently don't delete stale
14823     * containers.
14824     */
14825    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
14826        ArrayList<String> pkgList = new ArrayList<String>();
14827        Set<AsecInstallArgs> keys = processCids.keySet();
14828
14829        for (AsecInstallArgs args : keys) {
14830            String codePath = processCids.get(args);
14831            if (DEBUG_SD_INSTALL)
14832                Log.i(TAG, "Loading container : " + args.cid);
14833            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14834            try {
14835                // Make sure there are no container errors first.
14836                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
14837                    Slog.e(TAG, "Failed to mount cid : " + args.cid
14838                            + " when installing from sdcard");
14839                    continue;
14840                }
14841                // Check code path here.
14842                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
14843                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
14844                            + " does not match one in settings " + codePath);
14845                    continue;
14846                }
14847                // Parse package
14848                int parseFlags = mDefParseFlags;
14849                if (args.isExternalAsec()) {
14850                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
14851                }
14852                if (args.isFwdLocked()) {
14853                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
14854                }
14855
14856                synchronized (mInstallLock) {
14857                    PackageParser.Package pkg = null;
14858                    try {
14859                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
14860                    } catch (PackageManagerException e) {
14861                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
14862                    }
14863                    // Scan the package
14864                    if (pkg != null) {
14865                        /*
14866                         * TODO why is the lock being held? doPostInstall is
14867                         * called in other places without the lock. This needs
14868                         * to be straightened out.
14869                         */
14870                        // writer
14871                        synchronized (mPackages) {
14872                            retCode = PackageManager.INSTALL_SUCCEEDED;
14873                            pkgList.add(pkg.packageName);
14874                            // Post process args
14875                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
14876                                    pkg.applicationInfo.uid);
14877                        }
14878                    } else {
14879                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
14880                    }
14881                }
14882
14883            } finally {
14884                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
14885                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
14886                }
14887            }
14888        }
14889        // writer
14890        synchronized (mPackages) {
14891            // If the platform SDK has changed since the last time we booted,
14892            // we need to re-grant app permission to catch any new ones that
14893            // appear. This is really a hack, and means that apps can in some
14894            // cases get permissions that the user didn't initially explicitly
14895            // allow... it would be nice to have some better way to handle
14896            // this situation.
14897            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
14898            if (regrantPermissions)
14899                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
14900                        + mSdkVersion + "; regranting permissions for external storage");
14901            mSettings.mExternalSdkPlatform = mSdkVersion;
14902
14903            // Make sure group IDs have been assigned, and any permission
14904            // changes in other apps are accounted for
14905            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
14906                    | (regrantPermissions
14907                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
14908                            : 0));
14909
14910            mSettings.updateExternalDatabaseVersion();
14911
14912            // can downgrade to reader
14913            // Persist settings
14914            mSettings.writeLPr();
14915        }
14916        // Send a broadcast to let everyone know we are done processing
14917        if (pkgList.size() > 0) {
14918            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
14919        }
14920    }
14921
14922   /*
14923     * Utility method to unload a list of specified containers
14924     */
14925    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
14926        // Just unmount all valid containers.
14927        for (AsecInstallArgs arg : cidArgs) {
14928            synchronized (mInstallLock) {
14929                arg.doPostDeleteLI(false);
14930           }
14931       }
14932   }
14933
14934    /*
14935     * Unload packages mounted on external media. This involves deleting package
14936     * data from internal structures, sending broadcasts about diabled packages,
14937     * gc'ing to free up references, unmounting all secure containers
14938     * corresponding to packages on external media, and posting a
14939     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
14940     * that we always have to post this message if status has been requested no
14941     * matter what.
14942     */
14943    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
14944            final boolean reportStatus) {
14945        if (DEBUG_SD_INSTALL)
14946            Log.i(TAG, "unloading media packages");
14947        ArrayList<String> pkgList = new ArrayList<String>();
14948        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
14949        final Set<AsecInstallArgs> keys = processCids.keySet();
14950        for (AsecInstallArgs args : keys) {
14951            String pkgName = args.getPackageName();
14952            if (DEBUG_SD_INSTALL)
14953                Log.i(TAG, "Trying to unload pkg : " + pkgName);
14954            // Delete package internally
14955            PackageRemovedInfo outInfo = new PackageRemovedInfo();
14956            synchronized (mInstallLock) {
14957                boolean res = deletePackageLI(pkgName, null, false, null, null,
14958                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
14959                if (res) {
14960                    pkgList.add(pkgName);
14961                } else {
14962                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
14963                    failedList.add(args);
14964                }
14965            }
14966        }
14967
14968        // reader
14969        synchronized (mPackages) {
14970            // We didn't update the settings after removing each package;
14971            // write them now for all packages.
14972            mSettings.writeLPr();
14973        }
14974
14975        // We have to absolutely send UPDATED_MEDIA_STATUS only
14976        // after confirming that all the receivers processed the ordered
14977        // broadcast when packages get disabled, force a gc to clean things up.
14978        // and unload all the containers.
14979        if (pkgList.size() > 0) {
14980            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
14981                    new IIntentReceiver.Stub() {
14982                public void performReceive(Intent intent, int resultCode, String data,
14983                        Bundle extras, boolean ordered, boolean sticky,
14984                        int sendingUser) throws RemoteException {
14985                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
14986                            reportStatus ? 1 : 0, 1, keys);
14987                    mHandler.sendMessage(msg);
14988                }
14989            });
14990        } else {
14991            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
14992                    keys);
14993            mHandler.sendMessage(msg);
14994        }
14995    }
14996
14997    private void loadPrivatePackages(VolumeInfo vol) {
14998        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
14999        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
15000        synchronized (mInstallLock) {
15001        synchronized (mPackages) {
15002            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15003            for (PackageSetting ps : packages) {
15004                final PackageParser.Package pkg;
15005                try {
15006                    pkg = scanPackageLI(ps.codePath, parseFlags, 0, 0, null);
15007                    loaded.add(pkg.applicationInfo);
15008                } catch (PackageManagerException e) {
15009                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
15010                }
15011            }
15012
15013            // TODO: regrant any permissions that changed based since original install
15014
15015            mSettings.writeLPr();
15016        }
15017        }
15018
15019        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
15020        sendResourcesChangedBroadcast(true, false, loaded, null);
15021    }
15022
15023    private void unloadPrivatePackages(VolumeInfo vol) {
15024        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
15025        synchronized (mInstallLock) {
15026        synchronized (mPackages) {
15027            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15028            for (PackageSetting ps : packages) {
15029                if (ps.pkg == null) continue;
15030
15031                final ApplicationInfo info = ps.pkg.applicationInfo;
15032                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
15033                if (deletePackageLI(ps.name, null, false, null, null,
15034                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
15035                    unloaded.add(info);
15036                } else {
15037                    Slog.w(TAG, "Failed to unload " + ps.codePath);
15038                }
15039            }
15040
15041            mSettings.writeLPr();
15042        }
15043        }
15044
15045        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
15046        sendResourcesChangedBroadcast(false, false, unloaded, null);
15047    }
15048
15049    private void unfreezePackage(String packageName) {
15050        synchronized (mPackages) {
15051            final PackageSetting ps = mSettings.mPackages.get(packageName);
15052            if (ps != null) {
15053                ps.frozen = false;
15054            }
15055        }
15056    }
15057
15058    @Override
15059    public int movePackage(final String packageName, final String volumeUuid) {
15060        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15061
15062        final int moveId = mNextMoveId.getAndIncrement();
15063        try {
15064            movePackageInternal(packageName, volumeUuid, moveId);
15065        } catch (PackageManagerException e) {
15066            Slog.w(TAG, "Failed to move " + packageName, e);
15067            mMoveCallbacks.notifyStatusChanged(moveId,
15068                    PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15069        }
15070        return moveId;
15071    }
15072
15073    private void movePackageInternal(final String packageName, final String volumeUuid,
15074            final int moveId) throws PackageManagerException {
15075        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
15076        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15077        final PackageManager pm = mContext.getPackageManager();
15078
15079        final boolean currentAsec;
15080        final String currentVolumeUuid;
15081        final File codeFile;
15082        final String installerPackageName;
15083        final String packageAbiOverride;
15084        final int appId;
15085        final String seinfo;
15086        final String label;
15087
15088        // reader
15089        synchronized (mPackages) {
15090            final PackageParser.Package pkg = mPackages.get(packageName);
15091            final PackageSetting ps = mSettings.mPackages.get(packageName);
15092            if (pkg == null || ps == null) {
15093                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
15094            }
15095
15096            if (pkg.applicationInfo.isSystemApp()) {
15097                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
15098                        "Cannot move system application");
15099            }
15100
15101            if (Objects.equals(ps.volumeUuid, volumeUuid)) {
15102                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15103                        "Package already moved to " + volumeUuid);
15104            }
15105
15106            final File probe = new File(pkg.codePath);
15107            final File probeOat = new File(probe, "oat");
15108            if (!probe.isDirectory() || !probeOat.isDirectory()) {
15109                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15110                        "Move only supported for modern cluster style installs");
15111            }
15112
15113            if (ps.frozen) {
15114                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
15115                        "Failed to move already frozen package");
15116            }
15117            ps.frozen = true;
15118
15119            currentAsec = pkg.applicationInfo.isForwardLocked()
15120                    || pkg.applicationInfo.isExternalAsec();
15121            currentVolumeUuid = ps.volumeUuid;
15122            codeFile = new File(pkg.codePath);
15123            installerPackageName = ps.installerPackageName;
15124            packageAbiOverride = ps.cpuAbiOverrideString;
15125            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
15126            seinfo = pkg.applicationInfo.seinfo;
15127            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
15128        }
15129
15130        // Now that we're guarded by frozen state, kill app during move
15131        killApplication(packageName, appId, "move pkg");
15132
15133        final Bundle extras = new Bundle();
15134        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
15135        extras.putString(Intent.EXTRA_TITLE, label);
15136        mMoveCallbacks.notifyCreated(moveId, extras);
15137
15138        int installFlags;
15139        final boolean moveCompleteApp;
15140        final File measurePath;
15141
15142        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
15143            installFlags = INSTALL_INTERNAL;
15144            moveCompleteApp = !currentAsec;
15145            measurePath = Environment.getDataAppDirectory(volumeUuid);
15146        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
15147            installFlags = INSTALL_EXTERNAL;
15148            moveCompleteApp = false;
15149            measurePath = storage.getPrimaryPhysicalVolume().getPath();
15150        } else {
15151            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
15152            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
15153                    || !volume.isMountedWritable()) {
15154                unfreezePackage(packageName);
15155                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15156                        "Move location not mounted private volume");
15157            }
15158
15159            Preconditions.checkState(!currentAsec);
15160
15161            installFlags = INSTALL_INTERNAL;
15162            moveCompleteApp = true;
15163            measurePath = Environment.getDataAppDirectory(volumeUuid);
15164        }
15165
15166        final PackageStats stats = new PackageStats(null, -1);
15167        synchronized (mInstaller) {
15168            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
15169                unfreezePackage(packageName);
15170                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15171                        "Failed to measure package size");
15172            }
15173        }
15174
15175        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
15176                + stats.dataSize);
15177
15178        final long startFreeBytes = measurePath.getFreeSpace();
15179        final long sizeBytes;
15180        if (moveCompleteApp) {
15181            sizeBytes = stats.codeSize + stats.dataSize;
15182        } else {
15183            sizeBytes = stats.codeSize;
15184        }
15185
15186        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
15187            unfreezePackage(packageName);
15188            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15189                    "Not enough free space to move");
15190        }
15191
15192        mMoveCallbacks.notifyStatusChanged(moveId, 10);
15193
15194        final CountDownLatch installedLatch = new CountDownLatch(1);
15195        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
15196            @Override
15197            public void onUserActionRequired(Intent intent) throws RemoteException {
15198                throw new IllegalStateException();
15199            }
15200
15201            @Override
15202            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
15203                    Bundle extras) throws RemoteException {
15204                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
15205                        + PackageManager.installStatusToString(returnCode, msg));
15206
15207                installedLatch.countDown();
15208
15209                // Regardless of success or failure of the move operation,
15210                // always unfreeze the package
15211                unfreezePackage(packageName);
15212
15213                final int status = PackageManager.installStatusToPublicStatus(returnCode);
15214                switch (status) {
15215                    case PackageInstaller.STATUS_SUCCESS:
15216                        mMoveCallbacks.notifyStatusChanged(moveId,
15217                                PackageManager.MOVE_SUCCEEDED);
15218                        break;
15219                    case PackageInstaller.STATUS_FAILURE_STORAGE:
15220                        mMoveCallbacks.notifyStatusChanged(moveId,
15221                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
15222                        break;
15223                    default:
15224                        mMoveCallbacks.notifyStatusChanged(moveId,
15225                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15226                        break;
15227                }
15228            }
15229        };
15230
15231        final MoveInfo move;
15232        if (moveCompleteApp) {
15233            // Kick off a thread to report progress estimates
15234            new Thread() {
15235                @Override
15236                public void run() {
15237                    while (true) {
15238                        try {
15239                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
15240                                break;
15241                            }
15242                        } catch (InterruptedException ignored) {
15243                        }
15244
15245                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
15246                        final int progress = 10 + (int) MathUtils.constrain(
15247                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
15248                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
15249                    }
15250                }
15251            }.start();
15252
15253            final String dataAppName = codeFile.getName();
15254            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
15255                    dataAppName, appId, seinfo);
15256        } else {
15257            move = null;
15258        }
15259
15260        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
15261
15262        final Message msg = mHandler.obtainMessage(INIT_COPY);
15263        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
15264        msg.obj = new InstallParams(origin, move, installObserver, installFlags,
15265                installerPackageName, volumeUuid, null, user, packageAbiOverride);
15266        mHandler.sendMessage(msg);
15267    }
15268
15269    @Override
15270    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
15271        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15272
15273        final int realMoveId = mNextMoveId.getAndIncrement();
15274        final Bundle extras = new Bundle();
15275        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
15276        mMoveCallbacks.notifyCreated(realMoveId, extras);
15277
15278        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
15279            @Override
15280            public void onCreated(int moveId, Bundle extras) {
15281                // Ignored
15282            }
15283
15284            @Override
15285            public void onStatusChanged(int moveId, int status, long estMillis) {
15286                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
15287            }
15288        };
15289
15290        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15291        storage.setPrimaryStorageUuid(volumeUuid, callback);
15292        return realMoveId;
15293    }
15294
15295    @Override
15296    public int getMoveStatus(int moveId) {
15297        mContext.enforceCallingOrSelfPermission(
15298                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15299        return mMoveCallbacks.mLastStatus.get(moveId);
15300    }
15301
15302    @Override
15303    public void registerMoveCallback(IPackageMoveObserver callback) {
15304        mContext.enforceCallingOrSelfPermission(
15305                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15306        mMoveCallbacks.register(callback);
15307    }
15308
15309    @Override
15310    public void unregisterMoveCallback(IPackageMoveObserver callback) {
15311        mContext.enforceCallingOrSelfPermission(
15312                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15313        mMoveCallbacks.unregister(callback);
15314    }
15315
15316    @Override
15317    public boolean setInstallLocation(int loc) {
15318        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
15319                null);
15320        if (getInstallLocation() == loc) {
15321            return true;
15322        }
15323        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
15324                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
15325            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
15326                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
15327            return true;
15328        }
15329        return false;
15330   }
15331
15332    @Override
15333    public int getInstallLocation() {
15334        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15335                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
15336                PackageHelper.APP_INSTALL_AUTO);
15337    }
15338
15339    /** Called by UserManagerService */
15340    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
15341        mDirtyUsers.remove(userHandle);
15342        mSettings.removeUserLPw(userHandle);
15343        mPendingBroadcasts.remove(userHandle);
15344        if (mInstaller != null) {
15345            // Technically, we shouldn't be doing this with the package lock
15346            // held.  However, this is very rare, and there is already so much
15347            // other disk I/O going on, that we'll let it slide for now.
15348            final StorageManager storage = StorageManager.from(mContext);
15349            final List<VolumeInfo> vols = storage.getVolumes();
15350            for (VolumeInfo vol : vols) {
15351                if (vol.getType() == VolumeInfo.TYPE_PRIVATE && vol.isMountedWritable()) {
15352                    final String volumeUuid = vol.getFsUuid();
15353                    if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
15354                    mInstaller.removeUserDataDirs(volumeUuid, userHandle);
15355                }
15356            }
15357        }
15358        mUserNeedsBadging.delete(userHandle);
15359        removeUnusedPackagesLILPw(userManager, userHandle);
15360    }
15361
15362    /**
15363     * We're removing userHandle and would like to remove any downloaded packages
15364     * that are no longer in use by any other user.
15365     * @param userHandle the user being removed
15366     */
15367    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
15368        final boolean DEBUG_CLEAN_APKS = false;
15369        int [] users = userManager.getUserIdsLPr();
15370        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
15371        while (psit.hasNext()) {
15372            PackageSetting ps = psit.next();
15373            if (ps.pkg == null) {
15374                continue;
15375            }
15376            final String packageName = ps.pkg.packageName;
15377            // Skip over if system app
15378            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15379                continue;
15380            }
15381            if (DEBUG_CLEAN_APKS) {
15382                Slog.i(TAG, "Checking package " + packageName);
15383            }
15384            boolean keep = false;
15385            for (int i = 0; i < users.length; i++) {
15386                if (users[i] != userHandle && ps.getInstalled(users[i])) {
15387                    keep = true;
15388                    if (DEBUG_CLEAN_APKS) {
15389                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
15390                                + users[i]);
15391                    }
15392                    break;
15393                }
15394            }
15395            if (!keep) {
15396                if (DEBUG_CLEAN_APKS) {
15397                    Slog.i(TAG, "  Removing package " + packageName);
15398                }
15399                mHandler.post(new Runnable() {
15400                    public void run() {
15401                        deletePackageX(packageName, userHandle, 0);
15402                    } //end run
15403                });
15404            }
15405        }
15406    }
15407
15408    /** Called by UserManagerService */
15409    void createNewUserLILPw(int userHandle, File path) {
15410        if (mInstaller != null) {
15411            mInstaller.createUserConfig(userHandle);
15412            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
15413        }
15414    }
15415
15416    void newUserCreatedLILPw(final int userHandle) {
15417        // We cannot grant the default permissions with a lock held as
15418        // we query providers from other components for default handlers
15419        // such as enabled IMEs, etc.
15420        mHandler.post(new Runnable() {
15421            @Override
15422            public void run() {
15423                mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
15424            }
15425        });
15426    }
15427
15428    @Override
15429    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
15430        mContext.enforceCallingOrSelfPermission(
15431                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15432                "Only package verification agents can read the verifier device identity");
15433
15434        synchronized (mPackages) {
15435            return mSettings.getVerifierDeviceIdentityLPw();
15436        }
15437    }
15438
15439    @Override
15440    public void setPermissionEnforced(String permission, boolean enforced) {
15441        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
15442        if (READ_EXTERNAL_STORAGE.equals(permission)) {
15443            synchronized (mPackages) {
15444                if (mSettings.mReadExternalStorageEnforced == null
15445                        || mSettings.mReadExternalStorageEnforced != enforced) {
15446                    mSettings.mReadExternalStorageEnforced = enforced;
15447                    mSettings.writeLPr();
15448                }
15449            }
15450            // kill any non-foreground processes so we restart them and
15451            // grant/revoke the GID.
15452            final IActivityManager am = ActivityManagerNative.getDefault();
15453            if (am != null) {
15454                final long token = Binder.clearCallingIdentity();
15455                try {
15456                    am.killProcessesBelowForeground("setPermissionEnforcement");
15457                } catch (RemoteException e) {
15458                } finally {
15459                    Binder.restoreCallingIdentity(token);
15460                }
15461            }
15462        } else {
15463            throw new IllegalArgumentException("No selective enforcement for " + permission);
15464        }
15465    }
15466
15467    @Override
15468    @Deprecated
15469    public boolean isPermissionEnforced(String permission) {
15470        return true;
15471    }
15472
15473    @Override
15474    public boolean isStorageLow() {
15475        final long token = Binder.clearCallingIdentity();
15476        try {
15477            final DeviceStorageMonitorInternal
15478                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
15479            if (dsm != null) {
15480                return dsm.isMemoryLow();
15481            } else {
15482                return false;
15483            }
15484        } finally {
15485            Binder.restoreCallingIdentity(token);
15486        }
15487    }
15488
15489    @Override
15490    public IPackageInstaller getPackageInstaller() {
15491        return mInstallerService;
15492    }
15493
15494    private boolean userNeedsBadging(int userId) {
15495        int index = mUserNeedsBadging.indexOfKey(userId);
15496        if (index < 0) {
15497            final UserInfo userInfo;
15498            final long token = Binder.clearCallingIdentity();
15499            try {
15500                userInfo = sUserManager.getUserInfo(userId);
15501            } finally {
15502                Binder.restoreCallingIdentity(token);
15503            }
15504            final boolean b;
15505            if (userInfo != null && userInfo.isManagedProfile()) {
15506                b = true;
15507            } else {
15508                b = false;
15509            }
15510            mUserNeedsBadging.put(userId, b);
15511            return b;
15512        }
15513        return mUserNeedsBadging.valueAt(index);
15514    }
15515
15516    @Override
15517    public KeySet getKeySetByAlias(String packageName, String alias) {
15518        if (packageName == null || alias == null) {
15519            return null;
15520        }
15521        synchronized(mPackages) {
15522            final PackageParser.Package pkg = mPackages.get(packageName);
15523            if (pkg == null) {
15524                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15525                throw new IllegalArgumentException("Unknown package: " + packageName);
15526            }
15527            KeySetManagerService ksms = mSettings.mKeySetManagerService;
15528            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
15529        }
15530    }
15531
15532    @Override
15533    public KeySet getSigningKeySet(String packageName) {
15534        if (packageName == null) {
15535            return null;
15536        }
15537        synchronized(mPackages) {
15538            final PackageParser.Package pkg = mPackages.get(packageName);
15539            if (pkg == null) {
15540                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15541                throw new IllegalArgumentException("Unknown package: " + packageName);
15542            }
15543            if (pkg.applicationInfo.uid != Binder.getCallingUid()
15544                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
15545                throw new SecurityException("May not access signing KeySet of other apps.");
15546            }
15547            KeySetManagerService ksms = mSettings.mKeySetManagerService;
15548            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
15549        }
15550    }
15551
15552    @Override
15553    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
15554        if (packageName == null || ks == null) {
15555            return false;
15556        }
15557        synchronized(mPackages) {
15558            final PackageParser.Package pkg = mPackages.get(packageName);
15559            if (pkg == null) {
15560                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15561                throw new IllegalArgumentException("Unknown package: " + packageName);
15562            }
15563            IBinder ksh = ks.getToken();
15564            if (ksh instanceof KeySetHandle) {
15565                KeySetManagerService ksms = mSettings.mKeySetManagerService;
15566                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
15567            }
15568            return false;
15569        }
15570    }
15571
15572    @Override
15573    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
15574        if (packageName == null || ks == null) {
15575            return false;
15576        }
15577        synchronized(mPackages) {
15578            final PackageParser.Package pkg = mPackages.get(packageName);
15579            if (pkg == null) {
15580                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15581                throw new IllegalArgumentException("Unknown package: " + packageName);
15582            }
15583            IBinder ksh = ks.getToken();
15584            if (ksh instanceof KeySetHandle) {
15585                KeySetManagerService ksms = mSettings.mKeySetManagerService;
15586                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
15587            }
15588            return false;
15589        }
15590    }
15591
15592    public void getUsageStatsIfNoPackageUsageInfo() {
15593        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
15594            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
15595            if (usm == null) {
15596                throw new IllegalStateException("UsageStatsManager must be initialized");
15597            }
15598            long now = System.currentTimeMillis();
15599            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
15600            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
15601                String packageName = entry.getKey();
15602                PackageParser.Package pkg = mPackages.get(packageName);
15603                if (pkg == null) {
15604                    continue;
15605                }
15606                UsageStats usage = entry.getValue();
15607                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
15608                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
15609            }
15610        }
15611    }
15612
15613    /**
15614     * Check and throw if the given before/after packages would be considered a
15615     * downgrade.
15616     */
15617    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
15618            throws PackageManagerException {
15619        if (after.versionCode < before.mVersionCode) {
15620            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15621                    "Update version code " + after.versionCode + " is older than current "
15622                    + before.mVersionCode);
15623        } else if (after.versionCode == before.mVersionCode) {
15624            if (after.baseRevisionCode < before.baseRevisionCode) {
15625                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15626                        "Update base revision code " + after.baseRevisionCode
15627                        + " is older than current " + before.baseRevisionCode);
15628            }
15629
15630            if (!ArrayUtils.isEmpty(after.splitNames)) {
15631                for (int i = 0; i < after.splitNames.length; i++) {
15632                    final String splitName = after.splitNames[i];
15633                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
15634                    if (j != -1) {
15635                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
15636                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15637                                    "Update split " + splitName + " revision code "
15638                                    + after.splitRevisionCodes[i] + " is older than current "
15639                                    + before.splitRevisionCodes[j]);
15640                        }
15641                    }
15642                }
15643            }
15644        }
15645    }
15646
15647    private static class MoveCallbacks extends Handler {
15648        private static final int MSG_CREATED = 1;
15649        private static final int MSG_STATUS_CHANGED = 2;
15650
15651        private final RemoteCallbackList<IPackageMoveObserver>
15652                mCallbacks = new RemoteCallbackList<>();
15653
15654        private final SparseIntArray mLastStatus = new SparseIntArray();
15655
15656        public MoveCallbacks(Looper looper) {
15657            super(looper);
15658        }
15659
15660        public void register(IPackageMoveObserver callback) {
15661            mCallbacks.register(callback);
15662        }
15663
15664        public void unregister(IPackageMoveObserver callback) {
15665            mCallbacks.unregister(callback);
15666        }
15667
15668        @Override
15669        public void handleMessage(Message msg) {
15670            final SomeArgs args = (SomeArgs) msg.obj;
15671            final int n = mCallbacks.beginBroadcast();
15672            for (int i = 0; i < n; i++) {
15673                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
15674                try {
15675                    invokeCallback(callback, msg.what, args);
15676                } catch (RemoteException ignored) {
15677                }
15678            }
15679            mCallbacks.finishBroadcast();
15680            args.recycle();
15681        }
15682
15683        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
15684                throws RemoteException {
15685            switch (what) {
15686                case MSG_CREATED: {
15687                    callback.onCreated(args.argi1, (Bundle) args.arg2);
15688                    break;
15689                }
15690                case MSG_STATUS_CHANGED: {
15691                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
15692                    break;
15693                }
15694            }
15695        }
15696
15697        private void notifyCreated(int moveId, Bundle extras) {
15698            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
15699
15700            final SomeArgs args = SomeArgs.obtain();
15701            args.argi1 = moveId;
15702            args.arg2 = extras;
15703            obtainMessage(MSG_CREATED, args).sendToTarget();
15704        }
15705
15706        private void notifyStatusChanged(int moveId, int status) {
15707            notifyStatusChanged(moveId, status, -1);
15708        }
15709
15710        private void notifyStatusChanged(int moveId, int status, long estMillis) {
15711            Slog.v(TAG, "Move " + moveId + " status " + status);
15712
15713            final SomeArgs args = SomeArgs.obtain();
15714            args.argi1 = moveId;
15715            args.argi2 = status;
15716            args.arg3 = estMillis;
15717            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
15718
15719            synchronized (mLastStatus) {
15720                mLastStatus.put(moveId, status);
15721            }
15722        }
15723    }
15724
15725    private final class OnPermissionChangeListeners extends Handler {
15726        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
15727
15728        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
15729                new RemoteCallbackList<>();
15730
15731        public OnPermissionChangeListeners(Looper looper) {
15732            super(looper);
15733        }
15734
15735        @Override
15736        public void handleMessage(Message msg) {
15737            switch (msg.what) {
15738                case MSG_ON_PERMISSIONS_CHANGED: {
15739                    final int uid = msg.arg1;
15740                    handleOnPermissionsChanged(uid);
15741                } break;
15742            }
15743        }
15744
15745        public void addListenerLocked(IOnPermissionsChangeListener listener) {
15746            mPermissionListeners.register(listener);
15747
15748        }
15749
15750        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
15751            mPermissionListeners.unregister(listener);
15752        }
15753
15754        public void onPermissionsChanged(int uid) {
15755            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
15756                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
15757            }
15758        }
15759
15760        private void handleOnPermissionsChanged(int uid) {
15761            final int count = mPermissionListeners.beginBroadcast();
15762            try {
15763                for (int i = 0; i < count; i++) {
15764                    IOnPermissionsChangeListener callback = mPermissionListeners
15765                            .getBroadcastItem(i);
15766                    try {
15767                        callback.onPermissionsChanged(uid);
15768                    } catch (RemoteException e) {
15769                        Log.e(TAG, "Permission listener is dead", e);
15770                    }
15771                }
15772            } finally {
15773                mPermissionListeners.finishBroadcast();
15774            }
15775        }
15776    }
15777
15778    private class PackageManagerInternalImpl extends PackageManagerInternal {
15779        @Override
15780        public void setLocationPackagesProvider(PackagesProvider provider) {
15781            synchronized (mPackages) {
15782                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
15783            }
15784        }
15785
15786        @Override
15787        public void setImePackagesProvider(PackagesProvider provider) {
15788            synchronized (mPackages) {
15789                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
15790            }
15791        }
15792
15793        @Override
15794        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
15795            synchronized (mPackages) {
15796                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
15797            }
15798        }
15799    }
15800}
15801